context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright Bastian Eicher // Licensed under the MIT License using System.Reflection; using System.Text; namespace NanoByte.Common.Streams; /// <summary> /// Provides <see cref="Stream"/>-related helper methods. /// </summary> public static class StreamUtils { /// <summary> /// Reads a fixed number of bytes from a stream starting from the current offset. /// </summary> /// <param name="stream">The stream to read from.</param> /// <param name="count">The number of bytes to read.</param> /// <returns>The bytes read from the stream.</returns> /// <exception cref="IOException">The desired number of bytes could not be read from the stream.</exception> public static byte[] Read(this Stream stream, int count) => stream.TryRead(count) ?? throw new IOException(string.Format(Resources.UnableToReadBytesFromStream, count)); /// <summary> /// Reads a sequence of bytes from the stream. /// </summary> /// <param name="stream">The stream to read from.</param> /// <param name="buffer">The buffer to read the bytes into.</param> /// <returns>The bytes read from the stream.</returns> /// <exception cref="IOException">The desired number of bytes could not be read from the stream.</exception> public static int Read(this Stream stream, ArraySegment<byte> buffer) { #region Sanity checks if (stream == null) throw new ArgumentNullException(nameof(stream)); #endregion if (buffer.Array == null) return 0; return stream.Read(buffer.Array!, buffer.Offset, buffer.Count); } /// <summary> /// Reads a fixed number of bytes from a stream starting from the current offset. /// </summary> /// <param name="stream">The stream to read from.</param> /// <param name="count">The number of bytes to read.</param> /// <returns>The bytes read from the stream; <c>null</c> if the desired number of bytes could not be read from the stream.</returns> public static byte[]? TryRead(this Stream stream, int count) { #region Sanity checks if (stream == null) throw new ArgumentNullException(nameof(stream)); #endregion byte[] buffer = new byte[count]; int offset = 0; while (offset < count) { int read = stream.Read(buffer, offset, count - offset); if (read == 0) return null; offset += read; } return buffer; } /// <summary> /// Reads the entire content of a stream. Seeks to the beginning of the stream if <see cref="Stream.CanSeek"/>. /// </summary> /// <param name="stream">The stream to read from.</param> /// <returns>The entire content of the stream.</returns> public static ArraySegment<byte> ReadAll(this Stream stream) { #region Sanity checks if (stream == null) throw new ArgumentNullException(nameof(stream)); #endregion if (stream.CanSeek) stream.Position = 0; long GetLength() { try { return stream.Length > 0 ? stream.Length : 64; } catch (Exception) { return 64; } } byte[] buffer = new byte[GetLength()]; int count = 0; while (true) { if (buffer.Length == count) { byte[] newBuffer = new byte[buffer.Length * 2]; Array.Copy(buffer, newBuffer, count); buffer = newBuffer; } int read = stream.Read(buffer, count, buffer.Length - count); count += read; if (read == 0) return new ArraySegment<byte>(buffer, 0, count); } } /// <summary> /// Skips a number of bytes in the stream. /// Uses <see cref="Stream.Seek"/> if supported, <see cref="Stream.Read(byte[],int,int)"/> otherwise. /// </summary> /// <param name="stream">The stream to read from.</param> /// <param name="count">The number of bytes to skip.</param> /// <exception cref="IOException">The desired number of bytes could not be skipped in the stream.</exception> public static void Skip(this Stream stream, int count) { #region Sanity checks if (stream == null) throw new ArgumentNullException(nameof(stream)); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), "Must not be negative."); #endregion if (stream.CanSeek) { stream.Seek(count, SeekOrigin.Current); return; } #if NET20 || NET40 stream.Read(count); #else var pool = System.Buffers.ArrayPool<byte>.Shared; byte[] buffer = pool.Rent(Math.Min(count, 64)); try { int toRead = count; while (toRead > 0) { int read = stream.Read(buffer, 0, Math.Min(toRead, buffer.Length)); if (read == 0) throw new IOException(string.Format(Resources.UnableToReadBytesFromStream, count)); toRead -= read; } } finally { pool.Return(buffer); } #endif } /// <summary> /// Writes the entire contents of an array to a stream. /// </summary> /// <param name="stream">The stream to write to.</param> /// <param name="data">The array containing the bytes to write.</param> public static void Write(this Stream stream, params byte[] data) { #region Sanity checks if (stream == null) throw new ArgumentNullException(nameof(stream)); if (data == null) throw new ArgumentNullException(nameof(data)); #endregion #if NETFRAMEWORK stream.Write(data, 0, data.Length); #else stream.Write(data); #endif } /// <summary> /// Writes the entire contents of a buffer to a stream. /// </summary> /// <param name="stream">The stream to write to.</param> /// <param name="buffer">The buffer containing the bytes to write.</param> public static void Write(this Stream stream, ArraySegment<byte> buffer) { #region Sanity checks if (stream == null) throw new ArgumentNullException(nameof(stream)); #endregion if (buffer.Array == null) return; stream.Write(buffer.Array, buffer.Offset, buffer.Count); } /// <summary> /// The entire content of a stream as an array. Seeks to the beginning of the stream if <see cref="Stream.CanSeek"/>. Avoids copying the underlying array if possible. /// </summary> public static byte[] AsArray(this Stream stream) { #region Sanity checks if (stream == null) throw new ArgumentNullException(nameof(stream)); #endregion #if !NET20 && !NET40 && !NET45 if (stream is MemoryStream memory && memory.TryGetBuffer(out var segment)) return segment.AsArray(); #endif return stream.ReadAll().AsArray(); } /// <summary> /// Copies the entire content of a stream to a <see cref="MemoryStream"/>. Seeks to the beginning of the stream if <see cref="Stream.CanSeek"/>. /// </summary> /// <param name="stream">The stream to read from.</param> /// <returns>A new stream or the original <paramref name="stream"/> if it was already a <see cref="MemoryStream"/>.</returns> public static MemoryStream ToMemory(this Stream stream) { #region Sanity checks if (stream == null) throw new ArgumentNullException(nameof(stream)); #endregion var read = stream.ReadAll(); return new MemoryStream(read.Array!, read.Offset, read.Count, true, true); } /// <summary> /// Copies the content of one stream to another. Seeks to the beginning of the <paramref name="source"/> stream if <see cref="Stream.CanSeek"/>. /// </summary> /// <param name="source">The source stream to copy from.</param> /// <param name="destination">The destination stream to copy to.</param> [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] public static void CopyToEx(this Stream source, Stream destination) { #region Sanity checks if (source == null) throw new ArgumentNullException(nameof(source)); if (destination == null) throw new ArgumentNullException(nameof(destination)); #endregion if (source.CanSeek) source.Position = 0; #if NET20 var buffer = new byte[81920]; int read; long sum = 0; do { sum += read = source.Read(buffer, 0, buffer.Length); destination.Write(buffer, 0, read); } while (read != 0); #else source.CopyTo(destination); #endif } /// <summary> /// Writes the entire content of a stream to a file. Seeks to the beginning of the <paramref name="stream"/> if <see cref="Stream.CanSeek"/>. /// </summary> /// <param name="stream">The stream to read from.</param> /// <param name="path">The path of the file to write.</param> public static void CopyToFile(this Stream stream, [Localizable(false)] string path) { #region Sanity checks if (stream == null) throw new ArgumentNullException(nameof(stream)); if (string.IsNullOrEmpty(path)) throw new ArgumentNullException(nameof(path)); #endregion using var fileStream = File.Create(path); stream.CopyToEx(fileStream); } #if !NET20 && !NET40 /// <summary> /// Adds seek buffering to a stream unless it already <see cref="Stream.CanSeek"/>. /// </summary> /// <param name="stream">The stream.</param> /// <param name="bufferSize">The maximum number of bytes to buffer for seeking.</param> [Pure] public static Stream WithSeekBuffer(this Stream stream, int bufferSize = SeekBufferStream.DefaultBufferSize) { #region Sanity checks if (stream == null) throw new ArgumentNullException(nameof(stream)); #endregion return stream.CanSeek ? stream : new SeekBufferStream(stream, bufferSize); } #endif /// <summary> /// Overrides the value returned by <see cref="Stream.Length"/>. /// </summary> /// <param name="stream">The stream.</param> /// <param name="length">The value to return for <see cref="Stream.Length"/>.</param> [Pure] public static Stream WithLength(this Stream stream, long length) { var result = new ProgressStream(stream); result.SetLength(length); return result; } /// <summary> /// Reads the entire content of a stream as string data. Seeks to the beginning of the stream if <see cref="Stream.CanSeek"/>. /// </summary> /// <param name="stream">The stream to read from.</param> /// <param name="encoding">The encoding of the string; leave <c>null</c> to default to <see cref="EncodingUtils.Utf8"/>.</param> /// <returns>A entire content of the stream.</returns> public static string ReadToString(this Stream stream, Encoding? encoding = null) { #region Sanity checks if (stream == null) throw new ArgumentNullException(nameof(stream)); #endregion if (stream.CanSeek) stream.Position = 0; var reader = new StreamReader(stream, encoding ?? EncodingUtils.Utf8); return reader.ReadToEnd(); } /// <summary> /// Creates a new <see cref="MemoryStream"/> and fills it with string data. /// </summary> /// <param name="data">The data to fill the stream with.</param> /// <param name="encoding">The encoding of the string; leave <c>null</c> to default to <see cref="EncodingUtils.Utf8"/>.</param> /// <returns>A filled stream with the position set to zero.</returns> [Pure] public static MemoryStream ToStream(this string data, Encoding? encoding = null) => new((encoding ?? EncodingUtils.Utf8).GetBytes(data ?? throw new ArgumentNullException(nameof(data)))); /// <summary> /// Creates a new <see cref="MemoryStream"/> using the existing array as the underlying storage. /// </summary> /// <param name="array">The array to create the stream from.</param> /// <param name="writable">Controls whether the stream is writable (i.e., can modify the array).</param> [Pure] public static MemoryStream ToStream(this byte[] array, bool writable = false) => new(array ?? throw new ArgumentNullException(nameof(array)), writable); /// <summary> /// Creates a new <see cref="MemoryStream"/> using the existing array segment as the underlying storage. /// </summary> /// <param name="segment">The array segment to create the stream from.</param> /// <param name="writable">Controls whether the stream is writable (i.e., can modify the array).</param> [Pure] public static MemoryStream ToStream(this ArraySegment<byte> segment, bool writable = false) => new( segment.Array ?? throw new ArgumentNullException(nameof(segment)), segment.Offset, segment.Count, writable); /// <summary> /// Returns an embedded resource as a stream. /// </summary> /// <param name="type">A type that is located in the same namespace as the embedded resource.</param> /// <param name="name">The name of the embedded resource.</param> /// <exception cref="ArgumentException">The specified embedded resource does not exist.</exception> [Pure] public static Stream GetEmbeddedStream(this Type type, [Localizable(false)] string name) { #region Sanity checks if (type == null) throw new ArgumentNullException(nameof(type)); if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name)); #endregion var stream = Assembly.GetAssembly(type)?.GetManifestResourceStream(type, name); if (stream == null) throw new ArgumentException($"Embedded resource '{name}' not found.", nameof(name)); return stream; } /// <summary> /// Returns an embedded resource as a byte array. /// </summary> /// <param name="type">A type that is located in the same namespace as the embedded resource.</param> /// <param name="name">The name of the embedded resource.</param> /// <exception cref="ArgumentException">The specified embedded resource does not exist.</exception> [Pure] public static byte[] GetEmbeddedBytes(this Type type, [Localizable(false)] string name) => type.GetEmbeddedStream(name).AsArray(); /// <summary> /// Returns an embedded resource as a string. /// </summary> /// <param name="type">A type that is located in the same namespace as the embedded resource.</param> /// <param name="name">The name of the embedded resource.</param> /// <param name="encoding">The encoding of the string; leave <c>null</c> to default to <see cref="EncodingUtils.Utf8"/>.</param> /// <exception cref="ArgumentException">The specified embedded resource does not exist.</exception> [Pure] public static string GetEmbeddedString(this Type type, [Localizable(false)] string name, Encoding? encoding = null) { #region Sanity checks if (type == null) throw new ArgumentNullException(nameof(type)); if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name)); #endregion using var stream = type.GetEmbeddedStream(name); return stream.ReadToString(encoding); } /// <summary> /// Copies an embedded resource to a file. /// </summary> /// <param name="type">A type that is located in the same namespace as the embedded resource.</param> /// <param name="name">The name of the embedded resource.</param> /// <param name="path">The path of the file to write.</param> /// <exception cref="ArgumentException">The specified embedded resource does not exist.</exception> public static void CopyEmbeddedToFile(this Type type, [Localizable(false)] string name, [Localizable(false)] string path) { #region Sanity checks if (type == null) throw new ArgumentNullException(nameof(type)); if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name)); #endregion using var stream = type.GetEmbeddedStream(name); stream.CopyToFile(path); } }
/* Copyright 2014 Google Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Concurrent; using System.Collections.Generic; using DriveProxy.Utils; using Google.Apis.Drive.v2.Data; namespace DriveProxy.API { partial class DriveService { private class Journal : IDisposable { private readonly string _lastLargestChangeId = null; private string _lastSyncedRootFolderId; private bool _loadedFromDisk; private bool _loadedFromWeb; private long _loadedLargestChangeId; private string _loadedRootFolderId = ""; private bool _loadingFromDisk; private bool _loadingFromWeb; private int _processCount; private DateTime _syncChangesFromWebDateTime = default(DateTime); private SyncState _syncState = SyncState.Unknown; private bool _syncingChangesFromWeb; private bool _syncingFromWeb; private bool _syncingToDisk; private ConcurrentDictionary<string, Item> _files; private ConcurrentDictionary<string, ConcurrentDictionary<string, Item>> _filesByParent; private bool _multiThreaded = true; private Mutex _mutex; private Mutex _mutexSyncToDisk; private ConcurrentDictionary<string, Item> Files { get { return _files ?? (_files = new ConcurrentDictionary<string, Item>()); } set { _files = value; } } private ConcurrentDictionary<string, ConcurrentDictionary<string, Item>> FilesByParent { get { return _filesByParent ?? (_filesByParent = new ConcurrentDictionary<string, ConcurrentDictionary<string, Item>>()); } set { _filesByParent = value; } } private Mutex Mutex { get { return _mutex ?? (_mutex = new Mutex()); } } private bool MultiThreaded { get { return _multiThreaded; } set { _multiThreaded = value; } } public bool Loading { get { if (LoadingFromDisk || LoadingFromWeb) { return true; } return false; } } public bool Loaded { get { if (LoadedFromDisk && LoadedFromWeb) { return true; } return false; } } public bool Syncing { get { if (SyncingFromWeb || SyncingChangesFromWeb || SyncingToDisk) { return true; } return false; } } public bool Processing { get { if (Loading || Syncing) { return true; } return false; } } public bool LoadingFromDisk { get { return _loadingFromDisk; } } public bool LoadedFromDisk { get { return _loadedFromDisk; } } public bool LoadingFromWeb { get { return _loadingFromWeb; } } public bool LoadedFromWeb { get { return _loadedFromWeb; } } public bool SyncingFromWeb { get { return _syncingFromWeb; } } public bool SyncingChangesFromWeb { get { return _syncingChangesFromWeb; } } public bool SyncingToDisk { get { return _syncingToDisk; } } private Mutex MutexSyncToDisk { get { return _mutexSyncToDisk ?? (_mutexSyncToDisk = new Mutex()); } } public void Dispose() { try { Factory.Dispose(this); } catch (Exception exception) { Log.Error(exception, false); } } public static Journal Create() { return Factory.GetInstance(); } public static void Load() { Factory.Load(); } public static void Refresh() { Factory.Refresh(); } public static bool HasSynced(bool startSync) { return Factory.HasSynced(startSync); } public static bool RemoveItem(string fileId) { return Factory.RemoveItem(fileId); } public static void Stop() { Factory.Stop(); } public static void Cache(File file, List<File> children) { Factory.Cache(file, children); } private bool _LoadFromDisk() { try { if (LoadedFromDisk) { return true; } Mutex.Wait(); try { _UpdateProcessCount("_LoadFromDisk", 1); if (LoadedFromDisk) { return true; } _loadingFromDisk = true; try { if (FileExists(Settings.RootIdFilePath)) { _loadedRootFolderId = System.IO.File.ReadAllText(Settings.RootIdFilePath); } if (FileExists(Settings.LastChangeIdPath)) { string loadedLargestChangeId = System.IO.File.ReadAllText(Settings.LastChangeIdPath); _loadedLargestChangeId = GetLong(loadedLargestChangeId); } Files = new ConcurrentDictionary<string, Item>(); FilesByParent = new ConcurrentDictionary<string, ConcurrentDictionary<string, Item>>(); if (String.IsNullOrEmpty(_loadedRootFolderId) || _loadedLargestChangeId == 0) { try { _loadedRootFolderId = ""; _loadedLargestChangeId = 0; } catch { } } } finally { _loadingFromDisk = false; _UpdateProcessCount("_LoadFromDisk", -1); } _loadedFromDisk = true; } finally { Mutex.Release(); } return true; } catch (Exception exception) { Log.Error(exception, false); return false; } } private Item _LoadFromDisk(string fileId) { try { string journalFilePath = ""; Item item = null; try { journalFilePath = Settings.GetJournalFilePath(fileId + ".item", false); if (!FileExists(journalFilePath)) { return null; } DateTime lastWriteTime = GetFileLastWriteTime(journalFilePath); using ( System.IO.FileStream fileStream = OpenFile(journalFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)) { using (var streamReader = new System.IO.StreamReader(fileStream)) { using (Newtonsoft.Json.JsonReader jsonReader = new Newtonsoft.Json.JsonTextReader(streamReader)) { var jsonSerializer = new Newtonsoft.Json.JsonSerializer(); item = (Item)jsonSerializer.Deserialize(jsonReader, typeof (Item)); } } } if (item == null || item.Status != ItemStatus.Cached) { throw new Exception("Json parsing failed"); } _AddItem(item); } catch (Exception exception) { Log.Error(exception, false, false); try { DeleteFile(journalFilePath); } catch (Exception exception2) { Log.Error(exception2, false, false); } return null; } Item[] children = null; try { journalFilePath = Settings.GetJournalFilePath(fileId + ".children", false); if (!FileExists(journalFilePath)) { return null; } using ( System.IO.FileStream fileStream = OpenFile(journalFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)) { using (var streamReader = new System.IO.StreamReader(fileStream)) { using (Newtonsoft.Json.JsonReader jsonReader = new Newtonsoft.Json.JsonTextReader(streamReader)) { var jsonSerializer = new Newtonsoft.Json.JsonSerializer(); children = (Item[])jsonSerializer.Deserialize(jsonReader, typeof (Item[])); } } } if (children == null) { throw new Exception("Json parsing failed"); } foreach (Item child in children) { _AddItem(child); } } catch (Exception exception) { Log.Error(exception, false, false); try { DeleteFile(journalFilePath); } catch (Exception exception2) { Log.Error(exception2, false, false); } return null; } return item; } catch (Exception exception) { Log.Error(exception, false); return null; } } private void _LoadFromDiskAsync() { try { if (MultiThreaded) { new System.Threading.Thread(_LoadFromDisk_Async).Start(); } else { _LoadFromDisk_Async(); } } catch (Exception exception) { Log.Error(exception, false); } } private void _LoadFromDisk_Async() { try { _LoadFromDisk(); } catch (Exception exception) { Log.Error(exception, false); } } private SyncState _CheckSyncState() { try { if (_syncState != SyncState.Unknown) { return _syncState; } Mutex.Wait(); try { _UpdateProcessCount("_CheckSyncState", 1); try { if (_loadedRootFolderId != RootFolderId) { _loadedRootFolderId = RootFolderId; _loadedLargestChangeId = LargestChangeId; Files.Clear(); FilesByParent.Clear(); _syncState = SyncState.SyncFromWeb; } else if (_loadedLargestChangeId != LargestChangeId) { // used as StartChangeId in SyncChangesFromWeb _largestChangeId = _loadedLargestChangeId; _syncState = SyncState.SyncChangesFromWeb; } else { _syncState = SyncState.SyncedToWeb; } } finally { _UpdateProcessCount("_CheckSyncState", -1); } } finally { Mutex.Release(); } return _syncState; } catch (Exception exception) { Log.Error(exception, false); return _syncState; } } private bool _LoadFromWeb() { try { if (LoadedFromWeb) { return true; } if (!_LoadFromDisk()) { Log.Error("Cannot load Journal from web - Could not load Journal from disk."); return false; } if (!IsSignedIn) { Log.Error("Cannot load Journal from web - Not signed in."); return false; } if (LoadingFromWeb) { Log.Error("Cannot load Journal from web - Already loading from web."); return false; } Mutex.Wait(); try { _UpdateProcessCount("_LoadFromWeb", 1); _loadingFromWeb = true; try { SyncState syncState = _CheckSyncState(); if (syncState == SyncState.SyncFromWeb) { //if (_SyncFromWeb(RootFolderId, true) == null) //{ // Log.Error("Cannot load Journal from web - Could not sync from web."); // return false; //} } else if (syncState == SyncState.SyncChangesFromWeb) { //if (!_SyncChangesFromWeb()) //{ // Log.Error("Cannot load Journal from web - Could not sync changes from web."); // return false; //} } } finally { _loadingFromWeb = false; _UpdateProcessCount("_LoadFromWeb", -1); } _loadedFromWeb = true; _syncState = SyncState.SyncedToWeb; } finally { Mutex.Release(); } return true; } catch (Exception exception) { Log.Error(exception, false); return false; } } private void _LoadFromWebAsync() { try { if (MultiThreaded) { new System.Threading.Thread(_LoadFromWeb_Async).Start(); } else { _LoadFromWeb_Async(); } } catch (Exception exception) { Log.Error(exception, false); } } private void _LoadFromWeb_Async() { try { _LoadFromWeb(); } catch (Exception exception) { Log.Error(exception, false); } } private Item _SyncFromWeb(string fileId, bool getChildren) { try { if (!IsSignedIn) { Log.Error("Cannot sync Journal from web - Not signed in."); return null; } Mutex.Wait(); try { _UpdateProcessCount("_SyncFromWeb", 1); _syncingFromWeb = true; Item item = null; try { fileId = GetFileId(fileId); File file = _GetFile(fileId); if (file == null) { Log.Error("Cannot sync Journal from web - GetFile returned null."); return null; } List<File> children = null; if (getChildren) { children = _ListFiles(fileId, true); } item = _SyncFromData(file, children); } finally { _syncingFromWeb = false; _UpdateProcessCount("_SyncFromWeb", -1); } return item; } finally { Mutex.Release(); } } catch (Exception exception) { Log.Error(exception, false); return null; } } private Item _SyncFromData(File file, List<File> children = null) { try { Mutex.Wait(); try { _UpdateProcessCount("_SyncFromFile", 1); Item item = null; try { _RemoveItem(file.Id); item = Files.GetOrAdd(file.Id, new Item()); item.Status = ItemStatus.Pending; _BindToItem(item, file); if (!IsFolder(item.File)) { item.Status = ItemStatus.Cached; } else if (children != null) { foreach (File child in children) { _AddItem(child); } item.Status = ItemStatus.Cached; List<Item> itemChildren = GetChildrenItems(file.Id); _SyncToDiskAsync(item, itemChildren); } } finally { _UpdateProcessCount("_SyncFromFile", -1); } _loadedFromWeb = true; _syncState = SyncState.SyncedToWeb; return item; } finally { Mutex.Release(); } } catch (Exception exception) { Log.Error(exception, false); return null; } } private void _SyncFromDataAsync(Item item, List<Item> children) { try { if (MultiThreaded) { new System.Threading.Thread(_SyncFromData_Async).Start(new object[] {item, children}); } else { _SyncFromData_Async(new object[] {item, children}); } } catch (Exception exception) { Log.Error(exception, false); } } private void _SyncFromData_Async(object parameter) { try { var args = (object[])parameter; var file = (File)args[0]; var children = (List<File>)args[1]; _SyncFromData(file, children); } catch (Exception exception) { Log.Error(exception, false); } } private bool _SyncChangesFromWeb() { try { if (!LoadingFromWeb && !LoadedFromWeb) { Log.Error("Cannot sync Journal web changes - Cannot load from web."); return false; } if (!IsSignedIn) { Log.Error("Cannot sync Journal web changes - Not signed in."); return false; } Mutex.Wait(); try { _UpdateProcessCount("_SyncChangesFromWeb", 1); _syncingChangesFromWeb = true; try { TimeSpan timeSpan = DateTime.Now.Subtract(_syncChangesFromWebDateTime); if (timeSpan.TotalSeconds < 15) { Log.Information("Waiting to sync Journal (" + timeSpan.TotalSeconds + " seconds since last update)"); return true; } long largestChangeId = 0; List<Change> changes = _ListChanges(_largestChangeId, out largestChangeId); var changedItems = new Dictionary<string, Item>(); var changedParentIds = new List<string>(); foreach (Change change in changes) { if (change.Deleted.HasValue && change.Deleted.Value) { _RemoveItem(change.FileId); _RemoveFile(change.FileId); } string parentId = GetParentId(change.File); if (!Files.ContainsKey(parentId)) { continue; } if (!IsTrashed(change.File)) { Item item = _AddItem(change.File); if (IsFolder(item.File) && !changedItems.ContainsKey(item.File.Id)) { changedItems.Add(item.File.Id, item); } } else { _RemoveItem(change.FileId); _RemoveFile(change.FileId); } if (!String.IsNullOrEmpty(parentId) && !changedParentIds.Contains(parentId)) { changedParentIds.Add(parentId); } } foreach (string changedParentId in changedParentIds) { if (!changedItems.ContainsKey(changedParentId)) { _UpdateFile(changedParentId); } } foreach (Item changedItem in changedItems.Values) { _UpdateFile(changedItem); } _largestChangeId = largestChangeId; _syncChangesFromWebDateTime = DateTime.Now; } finally { _syncingChangesFromWeb = false; _UpdateProcessCount("_SyncChangesFromWeb", -1); } } finally { Mutex.Release(); } return true; } catch (Exception exception) { Log.Error(exception, false); return false; } } private void _UpdateFile(string fileId) { try { Item item = null; if (Files.TryGetValue(fileId, out item)) { _UpdateFile(item); } } catch (Exception exception) { Log.Error(exception); } } private void _UpdateFile(Item item) { try { if (item.Status == ItemStatus.Pending) { return; } List<Item> children = GetChildrenItems(item.File.Id); _SyncToDiskAsync(item, children); } catch (Exception exception) { Log.Error(exception); } } private bool _SyncToDisk(Item item, List<Item> children) { try { if (_cancelProcessing) { return false; } if (String.IsNullOrEmpty(RootFolderId)) { Log.Error("Cannot sync Journal to disk - RootFolderId is blank."); return false; } MutexSyncToDisk.Wait(); try { _UpdateProcessCount("_SyncToDisk", 1); _syncingToDisk = true; try { if (_lastSyncedRootFolderId == null || _lastSyncedRootFolderId != RootFolderId) { System.IO.File.WriteAllText(Settings.RootIdFilePath, RootFolderId); _lastSyncedRootFolderId = RootFolderId; } if (_lastLargestChangeId == null || _lastLargestChangeId != RootFolderId) { System.IO.File.WriteAllText(Settings.LastChangeIdPath, LargestChangeId.ToString()); _lastSyncedRootFolderId = RootFolderId; } string journalFilePath = Settings.GetJournalFilePath(item.File.Id + ".item"); using ( System.IO.FileStream fileStream = OpenFile(journalFilePath, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.Write)) { using (var streamWriter = new System.IO.StreamWriter(fileStream)) { using (Newtonsoft.Json.JsonWriter jsonWriter = new Newtonsoft.Json.JsonTextWriter(streamWriter)) { jsonWriter.Formatting = Newtonsoft.Json.Formatting.None; var jsonSerializer = new Newtonsoft.Json.JsonSerializer(); jsonSerializer.Serialize(jsonWriter, item); } } } System.IO.File.SetCreationTime(journalFilePath, DateTime.Now); journalFilePath = Settings.GetJournalFilePath(item.File.Id + ".children"); using ( System.IO.FileStream fileStream = OpenFile(journalFilePath, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.Write)) { using (var streamWriter = new System.IO.StreamWriter(fileStream)) { using (Newtonsoft.Json.JsonWriter jsonWriter = new Newtonsoft.Json.JsonTextWriter(streamWriter)) { jsonWriter.Formatting = Newtonsoft.Json.Formatting.None; var jsonSerializer = new Newtonsoft.Json.JsonSerializer(); jsonSerializer.Serialize(jsonWriter, children); } } } System.IO.File.SetCreationTime(journalFilePath, DateTime.Now); } finally { _syncingToDisk = false; _UpdateProcessCount("_SyncToDisk", -1); } } finally { MutexSyncToDisk.Release(); } return true; } catch (Exception exception) { Log.Error(exception, false); return false; } } private void _SyncToDiskAsync(Item item, List<Item> children) { try { if (_cancelProcessing) { return; } if (MultiThreaded) { new System.Threading.Thread(_SyncToDisk_Async).Start(new object[] {item, children}); } else { _SyncToDisk_Async(new object[] {item, children}); } } catch (Exception exception) { Log.Error(exception, false); } } private void _SyncToDisk_Async(object parameter) { try { if (_cancelProcessing) { return; } var args = (object[])parameter; var item = (Item)args[0]; var children = (List<Item>)args[1]; _SyncToDisk(item, children); } catch (Exception exception) { Log.Error(exception, false); } } public void UpdateCachedData() { try { _syncChangesFromWebDateTime = default(DateTime); } catch (Exception exception) { Log.Error(exception, false); } } public File GetCachedFile(string fileId, bool getChildren, out List<File> children) { children = null; try { if (!_LoadFromWeb()) { Log.Error("Cannot get Journal cached file - Cannot load from web."); return null; } Mutex.Wait(); try { _UpdateProcessCount("GetCachedFile", 1); try { fileId = GetFileId(fileId); Item item = null; Files.TryGetValue(fileId, out item); bool isLoaded = false; if (item == null || item.Status == ItemStatus.Pending) { item = _LoadFromDisk(fileId); if (item != null && item.Status == ItemStatus.Cached) { if (!_SyncChangesFromWeb()) { Log.Error("Cannot get Journal cached file - Cannot sync web changes."); return null; } isLoaded = true; } } if (!isLoaded) { if (item == null) { item = _SyncFromWeb(fileId, getChildren); if (item == null) { Log.Error("Cannot get Journal cached file - Cannot sync from web."); return null; } } else if (item.Status == ItemStatus.Pending) { item = _SyncFromWeb(fileId, getChildren); if (item == null) { Log.Error("Cannot get Journal cached file - Cannot sync from web."); return null; } } else if (item.Status == ItemStatus.Cached) { if (!_SyncChangesFromWeb()) { Log.Error("Cannot get Journal cached file - Cannot sync web changes."); return null; } } } if (IsFolder(item.File) && getChildren) { children = GetChildrenFiles(fileId); } return item.File; } finally { _UpdateProcessCount("GetCachedFile", -1); } } finally { Mutex.Release(); } } catch (Exception exception) { Log.Error(exception, false); return null; } } private Item _AddItem(File file) { try { Item item = Files.GetOrAdd(file.Id, new Item()); _BindToItem(item, file); return item; } catch (Exception exception) { Log.Error(exception); return null; } } private void _AddItem(Item item) { try { Files.GetOrAdd(item.File.Id, item); _BindToItem(item, item.File); } catch (Exception exception) { Log.Error(exception); } } private void _BindToItem(Item item, File file) { try { if (item.File != null && item.File.Parents != null && file.Parents != null) { if (item.File.Parents.Count > 0) { if (file.Parents.Count == 0 || file.Parents[0].Id != item.File.Parents[0].Id) { _RemoveFromParent(item); } } } item.Value = file; _AddToParent(item); } catch (Exception exception) { Log.Error(exception); } } private bool _AddToParent(Item item) { try { if (item.File == null || item.File.Parents == null) { return false; } if (item.File.Parents.Count > 0) { ParentReference parent = item.File.Parents[0]; ConcurrentDictionary<string, Item> itemParent = FilesByParent.GetOrAdd(parent.Id, new ConcurrentDictionary <string, Item>()); itemParent.GetOrAdd(item.File.Id, item); } return true; } catch (Exception exception) { Log.Error(exception); return false; } } private static bool _RemoveFile(string fileId) { try { if (!String.IsNullOrEmpty(fileId)) { string filePath = Settings.GetJournalFilePath(fileId + ".item", false); DeleteFile(filePath); filePath = Settings.GetJournalFilePath(fileId + ".children", false); DeleteFile(filePath); } return true; } catch (Exception exception) { Log.Error(exception); return false; } } private bool _RemoveItem(string fileId) { string parentId = null; return _RemoveItem(fileId, ref parentId); } private bool _RemoveItem(string fileId, ref string parentId) { try { parentId = null; Item item = null; if (Files.TryRemove(fileId, out item)) { _RemoveFromParent(item, ref parentId); } return true; } catch (Exception exception) { Log.Error(exception); return false; } } private bool _RemoveFromParent(Item item) { string parentId = null; return _RemoveFromParent(item, ref parentId); } private bool _RemoveFromParent(Item item, ref string parentId) { try { parentId = null; if (item.File == null) { return false; } if (item.File.Parents.Count > 0) { ParentReference parent = item.File.Parents[0]; ConcurrentDictionary<string, Item> itemParent = null; if (FilesByParent.TryGetValue(parent.Id, out itemParent)) { Item itemTemp = null; itemParent.TryRemove(item.File.Id, out itemTemp); parentId = parent.Id; } } return true; } catch (Exception exception) { Log.Error(exception); return false; } } private ConcurrentDictionary<string, Item> GetFilesByParent(string fileId) { try { ConcurrentDictionary<string, Item> itemChildren = null; FilesByParent.TryGetValue(fileId, out itemChildren); return itemChildren; } catch (Exception exception) { Log.Error(exception); return null; } } private List<Item> GetChildrenItems(string fileId) { try { ConcurrentDictionary<string, Item> itemChildren = GetFilesByParent(fileId); var children = new List<Item>(); if (itemChildren != null) { foreach (Item itemChild in itemChildren.Values) { if (!IsTrashed(itemChild.File)) { children.Add(itemChild); } } } return children; } catch (Exception exception) { Log.Error(exception); return null; } } private List<File> GetChildrenFiles(string fileId) { try { List<Item> itemChildren = GetChildrenItems(fileId); var children = new List<File>(); if (itemChildren != null) { foreach (Item itemChild in itemChildren) { children.Add(itemChild.File); } } return children; } catch (Exception exception) { Log.Error(exception); return null; } } private void _UpdateProcessCount(string functionName, int processCount) { try { if (Settings.LogLevel == LogType.All) { _processCount += processCount; if (_processCount < 0) { Debugger.Break(); Log.Error("PROCESS !ERROR! " + functionName + " - ProcessCount + " + processCount + " = " + _processCount); } else { Log.Information("Process " + functionName + " - ProcessCount + " + processCount + " = " + _processCount); } } } catch (Exception exception) { Log.Error(exception, false); } } private class Factory { private static Journal _journal; private static Mutex _mutex; private static Journal Journal { get { return _journal ?? (_journal = new Journal()); } set { _journal = value; } } private static Mutex Mutex { get { return _mutex ?? (_mutex = new Mutex()); } } public static Journal GetInstance() { try { return Journal; } catch (Exception exception) { Log.Error(exception); return null; } } public static void Load() { try { Journal._LoadFromDiskAsync(); } catch (Exception exception) { Log.Error(exception, false); } } public static void Dispose(Journal instance) { } public static void Refresh() { try { Mutex.Wait(); try { _rootFolderId = ""; _largestChangeId = 0; if (Journal != null) { Journal.Dispose(); Journal = null; } } finally { Mutex.Release(); } } catch (Exception exception) { Log.Error(exception, false); } } public static bool HasSynced(bool startSync) { try { Log.Information("Checking HasSynced"); SyncState syncState = Journal._CheckSyncState(); if (syncState == SyncState.SyncFromWeb) { Log.Information("Starting Sync From Web"); if (startSync) { Journal._LoadFromWebAsync(); } else { Log.Information("Bypassing Sync (sync not requested)"); } } else if (syncState == SyncState.SyncChangesFromWeb) { Log.Information("Starting Sync Changes From Web"); Journal._LoadFromWeb(); return true; } else if (syncState == SyncState.SyncedToWeb) { Log.Information("Already Synced To Web"); return true; } return false; } catch (Exception exception) { Log.Error(exception, false); return false; } } public static bool RemoveItem(string fileId) { try { string parentId = null; if (!Journal._RemoveItem(fileId, ref parentId)) { return false; } _RemoveFile(fileId); Journal._UpdateFile(parentId); return true; } catch (Exception exception) { Log.Error(exception, false); return false; } } public static void Stop() { try { _journal = new Journal(); } catch (Exception exception) { Log.Error(exception, false, false); } } public static void Cache(File file, List<File> children) { try { Journal._SyncFromData(file, children); } catch (Exception exception) { Log.Error(exception, false); } } } [Serializable] private class Item { public Item() { Status = ItemStatus.Pending; Value = null; } public ItemStatus Status { get; set; } public File Value { get; set; } public File File { get { return Value; } } public override string ToString() { if (File != null) { return File.Title; } return "null"; } } [Flags] private enum ItemStatus { Unknown = 0, Pending = 1, Cached = 2, DoesNotExist = 3 } private enum SyncState { Unknown, SyncFromWeb, SyncChangesFromWeb, SyncedToWeb } } } }
using System.Linq; using System.Threading.Tasks; using Marten.Testing.Events.Projections; using Marten.Testing.Harness; using Shouldly; using Xunit; namespace Marten.Testing.Events { [Collection("flexible_metadata")] public class flexible_event_metadata : OneOffConfigurationsContext { private QuestStarted started = new QuestStarted { Name = "Find the Orb" }; private MembersJoined joined = new MembersJoined { Day = 2, Location = "Faldor's Farm", Members = new string[] { "Garion", "Polgara", "Belgarath" } }; private MonsterSlayed slayed = new MonsterSlayed { Name = "Troll" }; [Fact] public async Task check_metadata_correlation_id_enabled() { StoreOptions(_ => _.Events.MetadataConfig.CorrelationIdEnabled = true); const string correlationId = "test-correlation-id"; theSession.CorrelationId = correlationId; var streamId = theSession.Events .StartStream<QuestParty>(started, joined, slayed).Id; await theSession.SaveChangesAsync(); var events = await theSession.Events.FetchStreamAsync(streamId); foreach (var @event in events) { @event.CorrelationId.ShouldBe(correlationId); } } [Fact] public async Task check_search_with_correlation_id() { StoreOptions(_ => _.Events.MetadataConfig.CorrelationIdEnabled = true); const string correlationId = "test-correlation-id"; theSession.CorrelationId = correlationId; var streamId = theSession.Events.StartStream<QuestParty>(started, joined, slayed).Id; await theSession.SaveChangesAsync(); var events = await theSession.Events.QueryAllRawEvents() .Where(x => x.CorrelationId == correlationId) .ToListAsync(); events.Count.ShouldBe(3); events[0].StreamId.ShouldBe(streamId); events[1].StreamId.ShouldBe(streamId); events[2].StreamId.ShouldBe(streamId); } [Fact] public async Task check_metadata_correlation_id_disabled() { // note: by default CorrelationId meta data is not enabled const string correlationId = "test-correlation-id"; theSession.CorrelationId = correlationId; var streamId = theSession.Events .StartStream<QuestParty>(started, joined, slayed).Id; await theSession.SaveChangesAsync(); var events = await theSession.Events.FetchStreamAsync(streamId); foreach (var @event in events) { @event.CorrelationId.ShouldBeNullOrEmpty(); } } [Fact] public async Task check_metadata_causation_id_enabled() { StoreOptions(_ => _.Events.MetadataConfig.CausationIdEnabled = true); const string causationId = "test-causation-id"; theSession.CausationId = causationId; var streamId = theSession.Events .StartStream<QuestParty>(started, joined, slayed).Id; await theSession.SaveChangesAsync(); var events = await theSession.Events.FetchStreamAsync(streamId); foreach (var @event in events) { @event.CausationId.ShouldBe(causationId); } } [Fact] public async Task check_search_with_causation_id() { StoreOptions(_ => _.Events.MetadataConfig.CausationIdEnabled = true); const string causationId = "test-causation-id"; theSession.CausationId = causationId; var streamId = theSession.Events.StartStream<QuestParty>(started, joined, slayed).Id; await theSession.SaveChangesAsync(); var events = await theSession.Events.QueryAllRawEvents() .Where(x => x.CausationId == causationId) .ToListAsync(); events.Count.ShouldBe(3); events[0].StreamId.ShouldBe(streamId); events[1].StreamId.ShouldBe(streamId); events[2].StreamId.ShouldBe(streamId); } [Fact] public async Task check_metadata_causation_id_disabled() { // note: by default CausationId meta data is not enabled const string causationId = "test-causation-id"; theSession.CausationId = causationId; var streamId = theSession.Events .StartStream<QuestParty>(started, joined, slayed).Id; await theSession.SaveChangesAsync(); var events = await theSession.Events.FetchStreamAsync(streamId); foreach (var @event in events) { @event.CausationId.ShouldBeNullOrEmpty(); } } [Fact] public async Task check_user_defined_metadata_enabled() { StoreOptions(_ => _.Events.MetadataConfig.HeadersEnabled = true); const string userDefinedMetadataName = "my-custom-metadata"; const string userDefinedMetadataValue = "my-custom-metadata-value"; theSession.SetHeader(userDefinedMetadataName, userDefinedMetadataValue); var streamId = theSession.Events .StartStream<QuestParty>(started, joined, slayed).Id; await theSession.SaveChangesAsync(); var events = await theSession.Events.FetchStreamAsync(streamId); foreach (var @event in events) { var retrievedVal = @event.GetHeader(userDefinedMetadataName).ToString(); retrievedVal.ShouldBe(userDefinedMetadataValue); } } [Fact] public async Task check_user_defined_metadata_disabled() { // note: by default user defined meta data is not enabled const string userDefinedMetadataName = "my-custom-metadata"; const string userDefinedMetadataValue = "my-custom-metadata-value"; theSession.SetHeader(userDefinedMetadataName, userDefinedMetadataValue); var streamId = theSession.Events .StartStream<QuestParty>(started, joined, slayed).Id; await theSession.SaveChangesAsync(); var events = await theSession.Events.FetchStreamAsync(streamId); foreach (var @event in events) { @event.GetHeader(userDefinedMetadataName).ShouldBeNull(); } } [Fact] public async Task check_flexible_metadata_with_all_enabled() { StoreOptions(_ => _.Events.MetadataConfig.EnableAll()); const string correlationId = "test-correlation-id"; theSession.CorrelationId = correlationId; const string causationId = "test-causation-id"; theSession.CausationId = causationId; const string userDefinedMetadataName = "my-custom-metadata"; const string userDefinedMetadataValue = "my-custom-metadata-value"; theSession.SetHeader(userDefinedMetadataName, userDefinedMetadataValue); var streamId = theSession.Events .StartStream<QuestParty>(started, joined, slayed).Id; await theSession.SaveChangesAsync(); var events = await theSession.Events.FetchStreamAsync(streamId); foreach (var @event in events) { @event.CorrelationId.ShouldBe(correlationId); @event.CausationId.ShouldBe(causationId); var retrievedVal = @event.GetHeader(userDefinedMetadataName).ToString(); retrievedVal.ShouldBe(userDefinedMetadataValue); } } public flexible_event_metadata() : base("event_flex_meta") { } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // ConcurrentStack.cs // // A lock-free, concurrent stack primitive, and its associated debugger view type. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Threading; namespace System.Collections.Concurrent { // A stack that uses CAS operations internally to maintain thread-safety in a lock-free // manner. Attempting to push or pop concurrently from the stack will not trigger waiting, // although some optimistic concurrency and retry is used, possibly leading to lack of // fairness and/or livelock. The stack uses spinning and backoff to add some randomization, // in hopes of statistically decreasing the possibility of livelock. // // Note that we currently allocate a new node on every push. This avoids having to worry // about potential ABA issues, since the CLR GC ensures that a memory address cannot be // reused before all references to it have died. /// <summary> /// Represents a thread-safe last-in, first-out collection of objects. /// </summary> /// <typeparam name="T">Specifies the type of elements in the stack.</typeparam> /// <remarks> /// All public and protected members of <see cref="ConcurrentStack{T}"/> are thread-safe and may be used /// concurrently from multiple threads. /// </remarks> [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(IProducerConsumerCollectionDebugView<>))] public class ConcurrentStack<T> : IProducerConsumerCollection<T>, IReadOnlyCollection<T> { /// <summary> /// A simple (internal) node type used to store elements of concurrent stacks and queues. /// </summary> private class Node { internal readonly T _value; // Value of the node. internal Node _next; // Next pointer. /// <summary> /// Constructs a new node with the specified value and no next node. /// </summary> /// <param name="value">The value of the node.</param> internal Node(T value) { _value = value; _next = null; } } private volatile Node _head; // The stack is a singly linked list, and only remembers the head. private const int BACKOFF_MAX_YIELDS = 8; // Arbitrary number to cap backoff. /// <summary> /// Initializes a new instance of the <see cref="ConcurrentStack{T}"/> /// class. /// </summary> public ConcurrentStack() { } /// <summary> /// Initializes a new instance of the <see cref="ConcurrentStack{T}"/> /// class that contains elements copied from the specified collection /// </summary> /// <param name="collection">The collection whose elements are copied to the new <see /// cref="ConcurrentStack{T}"/>.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="collection"/> argument is /// null.</exception> public ConcurrentStack(IEnumerable<T> collection) { if (collection == null) { throw new ArgumentNullException(nameof(collection)); } InitializeFromCollection(collection); } /// <summary> /// Initializes the contents of the stack from an existing collection. /// </summary> /// <param name="collection">A collection from which to copy elements.</param> private void InitializeFromCollection(IEnumerable<T> collection) { // We just copy the contents of the collection to our stack. Node lastNode = null; foreach (T element in collection) { Node newNode = new Node(element); newNode._next = lastNode; lastNode = newNode; } _head = lastNode; } /// <summary> /// Gets a value that indicates whether the <see cref="ConcurrentStack{T}"/> is empty. /// </summary> /// <value>true if the <see cref="ConcurrentStack{T}"/> is empty; otherwise, false.</value> /// <remarks> /// For determining whether the collection contains any items, use of this property is recommended /// rather than retrieving the number of items from the <see cref="Count"/> property and comparing it /// to 0. However, as this collection is intended to be accessed concurrently, it may be the case /// that another thread will modify the collection after <see cref="IsEmpty"/> returns, thus invalidating /// the result. /// </remarks> public bool IsEmpty { // Checks whether the stack is empty. Clearly the answer may be out of date even prior to // the function returning (i.e. if another thread concurrently adds to the stack). It does // guarantee, however, that, if another thread does not mutate the stack, a subsequent call // to TryPop will return true -- i.e. it will also read the stack as non-empty. get { return _head == null; } } /// <summary> /// Gets the number of elements contained in the <see cref="ConcurrentStack{T}"/>. /// </summary> /// <value>The number of elements contained in the <see cref="ConcurrentStack{T}"/>.</value> /// <remarks> /// For determining whether the collection contains any items, use of the <see cref="IsEmpty"/> /// property is recommended rather than retrieving the number of items from the <see cref="Count"/> /// property and comparing it to 0. /// </remarks> public int Count { // Counts the number of entries in the stack. This is an O(n) operation. The answer may be out // of date before returning, but guarantees to return a count that was once valid. Conceptually, // the implementation snaps a copy of the list and then counts the entries, though physically // this is not what actually happens. get { int count = 0; // Just whip through the list and tally up the number of nodes. We rely on the fact that // node next pointers are immutable after being enqueued for the first time, even as // they are being dequeued. If we ever changed this (e.g. to pool nodes somehow), // we'd need to revisit this implementation. for (Node curr = _head; curr != null; curr = curr._next) { count++; //we don't handle overflow, to be consistent with existing generic collection types in CLR } return count; } } /// <summary> /// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is /// synchronized with the SyncRoot. /// </summary> /// <value>true if access to the <see cref="T:System.Collections.ICollection"/> is synchronized /// with the SyncRoot; otherwise, false. For <see cref="ConcurrentStack{T}"/>, this property always /// returns false.</value> bool ICollection.IsSynchronized { // Gets a value indicating whether access to this collection is synchronized. Always returns // false. The reason is subtle. While access is in face thread safe, it's not the case that // locking on the SyncRoot would have prevented concurrent pushes and pops, as this property // would typically indicate; that's because we internally use CAS operations vs. true locks. get { return false; } } /// <summary> /// Gets an object that can be used to synchronize access to the <see /// cref="T:System.Collections.ICollection"/>. This property is not supported. /// </summary> /// <exception cref="T:System.NotSupportedException">The SyncRoot property is not supported</exception> object ICollection.SyncRoot { get { throw new NotSupportedException(SR.ConcurrentCollection_SyncRoot_NotSupported); } } /// <summary> /// Removes all objects from the <see cref="ConcurrentStack{T}"/>. /// </summary> public void Clear() { // Clear the list by setting the head to null. We don't need to use an atomic // operation for this: anybody who is mutating the head by pushing or popping // will need to use an atomic operation to guarantee they serialize and don't // overwrite our setting of the head to null. _head = null; } /// <summary> /// Copies the elements of the <see cref="T:System.Collections.ICollection"/> to an <see /// cref="T:System.Array"/>, starting at a particular /// <see cref="T:System.Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of /// the elements copied from the /// <see cref="ConcurrentStack{T}"/>. The <see cref="T:System.Array"/> must /// have zero-based indexing.</param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying /// begins.</param> /// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in /// Visual Basic).</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than /// zero.</exception> /// <exception cref="ArgumentException"> /// <paramref name="array"/> is multidimensional. -or- /// <paramref name="array"/> does not have zero-based indexing. -or- /// <paramref name="index"/> is equal to or greater than the length of the <paramref name="array"/> /// -or- The number of elements in the source <see cref="T:System.Collections.ICollection"/> is /// greater than the available space from <paramref name="index"/> to the end of the destination /// <paramref name="array"/>. -or- The type of the source <see /// cref="T:System.Collections.ICollection"/> cannot be cast automatically to the type of the /// destination <paramref name="array"/>. /// </exception> void ICollection.CopyTo(Array array, int index) { // Validate arguments. if (array == null) { throw new ArgumentNullException(nameof(array)); } // We must be careful not to corrupt the array, so we will first accumulate an // internal list of elements that we will then copy to the array. This requires // some extra allocation, but is necessary since we don't know up front whether // the array is sufficiently large to hold the stack's contents. ((ICollection)ToList()).CopyTo(array, index); } /// <summary> /// Copies the <see cref="ConcurrentStack{T}"/> elements to an existing one-dimensional <see /// cref="T:System.Array"/>, starting at the specified array index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of /// the elements copied from the /// <see cref="ConcurrentStack{T}"/>. The <see cref="T:System.Array"/> must have zero-based /// indexing.</param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying /// begins.</param> /// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in /// Visual Basic).</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than /// zero.</exception> /// <exception cref="ArgumentException"><paramref name="index"/> is equal to or greater than the /// length of the <paramref name="array"/> /// -or- The number of elements in the source <see cref="ConcurrentStack{T}"/> is greater than the /// available space from <paramref name="index"/> to the end of the destination <paramref /// name="array"/>. /// </exception> public void CopyTo(T[] array, int index) { if (array == null) { throw new ArgumentNullException(nameof(array)); } // We must be careful not to corrupt the array, so we will first accumulate an // internal list of elements that we will then copy to the array. This requires // some extra allocation, but is necessary since we don't know up front whether // the array is sufficiently large to hold the stack's contents. ToList().CopyTo(array, index); } /// <summary> /// Inserts an object at the top of the <see cref="ConcurrentStack{T}"/>. /// </summary> /// <param name="item">The object to push onto the <see cref="ConcurrentStack{T}"/>. The value can be /// a null reference (Nothing in Visual Basic) for reference types. /// </param> public void Push(T item) { // Pushes a node onto the front of the stack thread-safely. Internally, this simply // swaps the current head pointer using a (thread safe) CAS operation to accomplish // lock freedom. If the CAS fails, we add some back off to statistically decrease // contention at the head, and then go back around and retry. Node newNode = new Node(item); newNode._next = _head; if (Interlocked.CompareExchange(ref _head, newNode, newNode._next) == newNode._next) { return; } // If we failed, go to the slow path and loop around until we succeed. PushCore(newNode, newNode); } /// <summary> /// Inserts multiple objects at the top of the <see cref="ConcurrentStack{T}"/> atomically. /// </summary> /// <param name="items">The objects to push onto the <see cref="ConcurrentStack{T}"/>.</param> /// <exception cref="ArgumentNullException"><paramref name="items"/> is a null reference /// (Nothing in Visual Basic).</exception> /// <remarks> /// When adding multiple items to the stack, using PushRange is a more efficient /// mechanism than using <see cref="Push"/> one item at a time. Additionally, PushRange /// guarantees that all of the elements will be added atomically, meaning that no other threads will /// be able to inject elements between the elements being pushed. Items at lower indices in /// the <paramref name="items"/> array will be pushed before items at higher indices. /// </remarks> public void PushRange(T[] items) { if (items == null) { throw new ArgumentNullException(nameof(items)); } PushRange(items, 0, items.Length); } /// <summary> /// Inserts multiple objects at the top of the <see cref="ConcurrentStack{T}"/> atomically. /// </summary> /// <param name="items">The objects to push onto the <see cref="ConcurrentStack{T}"/>.</param> /// <param name="startIndex">The zero-based offset in <paramref name="items"/> at which to begin /// inserting elements onto the top of the <see cref="ConcurrentStack{T}"/>.</param> /// <param name="count">The number of elements to be inserted onto the top of the <see /// cref="ConcurrentStack{T}"/>.</param> /// <exception cref="ArgumentNullException"><paramref name="items"/> is a null reference /// (Nothing in Visual Basic).</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="startIndex"/> or <paramref /// name="count"/> is negative. Or <paramref name="startIndex"/> is greater than or equal to the length /// of <paramref name="items"/>.</exception> /// <exception cref="ArgumentException"><paramref name="startIndex"/> + <paramref name="count"/> is /// greater than the length of <paramref name="items"/>.</exception> /// <remarks> /// When adding multiple items to the stack, using PushRange is a more efficient /// mechanism than using <see cref="Push"/> one item at a time. Additionally, PushRange /// guarantees that all of the elements will be added atomically, meaning that no other threads will /// be able to inject elements between the elements being pushed. Items at lower indices in the /// <paramref name="items"/> array will be pushed before items at higher indices. /// </remarks> public void PushRange(T[] items, int startIndex, int count) { ValidatePushPopRangeInput(items, startIndex, count); // No op if the count is zero if (count == 0) return; Node head, tail; head = tail = new Node(items[startIndex]); for (int i = startIndex + 1; i < startIndex + count; i++) { Node node = new Node(items[i]); node._next = head; head = node; } tail._next = _head; if (Interlocked.CompareExchange(ref _head, head, tail._next) == tail._next) { return; } // If we failed, go to the slow path and loop around until we succeed. PushCore(head, tail); } /// <summary> /// Push one or many nodes into the stack, if head and tails are equal then push one node to the stack other wise push the list between head /// and tail to the stack /// </summary> /// <param name="head">The head pointer to the new list</param> /// <param name="tail">The tail pointer to the new list</param> private void PushCore(Node head, Node tail) { SpinWait spin = new SpinWait(); // Keep trying to CAS the existing head with the new node until we succeed. do { spin.SpinOnce(sleep1Threshold: -1); // Reread the head and link our new node. tail._next = _head; } while (Interlocked.CompareExchange( ref _head, head, tail._next) != tail._next); if (CDSCollectionETWBCLProvider.Log.IsEnabled()) { CDSCollectionETWBCLProvider.Log.ConcurrentStack_FastPushFailed(spin.Count); } } /// <summary> /// Local helper function to validate the Pop Push range methods input /// </summary> private static void ValidatePushPopRangeInput(T[] items, int startIndex, int count) { if (items == null) { throw new ArgumentNullException(nameof(items)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ConcurrentStack_PushPopRange_CountOutOfRange); } int length = items.Length; if (startIndex >= length || startIndex < 0) { throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ConcurrentStack_PushPopRange_StartOutOfRange); } if (length - count < startIndex) //instead of (startIndex + count > items.Length) to prevent overflow { throw new ArgumentException(SR.ConcurrentStack_PushPopRange_InvalidCount); } } /// <summary> /// Attempts to add an object to the <see /// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>. /// </summary> /// <param name="item">The object to add to the <see /// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>. The value can be a null /// reference (Nothing in Visual Basic) for reference types. /// </param> /// <returns>true if the object was added successfully; otherwise, false.</returns> /// <remarks>For <see cref="ConcurrentStack{T}"/>, this operation /// will always insert the object onto the top of the <see cref="ConcurrentStack{T}"/> /// and return true.</remarks> bool IProducerConsumerCollection<T>.TryAdd(T item) { Push(item); return true; } /// <summary> /// Attempts to return an object from the top of the <see cref="ConcurrentStack{T}"/> /// without removing it. /// </summary> /// <param name="result">When this method returns, <paramref name="result"/> contains an object from /// the top of the <see cref="T:System.Collections.Concurrent.ConcurrentStack{T}"/> or an /// unspecified value if the operation failed.</param> /// <returns>true if and object was returned successfully; otherwise, false.</returns> public bool TryPeek(out T result) { Node head = _head; // If the stack is empty, return false; else return the element and true. if (head == null) { result = default(T); return false; } else { result = head._value; return true; } } /// <summary> /// Attempts to pop and return the object at the top of the <see cref="ConcurrentStack{T}"/>. /// </summary> /// <param name="result"> /// When this method returns, if the operation was successful, <paramref name="result"/> contains the /// object removed. If no object was available to be removed, the value is unspecified. /// </param> /// <returns>true if an element was removed and returned from the top of the <see /// cref="ConcurrentStack{T}"/> /// successfully; otherwise, false.</returns> public bool TryPop(out T result) { Node head = _head; //stack is empty if (head == null) { result = default(T); return false; } if (Interlocked.CompareExchange(ref _head, head._next, head) == head) { result = head._value; return true; } // Fall through to the slow path. return TryPopCore(out result); } /// <summary> /// Attempts to pop and return multiple objects from the top of the <see cref="ConcurrentStack{T}"/> /// atomically. /// </summary> /// <param name="items"> /// The <see cref="T:System.Array"/> to which objects popped from the top of the <see /// cref="ConcurrentStack{T}"/> will be added. /// </param> /// <returns>The number of objects successfully popped from the top of the <see /// cref="ConcurrentStack{T}"/> and inserted in /// <paramref name="items"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="items"/> is a null argument (Nothing /// in Visual Basic).</exception> /// <remarks> /// When popping multiple items, if there is little contention on the stack, using /// TryPopRange can be more efficient than using <see cref="TryPop"/> /// once per item to be removed. Nodes fill the <paramref name="items"/> /// with the first node to be popped at the startIndex, the second node to be popped /// at startIndex + 1, and so on. /// </remarks> public int TryPopRange(T[] items) { if (items == null) { throw new ArgumentNullException(nameof(items)); } return TryPopRange(items, 0, items.Length); } /// <summary> /// Attempts to pop and return multiple objects from the top of the <see cref="ConcurrentStack{T}"/> /// atomically. /// </summary> /// <param name="items"> /// The <see cref="T:System.Array"/> to which objects popped from the top of the <see /// cref="ConcurrentStack{T}"/> will be added. /// </param> /// <param name="startIndex">The zero-based offset in <paramref name="items"/> at which to begin /// inserting elements from the top of the <see cref="ConcurrentStack{T}"/>.</param> /// <param name="count">The number of elements to be popped from top of the <see /// cref="ConcurrentStack{T}"/> and inserted into <paramref name="items"/>.</param> /// <returns>The number of objects successfully popped from the top of /// the <see cref="ConcurrentStack{T}"/> and inserted in <paramref name="items"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="items"/> is a null reference /// (Nothing in Visual Basic).</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="startIndex"/> or <paramref /// name="count"/> is negative. Or <paramref name="startIndex"/> is greater than or equal to the length /// of <paramref name="items"/>.</exception> /// <exception cref="ArgumentException"><paramref name="startIndex"/> + <paramref name="count"/> is /// greater than the length of <paramref name="items"/>.</exception> /// <remarks> /// When popping multiple items, if there is little contention on the stack, using /// TryPopRange can be more efficient than using <see cref="TryPop"/> /// once per item to be removed. Nodes fill the <paramref name="items"/> /// with the first node to be popped at the startIndex, the second node to be popped /// at startIndex + 1, and so on. /// </remarks> public int TryPopRange(T[] items, int startIndex, int count) { ValidatePushPopRangeInput(items, startIndex, count); // No op if the count is zero if (count == 0) return 0; Node poppedHead; int nodesCount = TryPopCore(count, out poppedHead); if (nodesCount > 0) { CopyRemovedItems(poppedHead, items, startIndex, nodesCount); } return nodesCount; } /// <summary> /// Local helper function to Pop an item from the stack, slow path /// </summary> /// <param name="result">The popped item</param> /// <returns>True if succeeded, false otherwise</returns> private bool TryPopCore(out T result) { Node poppedNode; if (TryPopCore(1, out poppedNode) == 1) { result = poppedNode._value; return true; } result = default(T); return false; } /// <summary> /// Slow path helper for TryPop. This method assumes an initial attempt to pop an element /// has already occurred and failed, so it begins spinning right away. /// </summary> /// <param name="count">The number of items to pop.</param> /// <param name="poppedHead"> /// When this method returns, if the pop succeeded, contains the removed object. If no object was /// available to be removed, the value is unspecified. This parameter is passed uninitialized. /// </param> /// <returns>The number of objects successfully popped from the top of /// the <see cref="ConcurrentStack{T}"/>.</returns> private int TryPopCore(int count, out Node poppedHead) { SpinWait spin = new SpinWait(); // Try to CAS the head with its current next. We stop when we succeed or // when we notice that the stack is empty, whichever comes first. Node head; Node next; int backoff = 1; Random r = null; while (true) { head = _head; // Is the stack empty? if (head == null) { if (count == 1 && CDSCollectionETWBCLProvider.Log.IsEnabled()) { CDSCollectionETWBCLProvider.Log.ConcurrentStack_FastPopFailed(spin.Count); } poppedHead = null; return 0; } next = head; int nodesCount = 1; for (; nodesCount < count && next._next != null; nodesCount++) { next = next._next; } // Try to swap the new head. If we succeed, break out of the loop. if (Interlocked.CompareExchange(ref _head, next._next, head) == head) { if (count == 1 && CDSCollectionETWBCLProvider.Log.IsEnabled()) { CDSCollectionETWBCLProvider.Log.ConcurrentStack_FastPopFailed(spin.Count); } // Return the popped Node. poppedHead = head; return nodesCount; } // We failed to CAS the new head. Spin briefly and retry. for (int i = 0; i < backoff; i++) { spin.SpinOnce(sleep1Threshold: -1); } if (spin.NextSpinWillYield) { if (r == null) { r = new Random(); } backoff = r.Next(1, BACKOFF_MAX_YIELDS); } else { backoff *= 2; } } } /// <summary> /// Local helper function to copy the popped elements into a given collection /// </summary> /// <param name="head">The head of the list to be copied</param> /// <param name="collection">The collection to place the popped items in</param> /// <param name="startIndex">the beginning of index of where to place the popped items</param> /// <param name="nodesCount">The number of nodes.</param> private static void CopyRemovedItems(Node head, T[] collection, int startIndex, int nodesCount) { Node current = head; for (int i = startIndex; i < startIndex + nodesCount; i++) { collection[i] = current._value; current = current._next; } } /// <summary> /// Attempts to remove and return an object from the <see /// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>. /// </summary> /// <param name="item"> /// When this method returns, if the operation was successful, <paramref name="item"/> contains the /// object removed. If no object was available to be removed, the value is unspecified. /// </param> /// <returns>true if an element was removed and returned successfully; otherwise, false.</returns> /// <remarks>For <see cref="ConcurrentStack{T}"/>, this operation will attempt to pope the object at /// the top of the <see cref="ConcurrentStack{T}"/>. /// </remarks> bool IProducerConsumerCollection<T>.TryTake(out T item) { return TryPop(out item); } /// <summary> /// Copies the items stored in the <see cref="ConcurrentStack{T}"/> to a new array. /// </summary> /// <returns>A new array containing a snapshot of elements copied from the <see /// cref="ConcurrentStack{T}"/>.</returns> public T[] ToArray() { Node curr = _head; return curr == null ? Array.Empty<T>() : ToList(curr).ToArray(); } /// <summary> /// Returns an array containing a snapshot of the list's contents, using /// the target list node as the head of a region in the list. /// </summary> /// <returns>A list of the stack's contents.</returns> private List<T> ToList() { return ToList(_head); } /// <summary> /// Returns an array containing a snapshot of the list's contents starting at the specified node. /// </summary> /// <returns>A list of the stack's contents starting at the specified node.</returns> private List<T> ToList(Node curr) { List<T> list = new List<T>(); while (curr != null) { list.Add(curr._value); curr = curr._next; } return list; } /// <summary> /// Returns an enumerator that iterates through the <see cref="ConcurrentStack{T}"/>. /// </summary> /// <returns>An enumerator for the <see cref="ConcurrentStack{T}"/>.</returns> /// <remarks> /// The enumeration represents a moment-in-time snapshot of the contents /// of the stack. It does not reflect any updates to the collection after /// <see cref="GetEnumerator()"/> was called. The enumerator is safe to use /// concurrently with reads from and writes to the stack. /// </remarks> public IEnumerator<T> GetEnumerator() { // Returns an enumerator for the stack. This effectively takes a snapshot // of the stack's contents at the time of the call, i.e. subsequent modifications // (pushes or pops) will not be reflected in the enumerator's contents. //If we put yield-return here, the iterator will be lazily evaluated. As a result a snapshot of //the stack is not taken when GetEnumerator is initialized but when MoveNext() is first called. //This is inconsistent with existing generic collections. In order to prevent it, we capture the //value of _head in a buffer and call out to a helper method return GetEnumerator(_head); } private IEnumerator<T> GetEnumerator(Node head) { Node current = head; while (current != null) { yield return current._value; current = current._next; } } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns>An <see cref="T:System.Collections.IEnumerator"/> that can be used to iterate through /// the collection.</returns> /// <remarks> /// The enumeration represents a moment-in-time snapshot of the contents of the stack. It does not /// reflect any updates to the collection after /// <see cref="GetEnumerator()"/> was called. The enumerator is safe to use concurrently with reads /// from and writes to the stack. /// </remarks> IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<T>)this).GetEnumerator(); } } }
// Copyright 2004 Dominic Cooney. All Rights Reserved. /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using NUnit.Framework; using System; using System.Collections.Generic; namespace Earley { [TestFixture] public class TestParser { [Test, ExpectedException(typeof(ArgumentNullException))] public void CreateNullStart() { new Parser(null); } [Test, ExpectedException(typeof(ArgumentException))] public void CreateStartWithoutEof() { new Parser(new Reduction("", new Terminal('x'))); } [Test, ExpectedException(typeof(ArgumentNullException))] public void ParseNull() { Parser parser = new Parser(new Reduction("", Terminal.Eof)); parser.Parse(null); } [Test] public void ParseTrivial() { Reduction start = new Reduction("return 123;", Terminal.Eof); ReductionCompiler comp = new ReductionCompiler(); comp.Add(start); comp.Compile(); Parser parser = new Parser(start); IList<object> results = parser.Parse(""); Assert.AreEqual(1, results.Count); Assert.AreEqual(123, results[0]); } [Test] public void ParseTrivialNullable() { Reduction nullable = new Reduction("return \"Hello, world!\";"); Reduction start = new Reduction("return $0;", new Nonterminal(nullable), Terminal.Eof); ReductionCompiler comp = new ReductionCompiler(); comp.Add(nullable); comp.Add(start); comp.Compile(); Parser parser = new Parser(start); IList<object> results = parser.Parse(""); Assert.AreEqual(1, results.Count); Assert.AreEqual("Hello, world!", results[0]); } [Test] public void ParseIndirectNullable() { Reduction hello = new Reduction("return \"Hello\";"); Reduction world = new Reduction("return \"world\";"); Reduction nullable = new Reduction("return string.Format(\"{0}, {1}!\", $0, $1);", new Nonterminal(hello), new Nonterminal(world)); Reduction start = new Reduction("return string.Format(\"{0}{1}\", $0, $1);", new Nonterminal(nullable), new Nonterminal(nullable), Terminal.Eof); ReductionCompiler comp = new ReductionCompiler(); comp.Add(hello); comp.Add(world); comp.Add(nullable); comp.Add(start); comp.Compile(); Parser parser = new Parser(start); IList<object> results = parser.Parse(""); Assert.AreEqual(1, results.Count); Assert.AreEqual("Hello, world!Hello, world!", results[0]); results = parser.Parse("xxx"); Assert.AreEqual(0, results.Count); } [Test, ExpectedException(typeof(InvalidOperationException))] public void ParseUncompiled() { Reduction start = new Reduction("return 123;", Terminal.Eof); Parser parser = new Parser(start); parser.Parse(""); } [Test] public void ParseCountRR() { // E ::= a // | a E Reduction single = new Reduction("return 1;", new Terminal('a')); Nonterminal e = new Nonterminal(); Reduction rec = new Reduction( "return 1 + (int)$1;", new Terminal('a'), e); e.Add(single); e.Add(rec); Reduction start = new Reduction("return $0;", e, Terminal.Eof); ReductionCompiler comp = new ReductionCompiler(); comp.Add(single); comp.Add(rec); comp.Add(start); comp.Compile(); Parser parser = new Parser(start); IList<object> result = parser.Parse(""); Assert.AreEqual(0, result.Count); result = parser.Parse("a"); Assert.AreEqual(1, result.Count); Assert.AreEqual(1, result[0]); result = parser.Parse("aa"); Assert.AreEqual(1, result.Count); Assert.AreEqual(2, result[0]); result = parser.Parse("aaa"); Assert.AreEqual(1, result.Count); Assert.AreEqual(3, result[0]); result = parser.Parse("aaaaaaaaaa"); Assert.AreEqual(1, result.Count); Assert.AreEqual(10, result[0]); } [Test] public void ParseCountLR() { // E ::= empty // | E a Reduction empty = new Reduction("return 0;"); Nonterminal e = new Nonterminal(); Reduction rec = new Reduction( "return 1 + (int)$0;", e, new Terminal('a')); e.Add(empty); e.Add(rec); Reduction start = new Reduction("return $0;", e, Terminal.Eof); ReductionCompiler comp = new ReductionCompiler(); comp.Add(empty); comp.Add(rec); comp.Add(start); comp.Compile(); Parser parser = new Parser(start); IList<object> result = parser.Parse(""); Assert.AreEqual(1, result.Count); Assert.AreEqual(0, result[0]); result = parser.Parse("a"); Assert.AreEqual(1, result.Count); Assert.AreEqual(1, result[0]); result = parser.Parse("aa"); Assert.AreEqual(1, result.Count); Assert.AreEqual(2, result[0]); result = parser.Parse("aaa"); Assert.AreEqual(1, result.Count); Assert.AreEqual(3, result[0]); result = parser.Parse("aaaaaaaaaa"); Assert.AreEqual(1, result.Count); Assert.AreEqual(10, result[0]); } [Test] public void ParseAmbiguousExpressions() { // E ::= E + E // | E * E // | ( E ) // | [0-9]+ Nonterminal e = new Nonterminal(); Reduction add = new Reduction( "return (int)$0 + (int)$2;", e, new Terminal('+'), e); Reduction mul = new Reduction( "return (int)$0 * (int)$2;", e, new Terminal('*'), e); Reduction brack = new Reduction( "return $1;", new Terminal('('), e, new Terminal(')')); Nonterminal anyLit = new Nonterminal(); Terminal digit = new Terminal('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); Reduction litBase = new Reduction( "return (int)$0 - (int)'0';", digit); Reduction litRec = new Reduction( "return 10 * (int)$0 + (int)$1 - (int)'0';", anyLit, digit); anyLit.Add(litBase); anyLit.Add(litRec); e.Add(add); e.Add(mul); e.Add(brack); e.Add(litRec); e.Add(litBase); Reduction start = new Reduction("return $0;", e, Terminal.Eof); ReductionCompiler comp = new ReductionCompiler(); comp.Add(add); comp.Add(mul); comp.Add(brack); comp.Add(litRec); comp.Add(litBase); comp.Add(start); comp.Compile(); Parser parser = new Parser(start); IList<object> result = parser.Parse("4"); Assert.AreEqual(1, result.Count); Assert.AreEqual(4, result[0]); result = parser.Parse("1023"); Assert.AreEqual(1, result.Count); Assert.AreEqual(1023, result[0]); result = parser.Parse("12*7"); Assert.AreEqual(1, result.Count); Assert.AreEqual(84, result[0]); result = parser.Parse("(((12))*(7))"); Assert.AreEqual(1, result.Count); Assert.AreEqual(84, result[0]); result = parser.Parse("2*20+3"); Assert.AreEqual(2, result.Count); Assert.IsTrue(result.Contains(43) && result.Contains(46)); result = parser.Parse("1+2+3"); Assert.AreEqual(2, result.Count); Assert.IsTrue(result[0].Equals(6) && result[1].Equals(6)); } } }
// 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. /*============================================================================= ** ** Class: Queue ** ** Purpose: Represents a first-in, first-out collection of objects. ** =============================================================================*/ using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; namespace System.Collections { // A simple Queue of objects. Internally it is implemented as a circular // buffer, so Enqueue can be O(n). Dequeue is O(1). [DebuggerTypeProxy(typeof(System.Collections.Queue.QueueDebugView))] [DebuggerDisplay("Count = {Count}")] public class Queue : ICollection { private Object[] _array; private int _head; // First valid element in the queue private int _tail; // Last valid element in the queue private int _size; // Number of elements. private int _growFactor; // 100 == 1.0, 130 == 1.3, 200 == 2.0 private int _version; private Object _syncRoot; private const int _MinimumGrow = 4; private const int _ShrinkThreshold = 32; // Creates a queue with room for capacity objects. The default initial // capacity and grow factor are used. public Queue() : this(32, (float)2.0) { } // Creates a queue with room for capacity objects. The default grow factor // is used. // public Queue(int capacity) : this(capacity, (float)2.0) { } // Creates a queue with room for capacity objects. When full, the new // capacity is set to the old capacity * growFactor. // public Queue(int capacity, float growFactor) { if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NeedNonNegNum); if (!(growFactor >= 1.0 && growFactor <= 10.0)) throw new ArgumentOutOfRangeException(nameof(growFactor), SR.Format(SR.ArgumentOutOfRange_QueueGrowFactor, 1, 10)); Contract.EndContractBlock(); _array = new Object[capacity]; _head = 0; _tail = 0; _size = 0; _growFactor = (int)(growFactor * 100); } // Fills a Queue with the elements of an ICollection. Uses the enumerator // to get each of the elements. // public Queue(ICollection col) : this((col == null ? 32 : col.Count)) { if (col == null) throw new ArgumentNullException(nameof(col)); Contract.EndContractBlock(); IEnumerator en = col.GetEnumerator(); while (en.MoveNext()) Enqueue(en.Current); } public virtual int Count { get { return _size; } } public virtual Object Clone() { Queue q = new Queue(_size); q._size = _size; int numToCopy = _size; int firstPart = (_array.Length - _head < numToCopy) ? _array.Length - _head : numToCopy; Array.Copy(_array, _head, q._array, 0, firstPart); numToCopy -= firstPart; if (numToCopy > 0) Array.Copy(_array, 0, q._array, _array.Length - _head, numToCopy); q._version = _version; return q; } public virtual bool IsSynchronized { get { return false; } } public virtual Object SyncRoot { get { if (_syncRoot == null) { System.Threading.Interlocked.CompareExchange(ref _syncRoot, new Object(), null); } return _syncRoot; } } // Removes all Objects from the queue. public virtual void Clear() { if (_size != 0) { if (_head < _tail) Array.Clear(_array, _head, _size); else { Array.Clear(_array, _head, _array.Length - _head); Array.Clear(_array, 0, _tail); } _size = 0; } _head = 0; _tail = 0; _version++; } // CopyTo copies a collection into an Array, starting at a particular // index into the array. // public virtual void CopyTo(Array array, int index) { if (array == null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); Contract.EndContractBlock(); int arrayLen = array.Length; if (arrayLen - index < _size) throw new ArgumentException(SR.Argument_InvalidOffLen); int numToCopy = _size; if (numToCopy == 0) return; int firstPart = (_array.Length - _head < numToCopy) ? _array.Length - _head : numToCopy; Array.Copy(_array, _head, array, index, firstPart); numToCopy -= firstPart; if (numToCopy > 0) Array.Copy(_array, 0, array, index + _array.Length - _head, numToCopy); } // Adds obj to the tail of the queue. // public virtual void Enqueue(Object obj) { if (_size == _array.Length) { int newcapacity = (int)((long)_array.Length * (long)_growFactor / 100); if (newcapacity < _array.Length + _MinimumGrow) { newcapacity = _array.Length + _MinimumGrow; } SetCapacity(newcapacity); } _array[_tail] = obj; _tail = (_tail + 1) % _array.Length; _size++; _version++; } // GetEnumerator returns an IEnumerator over this Queue. This // Enumerator will support removing. // public virtual IEnumerator GetEnumerator() { return new QueueEnumerator(this); } // Removes the object at the head of the queue and returns it. If the queue // is empty, this method simply returns null. public virtual Object Dequeue() { if (Count == 0) throw new InvalidOperationException(SR.InvalidOperation_EmptyQueue); Contract.EndContractBlock(); Object removed = _array[_head]; _array[_head] = null; _head = (_head + 1) % _array.Length; _size--; _version++; return removed; } // Returns the object at the head of the queue. The object remains in the // queue. If the queue is empty, this method throws an // InvalidOperationException. public virtual Object Peek() { if (Count == 0) throw new InvalidOperationException(SR.InvalidOperation_EmptyQueue); Contract.EndContractBlock(); return _array[_head]; } // Returns a synchronized Queue. Returns a synchronized wrapper // class around the queue - the caller must not use references to the // original queue. // public static Queue Synchronized(Queue queue) { if (queue == null) throw new ArgumentNullException(nameof(queue)); Contract.EndContractBlock(); return new SynchronizedQueue(queue); } // Returns true if the queue contains at least one object equal to obj. // Equality is determined using obj.Equals(). // // Exceptions: ArgumentNullException if obj == null. public virtual bool Contains(Object obj) { int index = _head; int count = _size; while (count-- > 0) { if (obj == null) { if (_array[index] == null) return true; } else if (_array[index] != null && _array[index].Equals(obj)) { return true; } index = (index + 1) % _array.Length; } return false; } internal Object GetElement(int i) { return _array[(_head + i) % _array.Length]; } // Iterates over the objects in the queue, returning an array of the // objects in the Queue, or an empty array if the queue is empty. // The order of elements in the array is first in to last in, the same // order produced by successive calls to Dequeue. public virtual Object[] ToArray() { if (_size == 0) return Array.Empty<Object>(); Object[] arr = new Object[_size]; if (_head < _tail) { Array.Copy(_array, _head, arr, 0, _size); } else { Array.Copy(_array, _head, arr, 0, _array.Length - _head); Array.Copy(_array, 0, arr, _array.Length - _head, _tail); } return arr; } // PRIVATE Grows or shrinks the buffer to hold capacity objects. Capacity // must be >= _size. private void SetCapacity(int capacity) { Object[] newarray = new Object[capacity]; if (_size > 0) { if (_head < _tail) { Array.Copy(_array, _head, newarray, 0, _size); } else { Array.Copy(_array, _head, newarray, 0, _array.Length - _head); Array.Copy(_array, 0, newarray, _array.Length - _head, _tail); } } _array = newarray; _head = 0; _tail = (_size == capacity) ? 0 : _size; _version++; } public virtual void TrimToSize() { SetCapacity(_size); } // Implements a synchronization wrapper around a queue. private class SynchronizedQueue : Queue { private Queue _q; private Object _root; internal SynchronizedQueue(Queue q) { _q = q; _root = _q.SyncRoot; } public override bool IsSynchronized { get { return true; } } public override Object SyncRoot { get { return _root; } } public override int Count { get { lock (_root) { return _q.Count; } } } public override void Clear() { lock (_root) { _q.Clear(); } } public override Object Clone() { lock (_root) { return new SynchronizedQueue((Queue)_q.Clone()); } } public override bool Contains(Object obj) { lock (_root) { return _q.Contains(obj); } } public override void CopyTo(Array array, int arrayIndex) { lock (_root) { _q.CopyTo(array, arrayIndex); } } public override void Enqueue(Object value) { lock (_root) { _q.Enqueue(value); } } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Thread safety problems with precondition - can't express the precondition as of Dev10. public override Object Dequeue() { lock (_root) { return _q.Dequeue(); } } public override IEnumerator GetEnumerator() { lock (_root) { return _q.GetEnumerator(); } } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Thread safety problems with precondition - can't express the precondition as of Dev10. public override Object Peek() { lock (_root) { return _q.Peek(); } } public override Object[] ToArray() { lock (_root) { return _q.ToArray(); } } public override void TrimToSize() { lock (_root) { _q.TrimToSize(); } } } // Implements an enumerator for a Queue. The enumerator uses the // internal version number of the list to ensure that no modifications are // made to the list while an enumeration is in progress. private class QueueEnumerator : IEnumerator { private Queue _q; private int _index; private int _version; private Object _currentElement; internal QueueEnumerator(Queue q) { _q = q; _version = _q._version; _index = 0; _currentElement = _q._array; if (_q._size == 0) _index = -1; } public virtual bool MoveNext() { if (_version != _q._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); if (_index < 0) { _currentElement = _q._array; return false; } _currentElement = _q.GetElement(_index); _index++; if (_index == _q._size) _index = -1; return true; } public virtual Object Current { get { if (_currentElement == _q._array) { if (_index == 0) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); else throw new InvalidOperationException(SR.InvalidOperation_EnumEnded); } return _currentElement; } } public virtual void Reset() { if (_version != _q._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); if (_q._size == 0) _index = -1; else _index = 0; _currentElement = _q._array; } } internal class QueueDebugView { private Queue _queue; public QueueDebugView(Queue queue) { if (queue == null) throw new ArgumentNullException(nameof(queue)); Contract.EndContractBlock(); _queue = queue; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public Object[] Items { get { return _queue.ToArray(); } } } } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; public class GPGSEventListener : MonoBehaviour { #if UNITY_IPHONE || UNITY_ANDROID void OnEnable() { GPGManager.authenticationSucceededEvent += authenticationSucceededEvent; GPGManager.authenticationFailedEvent += authenticationFailedEvent; GPGManager.licenseCheckFailedEvent += licenseCheckFailedEvent; GPGManager.profileImageLoadedAtPathEvent += profileImageLoadedAtPathEvent; GPGManager.finishedSharingEvent += finishedSharingEvent; GPGManager.userSignedOutEvent += userSignedOutEvent; GPGManager.reloadDataForKeyFailedEvent += reloadDataForKeyFailedEvent; GPGManager.reloadDataForKeySucceededEvent += reloadDataForKeySucceededEvent; GPGManager.loadCloudDataForKeyFailedEvent += loadCloudDataForKeyFailedEvent; GPGManager.loadCloudDataForKeySucceededEvent += loadCloudDataForKeySucceededEvent; GPGManager.updateCloudDataForKeyFailedEvent += updateCloudDataForKeyFailedEvent; GPGManager.updateCloudDataForKeySucceededEvent += updateCloudDataForKeySucceededEvent; GPGManager.clearCloudDataForKeyFailedEvent += clearCloudDataForKeyFailedEvent; GPGManager.clearCloudDataForKeySucceededEvent += clearCloudDataForKeySucceededEvent; GPGManager.deleteCloudDataForKeyFailedEvent += deleteCloudDataForKeyFailedEvent; GPGManager.deleteCloudDataForKeySucceededEvent += deleteCloudDataForKeySucceededEvent; GPGManager.unlockAchievementFailedEvent += unlockAchievementFailedEvent; GPGManager.unlockAchievementSucceededEvent += unlockAchievementSucceededEvent; GPGManager.incrementAchievementFailedEvent += incrementAchievementFailedEvent; GPGManager.incrementAchievementSucceededEvent += incrementAchievementSucceededEvent; GPGManager.revealAchievementFailedEvent += revealAchievementFailedEvent; GPGManager.revealAchievementSucceededEvent += revealAchievementSucceededEvent; GPGManager.submitScoreFailedEvent += submitScoreFailedEvent; GPGManager.submitScoreSucceededEvent += submitScoreSucceededEvent; GPGManager.loadScoresFailedEvent += loadScoresFailedEvent; GPGManager.loadScoresSucceededEvent += loadScoresSucceededEvent; } void OnDisable() { // Remove all event handlers GPGManager.authenticationSucceededEvent -= authenticationSucceededEvent; GPGManager.authenticationFailedEvent -= authenticationFailedEvent; GPGManager.licenseCheckFailedEvent -= licenseCheckFailedEvent; GPGManager.profileImageLoadedAtPathEvent -= profileImageLoadedAtPathEvent; GPGManager.finishedSharingEvent -= finishedSharingEvent; GPGManager.userSignedOutEvent -= userSignedOutEvent; GPGManager.reloadDataForKeyFailedEvent -= reloadDataForKeyFailedEvent; GPGManager.reloadDataForKeySucceededEvent -= reloadDataForKeySucceededEvent; GPGManager.loadCloudDataForKeyFailedEvent -= loadCloudDataForKeyFailedEvent; GPGManager.loadCloudDataForKeySucceededEvent -= loadCloudDataForKeySucceededEvent; GPGManager.updateCloudDataForKeyFailedEvent -= updateCloudDataForKeyFailedEvent; GPGManager.updateCloudDataForKeySucceededEvent -= updateCloudDataForKeySucceededEvent; GPGManager.clearCloudDataForKeyFailedEvent -= clearCloudDataForKeyFailedEvent; GPGManager.clearCloudDataForKeySucceededEvent -= clearCloudDataForKeySucceededEvent; GPGManager.deleteCloudDataForKeyFailedEvent -= deleteCloudDataForKeyFailedEvent; GPGManager.deleteCloudDataForKeySucceededEvent -= deleteCloudDataForKeySucceededEvent; GPGManager.unlockAchievementFailedEvent -= unlockAchievementFailedEvent; GPGManager.unlockAchievementSucceededEvent -= unlockAchievementSucceededEvent; GPGManager.incrementAchievementFailedEvent -= incrementAchievementFailedEvent; GPGManager.incrementAchievementSucceededEvent -= incrementAchievementSucceededEvent; GPGManager.revealAchievementFailedEvent -= revealAchievementFailedEvent; GPGManager.revealAchievementSucceededEvent -= revealAchievementSucceededEvent; GPGManager.submitScoreFailedEvent -= submitScoreFailedEvent; GPGManager.submitScoreSucceededEvent -= submitScoreSucceededEvent; GPGManager.loadScoresFailedEvent -= loadScoresFailedEvent; GPGManager.loadScoresSucceededEvent -= loadScoresSucceededEvent; } void authenticationSucceededEvent( string param ) { Debug.Log( "authenticationSucceededEvent: " + param ); } void authenticationFailedEvent( string error ) { Debug.Log( "authenticationFailedEvent: " + error ); } void licenseCheckFailedEvent() { Debug.Log( "licenseCheckFailedEvent" ); } void profileImageLoadedAtPathEvent( string path ) { Debug.Log( "profileImageLoadedAtPathEvent: " + path ); } void finishedSharingEvent( string errorOrNull ) { Debug.Log( "finishedSharingEvent. errorOrNull param: " + errorOrNull ); } void userSignedOutEvent() { Debug.Log( "userSignedOutEvent" ); } void reloadDataForKeyFailedEvent( string error ) { Debug.Log( "reloadDataForKeyFailedEvent: " + error ); } void reloadDataForKeySucceededEvent( string param ) { Debug.Log( "reloadDataForKeySucceededEvent: " + param ); } void loadCloudDataForKeyFailedEvent( string error ) { Debug.Log( "loadCloudDataForKeyFailedEvent: " + error ); } void loadCloudDataForKeySucceededEvent( int key, string data ) { Debug.Log( "loadCloudDataForKeySucceededEvent:" + data ); } void updateCloudDataForKeyFailedEvent( string error ) { Debug.Log( "updateCloudDataForKeyFailedEvent: " + error ); } void updateCloudDataForKeySucceededEvent( int key, string data ) { Debug.Log( "updateCloudDataForKeySucceededEvent: " + data ); } void clearCloudDataForKeyFailedEvent( string error ) { Debug.Log( "clearCloudDataForKeyFailedEvent: " + error ); } void clearCloudDataForKeySucceededEvent( string param ) { Debug.Log( "clearCloudDataForKeySucceededEvent: " + param ); } void deleteCloudDataForKeyFailedEvent( string error ) { Debug.Log( "deleteCloudDataForKeyFailedEvent: " + error ); } void deleteCloudDataForKeySucceededEvent( string param ) { Debug.Log( "deleteCloudDataForKeySucceededEvent: " + param ); } void unlockAchievementFailedEvent( string achievementId, string error ) { Debug.Log( "unlockAchievementFailedEvent. achievementId: " + achievementId + ", error: " + error ); } void unlockAchievementSucceededEvent( string achievementId, bool newlyUnlocked ) { Debug.Log( "unlockAchievementSucceededEvent. achievementId: " + achievementId + ", newlyUnlocked: " + newlyUnlocked ); } void incrementAchievementFailedEvent( string achievementId, string error ) { Debug.Log( "incrementAchievementFailedEvent. achievementId: " + achievementId + ", error: " + error ); } void incrementAchievementSucceededEvent( string achievementId, bool newlyUnlocked ) { Debug.Log( "incrementAchievementSucceededEvent. achievementId: " + achievementId + ", newlyUnlocked: " + newlyUnlocked ); } void revealAchievementFailedEvent( string achievementId, string error ) { Debug.Log( "revealAchievementFailedEvent. achievementId: " + achievementId + ", error: " + error ); } void revealAchievementSucceededEvent( string achievementId ) { Debug.Log( "revealAchievementSucceededEvent: " + achievementId ); } void submitScoreFailedEvent( string leaderboardId, string error ) { Debug.Log( "submitScoreFailedEvent. leaderboardId: " + leaderboardId + ", error: " + error ); } void submitScoreSucceededEvent( string leaderboardId, Dictionary<string,object> scoreReport ) { Debug.Log( "submitScoreSucceededEvent" ); Prime31.Utils.logObject( scoreReport ); } void loadScoresFailedEvent( string leaderboardId, string error ) { Debug.Log( "loadScoresFailedEvent. leaderboardId: " + leaderboardId + ", error: " + error ); } void loadScoresSucceededEvent( List<GPGScore> scores ) { Debug.Log( "loadScoresSucceededEvent" ); Prime31.Utils.logObject( scores ); } #endif }
// 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 Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Internal.Log; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal class SolutionCrawlerLogger { private const string Id = nameof(Id); private const string Kind = nameof(Kind); private const string Analyzer = nameof(Analyzer); private const string DocumentCount = nameof(DocumentCount); private const string HighPriority = nameof(HighPriority); private const string Enabled = nameof(Enabled); private const string AnalyzerCount = nameof(AnalyzerCount); private const string PersistentStorage = nameof(PersistentStorage); private const string GlobalOperation = nameof(GlobalOperation); private const string HigherPriority = nameof(HigherPriority); private const string LowerPriority = nameof(LowerPriority); private const string TopLevel = nameof(TopLevel); private const string MemberLevel = nameof(MemberLevel); private const string NewWorkItem = nameof(NewWorkItem); private const string UpdateWorkItem = nameof(UpdateWorkItem); private const string ProjectEnqueue = nameof(ProjectEnqueue); private const string ResetStates = nameof(ResetStates); private const string ProjectNotExist = nameof(ProjectNotExist); private const string DocumentNotExist = nameof(DocumentNotExist); private const string ProcessProject = nameof(ProcessProject); private const string OpenDocument = nameof(OpenDocument); private const string CloseDocument = nameof(CloseDocument); private const string SolutionHash = nameof(SolutionHash); private const string ProcessDocument = nameof(ProcessDocument); private const string ProcessDocumentCancellation = nameof(ProcessDocumentCancellation); private const string ProcessProjectCancellation = nameof(ProcessProjectCancellation); private const string ActiveFileEnqueue = nameof(ActiveFileEnqueue); private const string ActiveFileProcessDocument = nameof(ActiveFileProcessDocument); private const string ActiveFileProcessDocumentCancellation = nameof(ActiveFileProcessDocumentCancellation); private const string Max = "Maximum"; private const string Min = "Minimum"; private const string Median = nameof(Median); private const string Mean = nameof(Mean); private const string Mode = nameof(Mode); private const string Range = nameof(Range); private const string Count = nameof(Count); public static void LogRegistration(int correlationId, Workspace workspace) { Logger.Log(FunctionId.WorkCoordinatorRegistrationService_Register, KeyValueLogMessage.Create(m => { m[Id] = correlationId; m[Kind] = workspace.Kind; })); } public static void LogUnregistration(int correlationId) { Logger.Log(FunctionId.WorkCoordinatorRegistrationService_Unregister, KeyValueLogMessage.Create(m => { m[Id] = correlationId; })); } public static void LogReanalyze(int correlationId, IIncrementalAnalyzer analyzer, IEnumerable<DocumentId> documentIds, bool highPriority) { Logger.Log(FunctionId.WorkCoordinatorRegistrationService_Reanalyze, KeyValueLogMessage.Create(m => { m[Id] = correlationId; m[Analyzer] = analyzer.ToString(); m[DocumentCount] = documentIds == null ? 0 : documentIds.Count(); m[HighPriority] = highPriority; })); } public static void LogOptionChanged(int correlationId, bool value) { Logger.Log(FunctionId.WorkCoordinator_SolutionCrawlerOption, KeyValueLogMessage.Create(m => { m[Id] = correlationId; m[Enabled] = value; })); } public static void LogActiveFileAnalyzers(int correlationId, Workspace workspace, ImmutableArray<IIncrementalAnalyzer> reordered) { LogAnalyzersWorker( FunctionId.IncrementalAnalyzerProcessor_ActiveFileAnalyzers, FunctionId.IncrementalAnalyzerProcessor_ActiveFileAnalyzer, correlationId, workspace, reordered); } public static void LogAnalyzers(int correlationId, Workspace workspace, ImmutableArray<IIncrementalAnalyzer> reordered) { LogAnalyzersWorker( FunctionId.IncrementalAnalyzerProcessor_Analyzers, FunctionId.IncrementalAnalyzerProcessor_Analyzer, correlationId, workspace, reordered); } private static void LogAnalyzersWorker( FunctionId analyzersId, FunctionId analyzerId, int correlationId, Workspace workspace, ImmutableArray<IIncrementalAnalyzer> reordered) { if (workspace.Kind == WorkspaceKind.Preview) { return; } // log registered analyzers. Logger.Log(analyzersId, KeyValueLogMessage.Create(m => { m[Id] = correlationId; m[AnalyzerCount] = reordered.Length; })); foreach (var analyzer in reordered) { Logger.Log(analyzerId, KeyValueLogMessage.Create(m => { m[Id] = correlationId; m[Analyzer] = analyzer.ToString(); })); } } public static void LogWorkCoordinatorShutdownTimeout(int correlationId) { Logger.Log(FunctionId.WorkCoordinator_ShutdownTimeout, KeyValueLogMessage.Create(m => { m[Id] = correlationId; })); } public static void LogWorkspaceEvent(LogAggregator logAggregator, int kind) { logAggregator.IncreaseCount(kind); } public static void LogWorkCoordinatorShutdown(int correlationId, LogAggregator logAggregator) { Logger.Log(FunctionId.WorkCoordinator_Shutdown, KeyValueLogMessage.Create(m => { m[Id] = correlationId; foreach (var kv in logAggregator) { var change = ((WorkspaceChangeKind)kv.Key).ToString(); m[change] = kv.Value.GetCount(); } })); } public static void LogGlobalOperation(LogAggregator logAggregator) { logAggregator.IncreaseCount(GlobalOperation); } public static void LogActiveFileEnqueue(LogAggregator logAggregator) { logAggregator.IncreaseCount(ActiveFileEnqueue); } public static void LogWorkItemEnqueue(LogAggregator logAggregator, ProjectId projectId) { logAggregator.IncreaseCount(ProjectEnqueue); } public static void LogWorkItemEnqueue( LogAggregator logAggregator, string language, DocumentId documentId, InvocationReasons reasons, bool lowPriority, SyntaxPath activeMember, bool added) { logAggregator.IncreaseCount(language); logAggregator.IncreaseCount(added ? NewWorkItem : UpdateWorkItem); if (documentId != null) { logAggregator.IncreaseCount(activeMember == null ? TopLevel : MemberLevel); if (lowPriority) { logAggregator.IncreaseCount(LowerPriority); logAggregator.IncreaseCount(ValueTuple.Create(LowerPriority, documentId.Id)); } } foreach (var reason in reasons) { logAggregator.IncreaseCount(reason); } } public static void LogHigherPriority(LogAggregator logAggregator, Guid documentId) { logAggregator.IncreaseCount(HigherPriority); logAggregator.IncreaseCount(ValueTuple.Create(HigherPriority, documentId)); } public static void LogResetStates(LogAggregator logAggregator) { logAggregator.IncreaseCount(ResetStates); } public static void LogIncrementalAnalyzerProcessorStatistics(int correlationId, Solution solution, LogAggregator logAggregator, ImmutableArray<IIncrementalAnalyzer> analyzers) { Logger.Log(FunctionId.IncrementalAnalyzerProcessor_Shutdown, KeyValueLogMessage.Create(m => { var solutionHash = GetSolutionHash(solution); m[Id] = correlationId; m[SolutionHash] = solutionHash.ToString(); var statMap = new Dictionary<string, List<int>>(); foreach (var kv in logAggregator) { if (kv.Key is string) { m[kv.Key.ToString()] = kv.Value.GetCount(); continue; } if (kv.Key is ValueTuple<string, Guid>) { var tuple = (ValueTuple<string, Guid>)kv.Key; var list = statMap.GetOrAdd(tuple.Item1, _ => new List<int>()); list.Add(kv.Value.GetCount()); continue; } throw ExceptionUtilities.Unreachable; } foreach (var kv in statMap) { var key = kv.Key.ToString(); var result = LogAggregator.GetStatistics(kv.Value); m[CreateProperty(key, Max)] = result.Maximum; m[CreateProperty(key, Min)] = result.Minimum; m[CreateProperty(key, Median)] = result.Median; m[CreateProperty(key, Mean)] = result.Mean; m[CreateProperty(key, Mode)] = result.Mode; m[CreateProperty(key, Range)] = result.Range; m[CreateProperty(key, Count)] = result.Count; } })); foreach (var analyzer in analyzers) { var diagIncrementalAnalyzer = analyzer as DiagnosticAnalyzerService.IncrementalAnalyzerDelegatee; if (diagIncrementalAnalyzer != null) { diagIncrementalAnalyzer.LogAnalyzerCountSummary(); break; } } } private static int GetSolutionHash(Solution solution) { if (solution != null && solution.FilePath != null) { return solution.FilePath.ToLowerInvariant().GetHashCode(); } return 0; } private static string CreateProperty(string parent, string child) { return parent + "." + child; } public static void LogProcessCloseDocument(LogAggregator logAggregator, Guid documentId) { logAggregator.IncreaseCount(CloseDocument); logAggregator.IncreaseCount(ValueTuple.Create(CloseDocument, documentId)); } public static void LogProcessOpenDocument(LogAggregator logAggregator, Guid documentId) { logAggregator.IncreaseCount(OpenDocument); logAggregator.IncreaseCount(ValueTuple.Create(OpenDocument, documentId)); } public static void LogProcessActiveFileDocument(LogAggregator logAggregator, Guid documentId, bool processed) { if (processed) { logAggregator.IncreaseCount(ActiveFileProcessDocument); } else { logAggregator.IncreaseCount(ActiveFileProcessDocumentCancellation); } } public static void LogProcessDocument(LogAggregator logAggregator, Guid documentId, bool processed) { if (processed) { logAggregator.IncreaseCount(ProcessDocument); } else { logAggregator.IncreaseCount(ProcessDocumentCancellation); } logAggregator.IncreaseCount(ValueTuple.Create(ProcessDocument, documentId)); } public static void LogProcessDocumentNotExist(LogAggregator logAggregator) { logAggregator.IncreaseCount(DocumentNotExist); } public static void LogProcessProject(LogAggregator logAggregator, Guid projectId, bool processed) { if (processed) { logAggregator.IncreaseCount(ProcessProject); } else { logAggregator.IncreaseCount(ProcessProjectCancellation); } logAggregator.IncreaseCount(ValueTuple.Create(ProcessProject, projectId)); } public static void LogProcessProjectNotExist(LogAggregator logAggregator) { logAggregator.IncreaseCount(ProjectNotExist); } } }
using HarmonyLib; using HarmonyLibTests.Assets; using NUnit.Framework; using System.Linq; namespace HarmonyLibTests.Patching { [TestFixture] public class StaticPatches : TestLogger { [Test] public void Test_Method0() { var originalClass = typeof(Class0); Assert.NotNull(originalClass); var originalMethod = originalClass.GetMethod("Method0"); Assert.NotNull(originalMethod); var patchClass = typeof(Class0Patch); var postfix = patchClass.GetMethod("Postfix"); Assert.NotNull(postfix); var instance = new Harmony("test"); Assert.NotNull(instance); var patcher = instance.CreateProcessor(originalMethod); Assert.NotNull(patcher); _ = patcher.AddPostfix(postfix); _ = patcher.Patch(); var result = new Class0().Method0(); Assert.AreEqual("patched", result); } [Test] public void Test_Method1() { var originalClass = typeof(Class1); Assert.NotNull(originalClass); var originalMethod = originalClass.GetMethod("Method1"); Assert.NotNull(originalMethod); var patchClass = typeof(Class1Patch); var prefix = patchClass.GetMethod("Prefix"); var postfix = patchClass.GetMethod("Postfix"); var transpiler = patchClass.GetMethod("Transpiler"); Assert.NotNull(prefix); Assert.NotNull(postfix); Assert.NotNull(transpiler); Class1Patch.ResetTest(); var instance = new Harmony("test"); Assert.NotNull(instance); var patcher = instance.CreateProcessor(originalMethod); Assert.NotNull(patcher); _ = patcher.AddPrefix(prefix); _ = patcher.AddPostfix(postfix); _ = patcher.AddTranspiler(transpiler); var originalMethodStartPre = Memory.GetMethodStart(originalMethod, out _); _ = patcher.Patch(); var originalMethodStartPost = Memory.GetMethodStart(originalMethod, out _); Assert.AreEqual(originalMethodStartPre, originalMethodStartPost); Class1.Method1(); Assert.True(Class1Patch.prefixed, "Prefix was not executed"); Assert.True(Class1Patch.originalExecuted, "Original was not executed"); Assert.True(Class1Patch.postfixed, "Postfix was not executed"); } [Test] public void Test_Method2() { var originalClass = typeof(Class2); Assert.NotNull(originalClass); var originalMethod = originalClass.GetMethod("Method2"); Assert.NotNull(originalMethod); var patchClass = typeof(Class2Patch); var prefix = patchClass.GetMethod("Prefix"); var postfix = patchClass.GetMethod("Postfix"); var transpiler = patchClass.GetMethod("Transpiler"); Assert.NotNull(prefix); Assert.NotNull(postfix); Assert.NotNull(transpiler); Class2Patch.ResetTest(); var instance = new Harmony("test"); Assert.NotNull(instance); var patcher = instance.CreateProcessor(originalMethod); Assert.NotNull(patcher); _ = patcher.AddPrefix(prefix); _ = patcher.AddPostfix(postfix); _ = patcher.AddTranspiler(transpiler); var originalMethodStartPre = Memory.GetMethodStart(originalMethod, out _); _ = patcher.Patch(); var originalMethodStartPost = Memory.GetMethodStart(originalMethod, out _); Assert.AreEqual(originalMethodStartPre, originalMethodStartPost); new Class2().Method2(); Assert.True(Class2Patch.prefixed, "Prefix was not executed"); Assert.True(Class2Patch.originalExecuted, "Original was not executed"); Assert.True(Class2Patch.postfixed, "Postfix was not executed"); } [Test] public void Test_Method4() { var originalClass = typeof(Class4); Assert.NotNull(originalClass); var originalMethod = originalClass.GetMethod("Method4"); Assert.NotNull(originalMethod); var patchClass = typeof(Class4Patch); var prefix = patchClass.GetMethod("Prefix"); Assert.NotNull(prefix); Class4Patch.ResetTest(); var instance = new Harmony("test"); Assert.NotNull(instance); var patcher = instance.CreateProcessor(originalMethod); Assert.NotNull(patcher); _ = patcher.AddPrefix(prefix); var originalMethodStartPre = Memory.GetMethodStart(originalMethod, out _); _ = patcher.Patch(); var originalMethodStartPost = Memory.GetMethodStart(originalMethod, out _); Assert.AreEqual(originalMethodStartPre, originalMethodStartPost); (new Class4()).Method4("foo"); Assert.True(Class4Patch.prefixed, "Prefix was not executed"); Assert.True(Class4Patch.originalExecuted, "Original was not executed"); Assert.AreEqual(Class4Patch.senderValue, "foo"); } [Test] public void Test_Method5() { var originalClass = typeof(Class5); Assert.NotNull(originalClass); var originalMethod = originalClass.GetMethod("Method5"); Assert.NotNull(originalMethod); var patchClass = typeof(Class5Patch); var prefix = patchClass.GetMethod("Prefix"); Assert.NotNull(prefix); var postfix = patchClass.GetMethod("Postfix"); Assert.NotNull(postfix); Class5Patch.ResetTest(); var instance = new Harmony("test"); Assert.NotNull(instance); var patcher = instance.CreateProcessor(originalMethod); Assert.NotNull(patcher); _ = patcher.AddPrefix(prefix); _ = patcher.AddPostfix(postfix); _ = patcher.Patch(); (new Class5()).Method5("foo"); Assert.True(Class5Patch.prefixed, "Prefix was not executed"); Assert.True(Class5Patch.postfixed, "Postfix was not executed"); } [Test] public void Test_PatchUnpatch() { var originalClass = typeof(Class9); Assert.NotNull(originalClass); var originalMethod = originalClass.GetMethod("ToString"); Assert.NotNull(originalMethod); var patchClass = typeof(Class9Patch); var prefix = patchClass.GetMethod("Prefix"); Assert.NotNull(prefix); var postfix = patchClass.GetMethod("Postfix"); Assert.NotNull(postfix); var instance = new Harmony("unpatch-all-test"); Assert.NotNull(instance); var patcher = instance.CreateProcessor(originalMethod); Assert.NotNull(patcher); _ = patcher.AddPrefix(prefix); _ = patcher.AddPostfix(postfix); _ = patcher.Patch(); var instanceB = new Harmony("test"); Assert.NotNull(instanceB); instanceB.UnpatchAll("unpatch-all-test"); } [Test] public void Test_Attributes() { var originalClass = typeof(AttributesClass); Assert.NotNull(originalClass); var originalMethod = originalClass.GetMethod("Method"); Assert.NotNull(originalMethod); Assert.AreEqual(originalMethod, AttributesPatch.Patch0()); var instance = new Harmony("test"); Assert.NotNull(instance); var patchClass = typeof(AttributesPatch); Assert.NotNull(patchClass); AttributesPatch.ResetTest(); var patcher = instance.CreateClassProcessor(patchClass); Assert.NotNull(patcher); Assert.NotNull(patcher.Patch()); (new AttributesClass()).Method("foo"); Assert.True(AttributesPatch.targeted, "TargetMethod was not executed"); Assert.True(AttributesPatch.postfixed, "Prefix was not executed"); Assert.True(AttributesPatch.postfixed, "Postfix was not executed"); } [Test] public void Test_Method10() { var originalClass = typeof(Class10); Assert.NotNull(originalClass); var originalMethod = originalClass.GetMethod("Method10"); Assert.NotNull(originalMethod); var patchClass = typeof(Class10Patch); var postfix = patchClass.GetMethod("Postfix"); Assert.NotNull(postfix); var instance = new Harmony("test"); Assert.NotNull(instance); var patcher = instance.CreateProcessor(originalMethod); Assert.NotNull(patcher); _ = patcher.AddPostfix(postfix); _ = patcher.Patch(); _ = new Class10().Method10(); Assert.True(Class10Patch.postfixed); Assert.True(Class10Patch.originalResult); } [Test] public void Test_MultiplePatches_One_Class() { var originalClass = typeof(MultiplePatches1); Assert.NotNull(originalClass); var originalMethod = originalClass.GetMethod("TestMethod"); Assert.NotNull(originalMethod); var instance = new Harmony("test"); Assert.NotNull(instance); var patchClass = typeof(MultiplePatches1Patch); Assert.NotNull(patchClass); MultiplePatches1.result = "before"; var patcher = instance.CreateClassProcessor(patchClass); Assert.NotNull(patcher); Assert.NotNull(patcher.Patch()); var result = (new MultiplePatches1()).TestMethod("after"); Assert.AreEqual("after,prefix2,prefix1", MultiplePatches1.result); Assert.AreEqual("ok,postfix", result); } [Test] public void Test_MultiplePatches_Multiple_Classes() { var originalClass = typeof(MultiplePatches2); Assert.NotNull(originalClass); var originalMethod = originalClass.GetMethod("TestMethod"); Assert.NotNull(originalMethod); var instance = new Harmony("test"); Assert.NotNull(instance); var patchClass1 = typeof(MultiplePatchesPatch2_Part1); Assert.NotNull(patchClass1); var patchClass2 = typeof(MultiplePatchesPatch2_Part2); Assert.NotNull(patchClass2); var patchClass3 = typeof(MultiplePatchesPatch2_Part3); Assert.NotNull(patchClass3); MultiplePatches2.result = "before"; var patcher1 = instance.CreateClassProcessor(patchClass1); Assert.NotNull(patcher1); Assert.NotNull(patcher1.Patch()); var patcher2 = instance.CreateClassProcessor(patchClass2); Assert.NotNull(patcher2); Assert.NotNull(patcher2.Patch()); var patcher3 = instance.CreateClassProcessor(patchClass3); Assert.NotNull(patcher3); Assert.NotNull(patcher3.Patch()); var result = (new MultiplePatches2()).TestMethod("hey"); Assert.AreEqual("hey,prefix2,prefix1", MultiplePatches2.result); Assert.AreEqual("patched", result); } [Test] public void Test_Finalizer_Patch_Order() { var instance = new Harmony("test"); Assert.NotNull(instance, "instance"); var processor = instance.CreateClassProcessor(typeof(Finalizer_Patch_Order_Patch)); Assert.NotNull(processor, "processor"); var methods = processor.Patch(); Assert.NotNull(methods, "methods"); Assert.AreEqual(1, methods.Count); Finalizer_Patch_Order_Patch.ResetTest(); var test = new Finalizer_Patch_Order_Class(); Assert.NotNull(test, "test"); var values = test.Method().ToList(); Assert.NotNull(values, "values"); Assert.AreEqual(3, values.Count); Assert.AreEqual(11, values[0]); Assert.AreEqual(21, values[1]); Assert.AreEqual(31, values[2]); // note that since passthrough postfixes are async, they run AFTER any finalizer // var actualEvents = Finalizer_Patch_Order_Patch.GetEvents(); var correctEvents = new string[] { "Bool_Prefix", "Void_Prefix", "Simple_Postfix", "NonModifying_Finalizer", "ClearException_Finalizer", "Void_Finalizer", "Passthrough_Postfix2 start", "Passthrough_Postfix1 start", "Yield 10 [old=1]", "Yield 11 [old=10]", "Yield 20 [old=2]", "Yield 21 [old=20]", "Yield 30 [old=3]", "Yield 31 [old=30]", "Passthrough_Postfix1 end", "Passthrough_Postfix2 end" }; Assert.True(actualEvents.SequenceEqual(correctEvents), "events"); } [Test] public void Test_Affecting_Original_Prefixes() { var instance = new Harmony("test"); Assert.NotNull(instance, "instance"); var processor = instance.CreateClassProcessor(typeof(Affecting_Original_Prefixes_Patch)); Assert.NotNull(processor, "processor"); var methods = processor.Patch(); Assert.NotNull(methods, "methods"); Assert.AreEqual(1, methods.Count); Affecting_Original_Prefixes_Patch.ResetTest(); var test = new Affecting_Original_Prefixes_Class(); Assert.NotNull(test, "test"); var value = test.Method(100); Assert.AreEqual("patched", value); // note that since passthrough postfixes are async, they run AFTER any finalizer // var events = Affecting_Original_Prefixes_Patch.GetEvents(); Assert.AreEqual(4, events.Count, "event count"); Assert.AreEqual("Prefix1", events[0]); Assert.AreEqual("Prefix2", events[1]); Assert.AreEqual("Prefix3", events[2]); Assert.AreEqual("Prefix5", events[3]); } [Test] public void Test_Class18() { var instance = new Harmony("test"); Assert.NotNull(instance, "instance"); var processor = instance.CreateClassProcessor(typeof(Class18Patch)); Assert.NotNull(processor, "processor"); var methods = processor.Patch(); Assert.NotNull(methods, "methods"); Assert.AreEqual(1, methods.Count); Class18Patch.prefixExecuted = false; var color = Class18.GetDefaultNameplateColor(new APIUser()); Assert.IsTrue(Class18Patch.prefixExecuted, "prefixExecuted"); Assert.AreEqual((float)1, color.r); } [Test] public void Test_Class22() { var instance = new Harmony("test"); Assert.NotNull(instance, "instance"); var original = SymbolExtensions.GetMethodInfo(() => Class22.Method22()); Assert.NotNull(original, "original"); var prefix1 = SymbolExtensions.GetMethodInfo(() => Class22.Prefix1(false)); Assert.NotNull(original, "prefix1"); var prefix2 = SymbolExtensions.GetMethodInfo(() => Class22.Prefix2(false)); Assert.NotNull(original, "prefix2"); var patched1 = instance.Patch(original, new HarmonyMethod(prefix1)); Assert.NotNull(patched1, "patched1"); var patched2 = instance.Patch(original, new HarmonyMethod(prefix2)); Assert.NotNull(patched2, "patched2"); Class22.bool1 = null; Class22.bool2 = null; Class22.Method22(); Assert.NotNull(Class22.bool1, "Class22.bool1"); Assert.NotNull(Class22.bool2, "Class22.bool2"); Assert.IsTrue(Class22.bool1.Value, "Class22.bool1.Value"); Assert.IsFalse(Class22.bool2.Value, "Class22.bool2.Value"); } } }
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.Rendering.PostProcessing; using UnityEditorInternal; using System.IO; namespace UnityEditor.Rendering.PostProcessing { using SerializedBundleRef = PostProcessLayer.SerializedBundleRef; using EXRFlags = Texture2D.EXRFlags; [CanEditMultipleObjects, CustomEditor(typeof(PostProcessLayer))] public sealed class PostProcessLayerEditor : BaseEditor<PostProcessLayer> { SerializedProperty m_StopNaNPropagation; SerializedProperty m_VolumeTrigger; SerializedProperty m_VolumeLayer; SerializedProperty m_AntialiasingMode; SerializedProperty m_TaaJitterSpread; SerializedProperty m_TaaSharpness; SerializedProperty m_TaaStationaryBlending; SerializedProperty m_TaaMotionBlending; SerializedProperty m_SmaaQuality; SerializedProperty m_FxaaFastMode; SerializedProperty m_FxaaKeepAlpha; SerializedProperty m_FogEnabled; SerializedProperty m_FogExcludeSkybox; SerializedProperty m_ShowToolkit; SerializedProperty m_ShowCustomSorter; Dictionary<PostProcessEvent, ReorderableList> m_CustomLists; static GUIContent[] s_AntialiasingMethodNames = { new GUIContent("No Anti-aliasing"), new GUIContent("Fast Approximate Anti-aliasing (FXAA)"), new GUIContent("Subpixel Morphological Anti-aliasing (SMAA)"), new GUIContent("Temporal Anti-aliasing (TAA)") }; enum ExportMode { FullFrame, DisablePost, BreakBeforeColorGradingLinear, BreakBeforeColorGradingLog } void OnEnable() { m_StopNaNPropagation = FindProperty(x => x.stopNaNPropagation); m_VolumeTrigger = FindProperty(x => x.volumeTrigger); m_VolumeLayer = FindProperty(x => x.volumeLayer); m_AntialiasingMode = FindProperty(x => x.antialiasingMode); m_TaaJitterSpread = FindProperty(x => x.temporalAntialiasing.jitterSpread); m_TaaSharpness = FindProperty(x => x.temporalAntialiasing.sharpness); m_TaaStationaryBlending = FindProperty(x => x.temporalAntialiasing.stationaryBlending); m_TaaMotionBlending = FindProperty(x => x.temporalAntialiasing.motionBlending); m_SmaaQuality = FindProperty(x => x.subpixelMorphologicalAntialiasing.quality); m_FxaaFastMode = FindProperty(x => x.fastApproximateAntialiasing.fastMode); m_FxaaKeepAlpha = FindProperty(x => x.fastApproximateAntialiasing.keepAlpha); m_FogEnabled = FindProperty(x => x.fog.enabled); m_FogExcludeSkybox = FindProperty(x => x.fog.excludeSkybox); m_ShowToolkit = serializedObject.FindProperty("m_ShowToolkit"); m_ShowCustomSorter = serializedObject.FindProperty("m_ShowCustomSorter"); } void OnDisable() { m_CustomLists = null; } public override void OnInspectorGUI() { serializedObject.Update(); var camera = m_Target.GetComponent<Camera>(); #if !UNITY_2017_2_OR_NEWER if (RuntimeUtilities.isSinglePassStereoSelected) EditorGUILayout.HelpBox("Unity 2017.2+ required for full Single-pass stereo rendering support.", MessageType.Warning); #endif DoVolumeBlending(); DoAntialiasing(); DoFog(camera); EditorGUILayout.PropertyField(m_StopNaNPropagation, EditorUtilities.GetContent("Stop NaN Propagation|Automatically replaces NaN/Inf in shaders by a black pixel to avoid breaking some effects. This will slightly affect performances and should only be used if you experience NaN issues that you can't fix. Has no effect on GLES2 platforms.")); EditorGUILayout.Space(); DoToolkit(); DoCustomEffectSorter(); EditorUtilities.DrawSplitter(); EditorGUILayout.Space(); serializedObject.ApplyModifiedProperties(); } void DoVolumeBlending() { EditorGUILayout.LabelField(EditorUtilities.GetContent("Volume blending"), EditorStyles.boldLabel); EditorGUI.indentLevel++; { // The layout system sort of break alignement when mixing inspector fields with // custom layouted fields, do the layout manually instead var indentOffset = EditorGUI.indentLevel * 15f; var lineRect = GUILayoutUtility.GetRect(1, EditorGUIUtility.singleLineHeight); var labelRect = new Rect(lineRect.x, lineRect.y, EditorGUIUtility.labelWidth - indentOffset, lineRect.height); var fieldRect = new Rect(labelRect.xMax, lineRect.y, lineRect.width - labelRect.width - 60f, lineRect.height); var buttonRect = new Rect(fieldRect.xMax, lineRect.y, 60f, lineRect.height); EditorGUI.PrefixLabel(labelRect, EditorUtilities.GetContent("Trigger|A transform that will act as a trigger for volume blending.")); m_VolumeTrigger.objectReferenceValue = (Transform)EditorGUI.ObjectField(fieldRect, m_VolumeTrigger.objectReferenceValue, typeof(Transform), true); if (GUI.Button(buttonRect, EditorUtilities.GetContent("This|Assigns the current GameObject as a trigger."), EditorStyles.miniButton)) m_VolumeTrigger.objectReferenceValue = m_Target.transform; if (m_VolumeTrigger.objectReferenceValue == null) EditorGUILayout.HelpBox("No trigger has been set, the camera will only be affected by global volumes.", MessageType.Info); EditorGUILayout.PropertyField(m_VolumeLayer, EditorUtilities.GetContent("Layer|This camera will only be affected by volumes in the selected scene-layers.")); int mask = m_VolumeLayer.intValue; if (mask == 0) EditorGUILayout.HelpBox("No layer has been set, the trigger will never be affected by volumes.", MessageType.Warning); else if (mask == -1 || ((mask & 1) != 0)) EditorGUILayout.HelpBox("Do not use \"Everything\" or \"Default\" as a layer mask as it will slow down the volume blending process! Put post-processing volumes in their own dedicated layer for best performances.", MessageType.Warning); } EditorGUI.indentLevel--; EditorGUILayout.Space(); } void DoAntialiasing() { EditorGUILayout.LabelField(EditorUtilities.GetContent("Anti-aliasing"), EditorStyles.boldLabel); EditorGUI.indentLevel++; { m_AntialiasingMode.intValue = EditorGUILayout.Popup(EditorUtilities.GetContent("Mode|The anti-aliasing method to use. FXAA is fast but low quality. SMAA works well for non-HDR scenes. TAA is a bit slower but higher quality and works well with HDR."), m_AntialiasingMode.intValue, s_AntialiasingMethodNames); if (m_AntialiasingMode.intValue == (int)PostProcessLayer.Antialiasing.TemporalAntialiasing) { #if !UNITY_2017_3_OR_NEWER if (RuntimeUtilities.isSinglePassStereoSelected) EditorGUILayout.HelpBox("TAA requires Unity 2017.3+ for Single-pass stereo rendering support.", MessageType.Warning); #endif EditorGUILayout.PropertyField(m_TaaJitterSpread); EditorGUILayout.PropertyField(m_TaaStationaryBlending); EditorGUILayout.PropertyField(m_TaaMotionBlending); EditorGUILayout.PropertyField(m_TaaSharpness); } else if (m_AntialiasingMode.intValue == (int)PostProcessLayer.Antialiasing.SubpixelMorphologicalAntialiasing) { if (RuntimeUtilities.isSinglePassStereoSelected) EditorGUILayout.HelpBox("SMAA doesn't work with Single-pass stereo rendering.", MessageType.Warning); EditorGUILayout.PropertyField(m_SmaaQuality); if (m_SmaaQuality.intValue != (int)SubpixelMorphologicalAntialiasing.Quality.Low && EditorUtilities.isTargetingConsolesOrMobiles) EditorGUILayout.HelpBox("For performance reasons it is recommended to use Low Quality on mobile and console platforms.", MessageType.Warning); } else if (m_AntialiasingMode.intValue == (int)PostProcessLayer.Antialiasing.FastApproximateAntialiasing) { EditorGUILayout.PropertyField(m_FxaaFastMode); EditorGUILayout.PropertyField(m_FxaaKeepAlpha); if (!m_FxaaFastMode.boolValue && EditorUtilities.isTargetingConsolesOrMobiles) EditorGUILayout.HelpBox("For performance reasons it is recommended to use Fast Mode on mobile and console platforms.", MessageType.Warning); } } EditorGUI.indentLevel--; EditorGUILayout.Space(); } void DoFog(Camera camera) { if (camera == null || camera.actualRenderingPath != RenderingPath.DeferredShading) return; EditorGUILayout.LabelField(EditorUtilities.GetContent("Deferred Fog"), EditorStyles.boldLabel); EditorGUI.indentLevel++; { EditorGUILayout.PropertyField(m_FogEnabled); if (m_FogEnabled.boolValue) { EditorGUILayout.PropertyField(m_FogExcludeSkybox); EditorGUILayout.HelpBox("This adds fog compatibility to the deferred rendering path; actual fog settings should be set in the Lighting panel.", MessageType.Info); } } EditorGUI.indentLevel--; EditorGUILayout.Space(); } void DoToolkit() { EditorUtilities.DrawSplitter(); m_ShowToolkit.boolValue = EditorUtilities.DrawHeader("Toolkit", m_ShowToolkit.boolValue); if (m_ShowToolkit.boolValue) { GUILayout.Space(2); if (GUILayout.Button(EditorUtilities.GetContent("Export frame to EXR..."), EditorStyles.miniButton)) { var menu = new GenericMenu(); menu.AddItem(EditorUtilities.GetContent("Full Frame (as displayed)"), false, () => ExportFrameToExr(ExportMode.FullFrame)); menu.AddItem(EditorUtilities.GetContent("Disable post-processing"), false, () => ExportFrameToExr(ExportMode.DisablePost)); menu.AddItem(EditorUtilities.GetContent("Break before Color Grading (Linear)"), false, () => ExportFrameToExr(ExportMode.BreakBeforeColorGradingLinear)); menu.AddItem(EditorUtilities.GetContent("Break before Color Grading (Log)"), false, () => ExportFrameToExr(ExportMode.BreakBeforeColorGradingLog)); menu.ShowAsContext(); } if (GUILayout.Button(EditorUtilities.GetContent("Select all layer volumes|Selects all the volumes that will influence this layer."), EditorStyles.miniButton)) { var volumes = RuntimeUtilities.GetAllSceneObjects<PostProcessVolume>() .Where(x => (m_VolumeLayer.intValue & (1 << x.gameObject.layer)) != 0) .Select(x => x.gameObject) .Cast<UnityEngine.Object>() .ToArray(); if (volumes.Length > 0) Selection.objects = volumes; } if (GUILayout.Button(EditorUtilities.GetContent("Select all active volumes|Selects all volumes currently affecting the layer."), EditorStyles.miniButton)) { var volumes = new List<PostProcessVolume>(); PostProcessManager.instance.GetActiveVolumes(m_Target, volumes); if (volumes.Count > 0) { Selection.objects = volumes .Select(x => x.gameObject) .Cast<UnityEngine.Object>() .ToArray(); } } GUILayout.Space(3); } } void DoCustomEffectSorter() { EditorUtilities.DrawSplitter(); m_ShowCustomSorter.boolValue = EditorUtilities.DrawHeader("Custom Effect Sorting", m_ShowCustomSorter.boolValue); if (m_ShowCustomSorter.boolValue) { bool isInPrefab = false; // Init lists if needed if (m_CustomLists == null) { // In some cases the editor will refresh before components which means // components might not have been fully initialized yet. In this case we also // need to make sure that we're not in a prefab as sorteBundles isn't a // serializable object and won't exist until put on a scene. if (m_Target.sortedBundles == null) { isInPrefab = string.IsNullOrEmpty(m_Target.gameObject.scene.name); if (!isInPrefab) { // sortedBundles will be initialized and ready to use on the next frame Repaint(); } } else { // Create a reorderable list for each injection event m_CustomLists = new Dictionary<PostProcessEvent, ReorderableList>(); foreach (var evt in Enum.GetValues(typeof(PostProcessEvent)).Cast<PostProcessEvent>()) { var bundles = m_Target.sortedBundles[evt]; var listName = ObjectNames.NicifyVariableName(evt.ToString()); var list = new ReorderableList(bundles, typeof(SerializedBundleRef), true, true, false, false); list.drawHeaderCallback = (rect) => { EditorGUI.LabelField(rect, listName); }; list.drawElementCallback = (rect, index, isActive, isFocused) => { var sbr = (SerializedBundleRef)list.list[index]; EditorGUI.LabelField(rect, sbr.bundle.attribute.menuItem); }; list.onReorderCallback = (l) => { EditorUtility.SetDirty(m_Target); }; m_CustomLists.Add(evt, list); } } } GUILayout.Space(5); if (isInPrefab) { EditorGUILayout.HelpBox("Not supported in prefabs.", MessageType.Info); GUILayout.Space(3); return; } bool anyList = false; if (m_CustomLists != null) { foreach (var kvp in m_CustomLists) { var list = kvp.Value; // Skip empty lists to avoid polluting the inspector if (list.count == 0) continue; list.DoLayoutList(); anyList = true; } } if (!anyList) { EditorGUILayout.HelpBox("No custom effect loaded.", MessageType.Info); GUILayout.Space(3); } } } void ExportFrameToExr(ExportMode mode) { string path = EditorUtility.SaveFilePanel("Export EXR...", "", "Frame", "exr"); if (string.IsNullOrEmpty(path)) return; EditorUtility.DisplayProgressBar("Export EXR", "Rendering...", 0f); var camera = m_Target.GetComponent<Camera>(); var w = camera.pixelWidth; var h = camera.pixelHeight; var texOut = new Texture2D(w, h, TextureFormat.RGBAFloat, false, true); var target = RenderTexture.GetTemporary(w, h, 24, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear); var lastActive = RenderTexture.active; var lastTargetSet = camera.targetTexture; var lastPostFXState = m_Target.enabled; var lastBreakColorGradingState = m_Target.breakBeforeColorGrading; if (mode == ExportMode.DisablePost) m_Target.enabled = false; else if (mode == ExportMode.BreakBeforeColorGradingLinear || mode == ExportMode.BreakBeforeColorGradingLog) m_Target.breakBeforeColorGrading = true; camera.targetTexture = target; camera.Render(); camera.targetTexture = lastTargetSet; EditorUtility.DisplayProgressBar("Export EXR", "Reading...", 0.25f); m_Target.enabled = lastPostFXState; m_Target.breakBeforeColorGrading = lastBreakColorGradingState; if (mode == ExportMode.BreakBeforeColorGradingLog) { // Convert to log var material = new Material(Shader.Find("Hidden/PostProcessing/Editor/ConvertToLog")); var newTarget = RenderTexture.GetTemporary(w, h, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear); Graphics.Blit(target, newTarget, material, 0); RenderTexture.ReleaseTemporary(target); DestroyImmediate(material); target = newTarget; } RenderTexture.active = target; texOut.ReadPixels(new Rect(0, 0, w, h), 0, 0); texOut.Apply(); RenderTexture.active = lastActive; EditorUtility.DisplayProgressBar("Export EXR", "Encoding...", 0.5f); var bytes = texOut.EncodeToEXR(EXRFlags.OutputAsFloat | EXRFlags.CompressZIP); EditorUtility.DisplayProgressBar("Export EXR", "Saving...", 0.75f); File.WriteAllBytes(path, bytes); EditorUtility.ClearProgressBar(); AssetDatabase.Refresh(); RenderTexture.ReleaseTemporary(target); DestroyImmediate(texOut); } } }
// Copyright (c) MOSA Project. Licensed under the New BSD License. using Mosa.Compiler.Common; using Mosa.Compiler.Framework; using Mosa.Compiler.Framework.Stages; using Mosa.Compiler.Linker.Elf; using Mosa.Compiler.MosaTypeSystem; using Mosa.Platform.x86.Stages; using System.Diagnostics; namespace Mosa.Platform.x86 { /// <summary> /// This class provides a common base class for architecture /// specific operations. /// </summary> public class Architecture : BaseArchitecture { /// <summary> /// Gets the endianness of the target architecture. /// </summary> /// <value> /// The endianness. /// </value> public override Endianness Endianness { get { return Endianness.Little; } } /// <summary> /// Gets the type of the elf machine. /// </summary> /// <value> /// The type of the elf machine. /// </value> public override MachineType MachineType { get { return MachineType.Intel386; } } /// <summary> /// Defines the register set of the target architecture. /// </summary> private static readonly Register[] registers = new Register[] { //////////////////////////////////////////////////////// // 32-bit general purpose registers //////////////////////////////////////////////////////// GeneralPurposeRegister.EAX, GeneralPurposeRegister.ECX, GeneralPurposeRegister.EDX, GeneralPurposeRegister.EBX, GeneralPurposeRegister.ESP, GeneralPurposeRegister.EBP, GeneralPurposeRegister.ESI, GeneralPurposeRegister.EDI, //////////////////////////////////////////////////////// // SSE 128-bit floating point registers //////////////////////////////////////////////////////// SSE2Register.XMM0, SSE2Register.XMM1, SSE2Register.XMM2, SSE2Register.XMM3, SSE2Register.XMM4, SSE2Register.XMM5, SSE2Register.XMM6, SSE2Register.XMM7, //////////////////////////////////////////////////////// // Segmentation Registers //////////////////////////////////////////////////////// //SegmentRegister.CS, //SegmentRegister.DS, //SegmentRegister.ES, //SegmentRegister.FS, //SegmentRegister.GS, //SegmentRegister.SS }; /// <summary> /// Specifies the architecture features to use in generated code. /// </summary> private ArchitectureFeatureFlags architectureFeatures; /// <summary> /// Initializes a new instance of the <see cref="Architecture"/> class. /// </summary> /// <param name="architectureFeatures">The features this architecture supports.</param> private Architecture(ArchitectureFeatureFlags architectureFeatures) { this.architectureFeatures = architectureFeatures; CallingConvention = new DefaultCallingConvention(this); } /// <summary> /// Retrieves the native integer size of the x86 platform. /// </summary> /// <value>This property always returns 32.</value> public override int NativeIntegerSize { get { return 32; } } /// <summary> /// Gets the native alignment of the architecture in bytes. /// </summary> /// <value>This property always returns 4.</value> public override int NativeAlignment { get { return 4; } } /// <summary> /// Gets the native size of architecture in bytes. /// </summary> /// <value>This property always returns 4.</value> public override int NativePointerSize { get { return 4; } } /// <summary> /// Retrieves the register set of the x86 platform. /// </summary> public override Register[] RegisterSet { get { return registers; } } /// <summary> /// Retrieves the stack frame register of the x86. /// </summary> public override Register StackFrameRegister { get { return GeneralPurposeRegister.EBP; } } /// <summary> /// Retrieves the stack pointer register of the x86. /// </summary> public override Register StackPointerRegister { get { return GeneralPurposeRegister.ESP; } } /// <summary> /// Retrieves the exception register of the architecture. /// </summary> public override Register ExceptionRegister { get { return GeneralPurposeRegister.EDI; } } /// <summary> /// Gets the finally return block register. /// </summary> public override Register LeaveTargetRegister { get { return GeneralPurposeRegister.ESI; } } /// <summary> /// Retrieves the program counter register of the x86. /// </summary> public override Register ProgramCounter { get { return null; } } /// <summary> /// Gets the name of the platform. /// </summary> /// <value> /// The name of the platform. /// </value> public override string PlatformName { get { return "x86"; } } /// <summary> /// Factory method for the Architecture class. /// </summary> /// <returns>The created architecture instance.</returns> /// <param name="architectureFeatures">The features available in the architecture and code generation.</param> /// <remarks> /// This method creates an instance of an appropriate architecture class, which supports the specific /// architecture features. /// </remarks> public static BaseArchitecture CreateArchitecture(ArchitectureFeatureFlags architectureFeatures) { if (architectureFeatures == ArchitectureFeatureFlags.AutoDetect) architectureFeatures = ArchitectureFeatureFlags.MMX | ArchitectureFeatureFlags.SSE | ArchitectureFeatureFlags.SSE2 | ArchitectureFeatureFlags.SSE3 | ArchitectureFeatureFlags.SSE4; return new Architecture(architectureFeatures); } /// <summary> /// Extends the pre-compiler pipeline with x86 compiler stages. /// </summary> /// <param name="compilerPipeline">The pipeline to extend.</param> public override void ExtendCompilerPipeline(CompilerPipeline compilerPipeline) { compilerPipeline.Add( new StartUpStage() ); compilerPipeline.Add( new InterruptVectorStage() ); compilerPipeline.Add( new SSEInitStage() ); } /// <summary> /// Extends the method compiler pipeline with x86 specific stages. /// </summary> /// <param name="methodCompilerPipeline">The method compiler pipeline to extend.</param> public override void ExtendMethodCompilerPipeline(CompilerPipeline methodCompilerPipeline) { methodCompilerPipeline.InsertAfterLast<PlatformStubStage>( new IMethodCompilerStage[] { //new CheckOperandCountStage(), new PlatformIntrinsicStage(), new LongOperandTransformationStage(), new IRTransformationStage(), //new StopStage(), new TweakTransformationStage(), new FixedRegisterAssignmentStage(), new SimpleDeadCodeRemovalStage(), new AddressModeConversionStage(), new FloatingPointStage(), }); methodCompilerPipeline.InsertAfterLast<StackLayoutStage>( new BuildStackStage() ); methodCompilerPipeline.InsertBefore<CodeGenerationStage>( new FinalTweakTransformationStage() ); methodCompilerPipeline.InsertBefore<CodeGenerationStage>( new JumpOptimizationStage() ); methodCompilerPipeline.InsertBefore<CodeGenerationStage>( new ConversionPhaseStage() ); } /// <summary> /// Gets the type memory requirements. /// </summary> /// <param name="typeLayout">The type layouts.</param> /// <param name="type">The type.</param> /// <param name="size">Receives the memory size of the type.</param> /// <param name="alignment">Receives alignment requirements of the type.</param> public override void GetTypeRequirements(MosaTypeLayout typeLayout, MosaType type, out int size, out int alignment) { alignment = 4; size = type.IsValueType ? typeLayout.GetTypeSize(type) : 4; } /// <summary> /// Gets the code emitter. /// </summary> /// <returns></returns> public override BaseCodeEmitter GetCodeEmitter() { return new MachineCodeEmitter(); } /// <summary> /// Create platform move. /// </summary> /// <param name="context">The context.</param> /// <param name="destination">The destination.</param> /// <param name="source">The source.</param> public override void InsertMoveInstruction(Context context, Operand destination, Operand source) { var instruction = BaseTransformationStage.GetMove(destination, source); context.AppendInstruction(instruction, /*size,*/ destination, source); } /// <summary> /// Create platform compound move. /// </summary> /// <param name="context">The context.</param> /// <param name="destination">The destination.</param> /// <param name="source">The source.</param> /// <param name="size">The size.</param> public override void InsertCompoundMoveInstruction(BaseMethodCompiler compiler, Context context, Operand destination, Operand source, int size) { Debug.Assert(size > 0); Debug.Assert(source.IsMemoryAddress && destination.IsMemoryAddress); const int LargeAlignment = 16; int alignedSize = size - (size % NativeAlignment); int largeAlignedTypeSize = size - (size % LargeAlignment); var srcReg = compiler.CreateVirtualRegister(destination.Type.TypeSystem.BuiltIn.I4); var dstReg = compiler.CreateVirtualRegister(destination.Type.TypeSystem.BuiltIn.I4); var tmp = compiler.CreateVirtualRegister(destination.Type.TypeSystem.BuiltIn.I4); var tmpLarge = Operand.CreateCPURegister(destination.Type.TypeSystem.BuiltIn.Void, SSE2Register.XMM1); context.AppendInstruction(X86.Lea, srcReg, source); context.AppendInstruction(X86.Lea, dstReg, destination); for (int i = 0; i < largeAlignedTypeSize; i += LargeAlignment) { // Large aligned moves allow 128bits to be copied at a time var index = Operand.CreateConstant(destination.Type.TypeSystem.BuiltIn.I4, i); context.AppendInstruction(X86.MovupsLoad, InstructionSize.Size128, tmpLarge, srcReg, index); context.AppendInstruction(X86.MovupsStore, InstructionSize.Size128, null, dstReg, index, tmpLarge); } for (int i = largeAlignedTypeSize; i < alignedSize; i += NativeAlignment) { var index = Operand.CreateConstant(destination.Type.TypeSystem.BuiltIn.I4, i); context.AppendInstruction(X86.MovLoad, InstructionSize.Size32, tmp, srcReg, index); context.AppendInstruction(X86.MovStore, InstructionSize.Size32, null, dstReg, index, tmp); } for (int i = alignedSize; i < size; i++) { var index = Operand.CreateConstant(destination.Type.TypeSystem.BuiltIn.I4, i); context.AppendInstruction(X86.MovLoad, InstructionSize.Size8, tmp, srcReg, index); context.AppendInstruction(X86.MovStore, InstructionSize.Size8, null, dstReg, index, tmp); } } /// <summary> /// Creates the swap. /// </summary> /// <param name="context">The context.</param> /// <param name="destination">The destination.</param> /// <param name="source">The source.</param> public override void InsertExchangeInstruction(Context context, Operand destination, Operand source) { if (source.IsR4) { // TODO throw new CompilerException("R4 not implemented in InsertExchangeInstruction method"); } else if (source.IsR8) { // TODO throw new CompilerException("R8 not implemented in InsertExchangeInstruction method"); } else { context.AppendInstruction2(X86.Xchg, destination, source, source, destination); } } /// <summary> /// Inserts the jump instruction. /// </summary> /// <param name="context">The context.</param> /// <param name="destination">The destination.</param> /// <param name="source">The source.</param> public override void InsertJumpInstruction(Context context, Operand destination) { context.AppendInstruction(X86.Jmp, destination); } /// <summary> /// Inserts the jump instruction. /// </summary> /// <param name="context">The context.</param> /// <param name="Destination">The destination.</param> public override void InsertJumpInstruction(Context context, BasicBlock destination) { context.AppendInstruction(X86.Jmp, destination); } /// <summary> /// Inserts the call instruction. /// </summary> /// <param name="context">The context.</param> /// <param name="source">The source.</param> public override void InsertCallInstruction(Context context, Operand source) { context.AppendInstruction(X86.Call, null, source); } /// <summary> /// Inserts the address of instruction. /// </summary> /// <param name="context">The context.</param> /// <param name="destination">The destination.</param> /// <param name="source">The source.</param> public override void InsertAddressOfInstruction(Context context, Operand destination, Operand source) { context.AppendInstruction(X86.Lea, destination, source); } /// <summary> /// Inserts the add instruction. /// </summary> /// <param name="context">The context.</param> /// <param name="Destination">The destination.</param> /// <param name="Source">The source.</param> public override void InsertAddInstruction(Context context, Operand destination, Operand source1, Operand source2) { Debug.Assert(source1 == destination); context.AppendInstruction(X86.Add, destination, source1, source2); } /// <summary> /// Inserts the sub instruction. /// </summary> /// <param name="context">The context.</param> /// <param name="Destination">The destination.</param> /// <param name="Source">The source.</param> public override void InsertSubInstruction(Context context, Operand destination, Operand source1, Operand source2) { Debug.Assert(source1 == destination); context.AppendInstruction(X86.Sub, destination, source1, source2); } /// <summary> /// Determines whether [is instruction move] [the specified instruction]. /// </summary> /// <param name="instruction">The instruction.</param> /// <returns></returns> public override bool IsInstructionMove(BaseInstruction instruction) { return (instruction == X86.Mov || instruction == X86.Movsd || instruction == X86.Movss); } } }
namespace java.util.concurrent { [global::MonoJavaBridge.JavaClass(typeof(global::java.util.concurrent.TimeUnit_))] public abstract partial class TimeUnit : java.lang.Enum { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static TimeUnit() { InitJNI(); } protected TimeUnit(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _values15728; public static global::java.util.concurrent.TimeUnit[] values() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.util.concurrent.TimeUnit>(@__env.CallStaticObjectMethod(java.util.concurrent.TimeUnit.staticClass, global::java.util.concurrent.TimeUnit._values15728)) as java.util.concurrent.TimeUnit[]; } internal static global::MonoJavaBridge.MethodId _valueOf15729; public static global::java.util.concurrent.TimeUnit valueOf(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.util.concurrent.TimeUnit.staticClass, global::java.util.concurrent.TimeUnit._valueOf15729, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.util.concurrent.TimeUnit; } internal static global::MonoJavaBridge.MethodId _sleep15730; public virtual void sleep(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.util.concurrent.TimeUnit._sleep15730, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.util.concurrent.TimeUnit.staticClass, global::java.util.concurrent.TimeUnit._sleep15730, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _toNanos15731; public virtual long toNanos(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::java.util.concurrent.TimeUnit._toNanos15731, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::java.util.concurrent.TimeUnit.staticClass, global::java.util.concurrent.TimeUnit._toNanos15731, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _convert15732; public virtual long convert(long arg0, java.util.concurrent.TimeUnit arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::java.util.concurrent.TimeUnit._convert15732, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::java.util.concurrent.TimeUnit.staticClass, global::java.util.concurrent.TimeUnit._convert15732, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _toMicros15733; public virtual long toMicros(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::java.util.concurrent.TimeUnit._toMicros15733, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::java.util.concurrent.TimeUnit.staticClass, global::java.util.concurrent.TimeUnit._toMicros15733, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _toMillis15734; public virtual long toMillis(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::java.util.concurrent.TimeUnit._toMillis15734, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::java.util.concurrent.TimeUnit.staticClass, global::java.util.concurrent.TimeUnit._toMillis15734, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _toSeconds15735; public virtual long toSeconds(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::java.util.concurrent.TimeUnit._toSeconds15735, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::java.util.concurrent.TimeUnit.staticClass, global::java.util.concurrent.TimeUnit._toSeconds15735, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _toMinutes15736; public virtual long toMinutes(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::java.util.concurrent.TimeUnit._toMinutes15736, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::java.util.concurrent.TimeUnit.staticClass, global::java.util.concurrent.TimeUnit._toMinutes15736, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _toHours15737; public virtual long toHours(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::java.util.concurrent.TimeUnit._toHours15737, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::java.util.concurrent.TimeUnit.staticClass, global::java.util.concurrent.TimeUnit._toHours15737, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _toDays15738; public virtual long toDays(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::java.util.concurrent.TimeUnit._toDays15738, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::java.util.concurrent.TimeUnit.staticClass, global::java.util.concurrent.TimeUnit._toDays15738, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _timedWait15739; public virtual void timedWait(java.lang.Object arg0, long arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.util.concurrent.TimeUnit._timedWait15739, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.util.concurrent.TimeUnit.staticClass, global::java.util.concurrent.TimeUnit._timedWait15739, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _timedJoin15740; public virtual void timedJoin(java.lang.Thread arg0, long arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::java.util.concurrent.TimeUnit._timedJoin15740, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::java.util.concurrent.TimeUnit.staticClass, global::java.util.concurrent.TimeUnit._timedJoin15740, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.FieldId _NANOSECONDS15741; public static global::java.util.concurrent.TimeUnit NANOSECONDS { get { return default(global::java.util.concurrent.TimeUnit); } } internal static global::MonoJavaBridge.FieldId _MICROSECONDS15742; public static global::java.util.concurrent.TimeUnit MICROSECONDS { get { return default(global::java.util.concurrent.TimeUnit); } } internal static global::MonoJavaBridge.FieldId _MILLISECONDS15743; public static global::java.util.concurrent.TimeUnit MILLISECONDS { get { return default(global::java.util.concurrent.TimeUnit); } } internal static global::MonoJavaBridge.FieldId _SECONDS15744; public static global::java.util.concurrent.TimeUnit SECONDS { get { return default(global::java.util.concurrent.TimeUnit); } } internal static global::MonoJavaBridge.FieldId _MINUTES15745; public static global::java.util.concurrent.TimeUnit MINUTES { get { return default(global::java.util.concurrent.TimeUnit); } } internal static global::MonoJavaBridge.FieldId _HOURS15746; public static global::java.util.concurrent.TimeUnit HOURS { get { return default(global::java.util.concurrent.TimeUnit); } } internal static global::MonoJavaBridge.FieldId _DAYS15747; public static global::java.util.concurrent.TimeUnit DAYS { get { return default(global::java.util.concurrent.TimeUnit); } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.util.concurrent.TimeUnit.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/util/concurrent/TimeUnit")); global::java.util.concurrent.TimeUnit._values15728 = @__env.GetStaticMethodIDNoThrow(global::java.util.concurrent.TimeUnit.staticClass, "values", "()[Ljava/util/concurrent/TimeUnit;"); global::java.util.concurrent.TimeUnit._valueOf15729 = @__env.GetStaticMethodIDNoThrow(global::java.util.concurrent.TimeUnit.staticClass, "valueOf", "(Ljava/lang/String;)Ljava/util/concurrent/TimeUnit;"); global::java.util.concurrent.TimeUnit._sleep15730 = @__env.GetMethodIDNoThrow(global::java.util.concurrent.TimeUnit.staticClass, "sleep", "(J)V"); global::java.util.concurrent.TimeUnit._toNanos15731 = @__env.GetMethodIDNoThrow(global::java.util.concurrent.TimeUnit.staticClass, "toNanos", "(J)J"); global::java.util.concurrent.TimeUnit._convert15732 = @__env.GetMethodIDNoThrow(global::java.util.concurrent.TimeUnit.staticClass, "convert", "(JLjava/util/concurrent/TimeUnit;)J"); global::java.util.concurrent.TimeUnit._toMicros15733 = @__env.GetMethodIDNoThrow(global::java.util.concurrent.TimeUnit.staticClass, "toMicros", "(J)J"); global::java.util.concurrent.TimeUnit._toMillis15734 = @__env.GetMethodIDNoThrow(global::java.util.concurrent.TimeUnit.staticClass, "toMillis", "(J)J"); global::java.util.concurrent.TimeUnit._toSeconds15735 = @__env.GetMethodIDNoThrow(global::java.util.concurrent.TimeUnit.staticClass, "toSeconds", "(J)J"); global::java.util.concurrent.TimeUnit._toMinutes15736 = @__env.GetMethodIDNoThrow(global::java.util.concurrent.TimeUnit.staticClass, "toMinutes", "(J)J"); global::java.util.concurrent.TimeUnit._toHours15737 = @__env.GetMethodIDNoThrow(global::java.util.concurrent.TimeUnit.staticClass, "toHours", "(J)J"); global::java.util.concurrent.TimeUnit._toDays15738 = @__env.GetMethodIDNoThrow(global::java.util.concurrent.TimeUnit.staticClass, "toDays", "(J)J"); global::java.util.concurrent.TimeUnit._timedWait15739 = @__env.GetMethodIDNoThrow(global::java.util.concurrent.TimeUnit.staticClass, "timedWait", "(Ljava/lang/Object;J)V"); global::java.util.concurrent.TimeUnit._timedJoin15740 = @__env.GetMethodIDNoThrow(global::java.util.concurrent.TimeUnit.staticClass, "timedJoin", "(Ljava/lang/Thread;J)V"); } } [global::MonoJavaBridge.JavaProxy(typeof(global::java.util.concurrent.TimeUnit))] public sealed partial class TimeUnit_ : java.util.concurrent.TimeUnit { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static TimeUnit_() { InitJNI(); } internal TimeUnit_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.util.concurrent.TimeUnit_.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/util/concurrent/TimeUnit")); } } }
/* * XmlDocumentNavigator.cs - Implementation of the * "System.Xml.Private.XmlDocumentNavigator" class. * * Copyright (C) 2004 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Xml.Private { #if CONFIG_XPATH using System; using System.Xml; using System.Xml.XPath; using System.Collections; internal class XmlDocumentNavigator : XPathNavigator, IHasXmlNode { private XmlNode node; private XmlAttribute nsAttr = null; private XmlDocument document; /* xml:xmlns="http://www.w3.org/XML/1998/namespace" */ private XmlAttribute xmlAttr = null; private ArrayList nsNames = null; public XmlDocumentNavigator(XmlNode node) : base() { this.node = node; this.document = (node is XmlDocument) ? (XmlDocument)node : node.OwnerDocument; this.xmlAttr = document.CreateAttribute("xmlns", "xml", XmlDocument.xmlns); this.xmlAttr.Value = XmlDocument.xmlnsXml; this.nsNames = null; } public XmlDocumentNavigator(XmlDocumentNavigator copy) { this.MoveTo(copy); } public override XPathNavigator Clone() { return new XmlDocumentNavigator(this); } public override String GetAttribute(String localName, String namespaceURI) { XmlAttribute attr = node.Attributes[localName, namespaceURI] ; if(attr != null) { return attr.Value; } return null; } public override String GetNamespace(String name) { return node.GetNamespaceOfPrefix(name); } public override bool IsSamePosition(XPathNavigator other) { XmlDocumentNavigator nav = (other as XmlDocumentNavigator); return ((nav != null) && (nav.node == node) && (nav.nsAttr == nsAttr)); } public override bool MoveTo(XPathNavigator other) { XmlDocumentNavigator nav = (other as XmlDocumentNavigator); if(nav != null) { node = nav.node; nsAttr = nav.nsAttr; document = nav.document; xmlAttr = nav.xmlAttr; if(nav.nsNames == null || nav.nsNames.IsReadOnly) { nsNames = nav.nsNames; } else { nsNames = ArrayList.ReadOnly(nav.nsNames); } return true; } return false; } public override bool MoveToAttribute(String localName, String namespaceURI) { if(node.Attributes != null) { foreach(XmlAttribute attr in node.Attributes) { // TODO : can this be an Object Ref compare ? if(attr.LocalName == localName && attr.NamespaceURI == namespaceURI) { node = attr; NamespaceAttribute = null; return true; } } } return false; } public override bool MoveToFirst() { // TODO : is this correct ?. Will a Text qualify as a first node ? if(node.NodeType != XmlNodeType.Attribute && node.ParentNode != null) { node = node.ParentNode.FirstChild; return true; } return false; } public override bool MoveToFirstAttribute() { if(NodeType == XPathNodeType.Element && node.Attributes != null) { foreach(XmlAttribute attr in node.Attributes) { if(attr.NamespaceURI != XmlDocument.xmlns) { node = attr; NamespaceAttribute = null; return true; } } } return false; } public override bool MoveToFirstChild() { if(!HasChildren) { return false; } XmlNode next = node.FirstChild; // TODO: implement normalization while(next!= null && (next.NodeType == XmlNodeType.EntityReference || next.NodeType == XmlNodeType.DocumentType || next.NodeType == XmlNodeType.XmlDeclaration)) { next = next.NextSibling; } if(next != null) { node = next; return true; } return false; } public override bool MoveToFirstNamespace( XPathNamespaceScope namespaceScope) { if(NodeType != XPathNodeType.Element) { return false; } XmlElement element = (XmlElement)node; while(element != null) { if(element.Attributes != null) { foreach(XmlAttribute attr in element.Attributes) { if(attr.NamespaceURI == XmlDocument.xmlns && !CheckForDuplicateNS(attr.Name, attr.Value)) { NamespaceAttribute = attr; return true; } } } if(namespaceScope == XPathNamespaceScope.Local) { return false; } element = element.ParentNode as XmlElement; } if(namespaceScope == XPathNamespaceScope.All) { if(!CheckForDuplicateNS(xmlAttr.Name, xmlAttr.Value)) { NamespaceAttribute = xmlAttr; return true; } } return false; } public override bool MoveToId(String id) { return false; } public override bool MoveToNamespace(String name) { if(name == "xml") { /* seems to be that xml namespaces are valid wherever you are ? */ NamespaceAttribute = xmlAttr; return true; } if(NodeType != XPathNodeType.Element) { return false; } XmlElement element = (XmlElement)node; while(element != null) { if(element.Attributes != null) { foreach(XmlAttribute attr in element.Attributes) { if(attr.NamespaceURI == XmlDocument.xmlns && !CheckForDuplicateNS(attr.Name,attr.Value)) { NamespaceAttribute = attr; return true; } } } element = element.ParentNode as XmlElement; } return false; } public override bool MoveToNext() { if(nsAttr != null) { return false; } XmlNode next = node.NextSibling; // TODO: implement normalization while(next!= null && (next.NodeType == XmlNodeType.EntityReference || next.NodeType == XmlNodeType.DocumentType || next.NodeType == XmlNodeType.XmlDeclaration)) { next = next.NextSibling; } if(next != null) { node = next; return true; } return false; } public override bool MoveToNextAttribute() { if(NodeType == XPathNodeType.Attribute) { int i; XmlElement owner = ((XmlAttribute)node).OwnerElement; if(owner == null) { return false; } XmlAttributeCollection list = owner.Attributes; if(list == null) { return false; } for(i=0 ; i<list.Count ; i++) { // This should be a lot faster if(((Object)list[i]) == ((Object)node)) { i++; /* Move to Next */ break; } } if(i != list.Count) { node = list[i]; NamespaceAttribute = null; return true; } } return false; } private XmlAttribute GetNextNamespace(XmlElement owner, XmlAttribute current) { for(int i = 0; i < owner.Attributes.Count; i++) { XmlAttribute attr = owner.Attributes[i]; if(((Object)attr) == ((Object)current) || current == null) { for(int j = i+1; j < owner.Attributes.Count; j++) { attr = owner.Attributes[j]; if(attr.NamespaceURI == XmlDocument.xmlns && !CheckForDuplicateNS(attr.Name, attr.Value)) { return attr; } } } } return null; } public override bool MoveToNextNamespace(XPathNamespaceScope namespaceScope) { if(nsAttr == null) { return false; } XmlElement owner = nsAttr.OwnerElement; if(owner == null || ((Object)nsAttr) == ((Object)this.xmlAttr)) { /* technically, I don't think we need the extra condition because xmlAttr won't be attached to an element, but it's there because it makes it clear :) */ return false; } XmlAttribute nextNs = GetNextNamespace(owner, nsAttr); if(nextNs != null) { NamespaceAttribute = nextNs; return true; } if(namespaceScope == XPathNamespaceScope.Local) { return false; } for(XmlNode node = owner.ParentNode; node != null; node = node.ParentNode) { owner = (node as XmlElement); if(owner == null) { continue; } nextNs = GetNextNamespace(owner, null); if(nextNs != null) { NamespaceAttribute = nextNs; return true; } } if(namespaceScope == XPathNamespaceScope.All) { if(!CheckForDuplicateNS(xmlAttr.Name, xmlAttr.Value)) { NamespaceAttribute = xmlAttr; return true; } } return false; } public override bool MoveToParent() { if(nsAttr != null) { /* the scary part is the MoveToNextNamespace function where you just traverse up. So there is no guarantee that parent node of nsAttr is the next node you want */ NamespaceAttribute = null; return true; } if(node.NodeType == XmlNodeType.Attribute) { XmlElement owner = ((XmlAttribute)node).OwnerElement; if(owner != null) { node = owner; NamespaceAttribute = null; return true; } } else if (node.ParentNode != null) { node = node.ParentNode; NamespaceAttribute = null; return true; } return false; } public override bool MoveToPrevious() { if(nsAttr != null) { return true; } if(node.PreviousSibling != null) { node = node.PreviousSibling; return true; } return false; } public override void MoveToRoot() { // TODO: make sure we don't use this for fragments if(document != null && document.DocumentElement != null) { node = document; } NamespaceAttribute = null; return; } public override String BaseURI { get { return node.BaseURI; } } public override bool HasAttributes { get { if(nsAttr == null && node.Attributes != null) { return (node.Attributes.Count != 0); } return false; } } public override bool HasChildren { get { return (nsAttr == null && node.FirstChild != null); } } public override bool IsEmptyElement { get { if(nsAttr == null && node.NodeType == XmlNodeType.Element) { return ((XmlElement)node).IsEmpty; } return false; } } public override String LocalName { get { XPathNodeType nodeType = NodeType; if(nodeType == XPathNodeType.Element || nodeType == XPathNodeType.Attribute || nodeType == XPathNodeType.ProcessingInstruction) { return node.LocalName; } else if(nodeType == XPathNodeType.Namespace) { return nsAttr.LocalName; } return String.Empty; } } public override String Name { get { XPathNodeType nodeType = NodeType; if(nodeType == XPathNodeType.Element || nodeType == XPathNodeType.Attribute || nodeType == XPathNodeType.ProcessingInstruction) { return node.Name; } else if(nodeType == XPathNodeType.Namespace) { return LocalName; } return String.Empty; } } public override XmlNameTable NameTable { get { return document.NameTable; } } public override String NamespaceURI { get { if(nsAttr != null) { return String.Empty; } return node.NamespaceURI; } } public override XPathNodeType NodeType { get { if(nsAttr != null) { return XPathNodeType.Namespace; } switch(node.NodeType) { case XmlNodeType.Element: { return XPathNodeType.Element; } break; case XmlNodeType.Comment: { return XPathNodeType.Comment; } break; case XmlNodeType.Attribute: { return XPathNodeType.Attribute; } break; case XmlNodeType.Text: { return XPathNodeType.Text; } break; case XmlNodeType.Whitespace: { return XPathNodeType.Whitespace; } break; case XmlNodeType.SignificantWhitespace: { return XPathNodeType.SignificantWhitespace; } break; case XmlNodeType.ProcessingInstruction: { return XPathNodeType.ProcessingInstruction; } break; case XmlNodeType.Document: { return XPathNodeType.Root; } break; } // TODO resources throw new InvalidOperationException( String.Format("Invalid XPathNodeType for: {0}", node.NodeType)); } } public override String Prefix { get { return node.Prefix; } } public override String Value { get { switch(NodeType) { case XPathNodeType.Attribute: case XPathNodeType.Comment: case XPathNodeType.ProcessingInstruction: { return node.Value; } break; case XPathNodeType.Text: case XPathNodeType.Whitespace: case XPathNodeType.SignificantWhitespace: { // TODO : normalize return node.Value; } break; case XPathNodeType.Element: case XPathNodeType.Root: { return node.InnerText; } break; case XPathNodeType.Namespace: { return nsAttr.Value; } break; } return String.Empty; } } public override String XmlLang { get { return String.Empty; } } public override String ToString() { return String.Format("<XPathNavigator {0} , {1}>", node,document); } internal XmlNode CurrentNode { get { if(this.nsAttr != null) { return this.nsAttr; } return this.node; } } internal XmlAttribute NamespaceAttribute { get { return this.nsAttr; } set { this.nsAttr = value; if(value != null) { if(this.nsNames == null) { this.nsNames = new ArrayList(); } else if(this.nsNames.IsReadOnly) { this.nsNames = new ArrayList(this.nsNames); } this.nsNames.Add(value.Value); } else { this.nsNames = null; } } } // return true if the namespace has been seen before private bool CheckForDuplicateNS(String name, String ns) { // XmlNameTable to the rescue, we can compare names as objects if(this.nsNames != null && this.nsNames.Contains((Object)name)) { // duplicate return true; } /* tricky part: setting xmlns='' in your XML causes the default namespace to be *seen* but forgotten. */ if(ns == String.Empty) { if(this.nsNames == null) { this.nsNames = new ArrayList(); } else if(this.nsNames.IsReadOnly) { this.nsNames = new ArrayList(this.nsNames); } this.nsNames.Add(NameTable.Get("xmlns")); return true; } return false; } XmlNode IHasXmlNode.GetNode() { return CurrentNode; } } #endif // CONFIG_XPATH }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using NSubstitute; using NSubstitute.ExceptionExtensions; using NUnit.Framework; using System; using System.Collections.Generic; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Rest.Conversations.V1; namespace Twilio.Tests.Rest.Conversations.V1 { [TestFixture] public class RoleTest : TwilioTest { [Test] public void TestCreateRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Post, Twilio.Rest.Domain.Conversations, "/v1/Roles", "" ); request.AddPostParam("FriendlyName", Serialize("friendly_name")); request.AddPostParam("Type", Serialize(RoleResource.RoleTypeEnum.Conversation)); request.AddPostParam("Permission", Serialize("permission")); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { RoleResource.Create("friendly_name", RoleResource.RoleTypeEnum.Conversation, Promoter.ListOfOne("permission"), client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestCreateResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.Created, "{\"sid\": \"RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"chat_service_sid\": \"ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"friendly_name\": \"Conversation Role\",\"type\": \"conversation\",\"permissions\": [\"sendMessage\",\"leaveConversation\",\"editOwnMessage\",\"deleteOwnMessage\"],\"date_created\": \"2016-03-03T19:47:15Z\",\"date_updated\": \"2016-03-03T19:47:15Z\",\"url\": \"https://conversations.twilio.com/v1/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}" )); var response = RoleResource.Create("friendly_name", RoleResource.RoleTypeEnum.Conversation, Promoter.ListOfOne("permission"), client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestUpdateRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Post, Twilio.Rest.Domain.Conversations, "/v1/Roles/RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "" ); request.AddPostParam("Permission", Serialize("permission")); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { RoleResource.Update("RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", Promoter.ListOfOne("permission"), client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestUpdateResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"sid\": \"RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"chat_service_sid\": \"ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"friendly_name\": \"Conversation Role\",\"type\": \"conversation\",\"permissions\": [\"sendMessage\",\"leaveConversation\",\"editOwnMessage\",\"deleteOwnMessage\"],\"date_created\": \"2016-03-03T19:47:15Z\",\"date_updated\": \"2016-03-03T19:47:15Z\",\"url\": \"https://conversations.twilio.com/v1/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}" )); var response = RoleResource.Update("RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", Promoter.ListOfOne("permission"), client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestDeleteRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Delete, Twilio.Rest.Domain.Conversations, "/v1/Roles/RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { RoleResource.Delete("RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestDeleteResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.NoContent, "null" )); var response = RoleResource.Delete("RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestFetchRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Get, Twilio.Rest.Domain.Conversations, "/v1/Roles/RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { RoleResource.Fetch("RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestFetchResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"sid\": \"RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"chat_service_sid\": \"ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"friendly_name\": \"Conversation Role\",\"type\": \"conversation\",\"permissions\": [\"sendMessage\",\"leaveConversation\",\"editOwnMessage\",\"deleteOwnMessage\"],\"date_created\": \"2016-03-03T19:47:15Z\",\"date_updated\": \"2016-03-03T19:47:15Z\",\"url\": \"https://conversations.twilio.com/v1/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}" )); var response = RoleResource.Fetch("RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestReadRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Get, Twilio.Rest.Domain.Conversations, "/v1/Roles", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { RoleResource.Read(client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestReadFullResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"meta\": {\"page\": 0,\"page_size\": 50,\"first_page_url\": \"https://conversations.twilio.com/v1/Roles?PageSize=50&Page=0\",\"previous_page_url\": null,\"url\": \"https://conversations.twilio.com/v1/Roles?PageSize=50&Page=0\",\"next_page_url\": null,\"key\": \"roles\"},\"roles\": [{\"sid\": \"RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"chat_service_sid\": \"ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"friendly_name\": \"Conversation Role\",\"type\": \"conversation\",\"permissions\": [\"sendMessage\",\"leaveConversation\",\"editOwnMessage\",\"deleteOwnMessage\"],\"date_created\": \"2016-03-03T19:47:15Z\",\"date_updated\": \"2016-03-03T19:47:15Z\",\"url\": \"https://conversations.twilio.com/v1/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}]}" )); var response = RoleResource.Read(client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestReadEmptyResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"meta\": {\"page\": 0,\"page_size\": 50,\"first_page_url\": \"https://conversations.twilio.com/v1/Roles?PageSize=50&Page=0\",\"previous_page_url\": null,\"url\": \"https://conversations.twilio.com/v1/Roles?PageSize=50&Page=0\",\"next_page_url\": null,\"key\": \"roles\"},\"roles\": []}" )); var response = RoleResource.Read(client: twilioRestClient); Assert.NotNull(response); } } }
//A GUI frontend for commandline POX ,all components not supported yet // https://github.com/abh15 using System; using System.Windows.Forms; using System.Globalization; using System.Diagnostics; using System.Text; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Threading; public class guifrontend: Form { public TextBox t,t2,t3,t4,t5; public RadioButton r1,r2,r3,r4,r5,r6,r7,r8,r9; public ComboBox cb; Process p=new Process();//instantiate new process p string sel=""; //file to run int s_case=0; //select case void reset() { //func to clear all fields & visibility t2.Visible=false; t3.Visible=false; t4.Visible=false; t5.Visible=false; s_case=0; t2.Text=""; t3.Text=""; t4.Text=""; t5.Text=""; } public guifrontend() { Text="POXGUI"; Size=new Size(700,630); Label L1=new Label(); L1.Parent=this; L1.Text="Path to directory containing pox.py:"; L1.Size=new Size(50,10); L1.Location=new Point(10,14); L1.AutoSize=true; Label L2=new Label(); L2.Parent=this; L2.Text="Select log level:"; L2.Size=new Size(50,10); L2.Location=new Point(10,53); L2.AutoSize=true; t=new TextBox(); t.Parent=this; t.Location=new Point(210,10); t.Size=new Size(250,80); t.Text=""; // t.SelectAll(); Button b=new Button(); b.Text="Run script"; b.Location=new Point(210,560); b.Parent=this; b.Click+=new EventHandler(Onsubmit); Button b2=new Button(); b2.Text="Terminate"; b2.Location=new Point(310,560); b2.Parent=this; b2.Click+=new EventHandler(Onterm); Button b4=new Button(); b4.Text="Exit"; b4.Location=new Point(410,560); b4.Parent=this; b4.Click+=new EventHandler(Onexit); Button b3=new Button(); b3.Text="Browse"; b3.Location=new Point(470,10); b3.Parent=this; b3.Click+=new EventHandler(Onbrowse); b3.Visible=true; RadioButton r1=new RadioButton(); r1.Text="Hub"; r1.Location=new Point(10,100); r1.Parent=this; r1.CheckedChanged+=new EventHandler(Onr1); RadioButton r2=new RadioButton(); r2.Text="L2 learning"; r2.Location=new Point(10,150); r2.Parent=this; r2.CheckedChanged+=new EventHandler(Onr2); RadioButton r3=new RadioButton(); r3.Text="L3 learning"; r3.Location=new Point(10,300); r3.Parent=this; r3.CheckedChanged+=new EventHandler(Onr3); RadioButton r7=new RadioButton(); r7.Text="L2 pairs"; r7.Location=new Point(10,250); r7.Parent=this; r7.CheckedChanged+=new EventHandler(Onr7); RadioButton r8=new RadioButton(); r8.Text="L2 multi"; r8.Location=new Point(10,200); r8.Parent=this; r8.CheckedChanged+=new EventHandler(Onr8); RadioButton r5=new RadioButton(); r5.Text="DHCP"; r5.Location=new Point(10,350); r5.Parent=this; r5.CheckedChanged+=new EventHandler(Onr5); RadioButton r6=new RadioButton(); r6.Text="IP loadbalancer"; r6.Location=new Point(10,400); r6.Parent=this; r6.CheckedChanged+=new EventHandler(Onr6); RadioButton r9=new RadioButton(); r9.Text="NAT"; r9.Location=new Point(10,450); r9.Parent=this; r9.CheckedChanged+=new EventHandler(Onr9); RadioButton r4=new RadioButton(); r4.Text="Custom script"; r4.Location=new Point(10,500); r4.Parent=this; r4.CheckedChanged+=new EventHandler(Onr4); t2=new TextBox(); t2.Parent=this; t2.Location=new Point(300,100); t2.Size=new Size(300,80); t2.Text=""; t2.Visible=false; t2.MouseDown+=new MouseEventHandler(clear2); t3=new TextBox(); t3.Parent=this; t3.Location=new Point(300,180); t3.Size=new Size(300,80); t3.Text=""; t3.Visible=false; t3.MouseDown+=new MouseEventHandler(clear3); t4=new TextBox(); t4.Parent=this; t4.Location=new Point(300,260); t4.Size=new Size(300,80); t4.Text=""; t4.Visible=false; t4.MouseDown+=new MouseEventHandler(clear4); t5=new TextBox(); t5.Parent=this; t5.Location=new Point(300,340); t5.Size=new Size(300,80); t5.Text=""; t5.Visible=false; t5.MouseDown+=new MouseEventHandler(clear5); cb=new ComboBox(); cb.Parent=this; cb.Text="DEBUG"; cb.Location=new Point (150,50); cb.Items.AddRange(new object[]{"DEBUG ","INFO ","WARNING ","CRITICAL ","ERROR "}); Controls.Add(r1); Controls.Add(r2); Controls.Add(r3); Controls.Add(r4); Controls.Add(r5); Controls.Add(r6); Controls.Add(r7); Controls.Add(r8); Controls.Add(r9); Controls.Add(cb); if(Convert.ToString(Environment.OSVersion.Platform)!="Unix") //browse button only if non-windows OS { b3.Visible=false; } } //=======GUI ends======= void Onsubmit(object sender,EventArgs e) { sel=sel+this.t2.Text; //for scripts with no param switch (s_case) //case for scripts with params { case 1: sel=" proto.dhcpd --network="+t2.Text+" --ip="+t3.Text+" --first="+t4.Text+" --last="+t5.Text+" --router=None --dns=None"; break; case 2: sel=" misc.ip_loadbalancer --ip="+t4.Text+" --servers="+t5.Text; break; case 3: sel=t2.Text+" "+t3.Text; break; case 4: sel=" misc.nat --dpid="+t2.Text+" --outside-port="+t3.Text; break; default: Console.WriteLine(""); break; } if(Convert.ToString(Environment.OSVersion.Platform)!="Unix")//to check os { this.t.Text=this.t.Text+"\\"; //in windows path is given as dir\file & default in UNIX is dir/file } string par=this.t.Text+"pox.py log.level --"+this.cb.Text+sel+" openflow.keepalive";//store parameters common to all scripts along with log.level selection to a string string name= "python"; //pass filename to process p p.StartInfo.FileName=name; p.StartInfo.Arguments=par; //pass the args to process p Console.WriteLine(name+par); p.Start(); //start process p reset(); } //OnClicklisteners to clear textfields as soon as they're clicked void clear2(object sender,EventArgs e){t2.Text="";} void clear3(object sender,EventArgs e){t3.Text="";} void clear4(object sender,EventArgs e){t4.Text="";} void clear5(object sender,EventArgs e){t5.Text="";} void Onr1(object sender,EventArgs e) { //hub reset(); sel=" forwarding.hub"; } void Onr2(object sender,EventArgs e) { //l2_learn reset(); sel=" forwarding.l2_learning"; } void Onr3(object sender,EventArgs e) { reset(); //l3_learn sel=" forwarding.l3_learning --fakeways="; this.t2.Text="Enter fakeways for hosts (fakeway1,fakeway2,..)"; //set textfield to get params for l3 learning this.t2.Visible=true; } void Onr4(object sender,EventArgs e) { //custom scripts reset(); this.t2.Text="Name of custom script without extension (in /ext folder)" ; this.t2.Visible=true; sel=""; this.t3.Text="Parameters (optional)" ; this.t3.Visible=true; s_case=3; } void Onr5(object sender,EventArgs e) { //dhcp reset(); s_case=1; this.t2.Text="Subnet to allocate addresses from (e.g 192.168.0.0/24)" ; this.t2.Visible=true; this.t3.Text="IP to use for DHCP server"; this.t3.Visible=true; this.t4.Text="Start of range (e.g 10)"; this.t4.Visible=true; this.t5.Text="End of range (e.g 250)" ; this.t5.Visible=true; } void Onr6(object sender,EventArgs e) { //iploadbalancer reset(); s_case=2; this.t4.Text="IP from which traffic is to be redirected"; this.t4.Visible=true; this.t5.Text="IP of servers where the traffic will be redir (IP1,IP2)" ; this.t5.Visible=true; } void Onr7(object sender,EventArgs e) { //l2 pairs reset(); sel=" forwarding.l2_pairs"; } void Onr8(object sender,EventArgs e) { //l2 multi reset(); sel=" openflow.discovery forwarding.l2_multi"; } void Onr9(object sender,EventArgs e) { reset(); //NAT s_case=4; this.t2.Text="DPID to NAT-ize" ; this.t2.Visible=true; this.t3.Text="port on which DPID connects upstream(e.g, eth0)" ; this.t3.Visible=true; } void Onbrowse (object sender,EventArgs e) { //get path to pox folder only for UNIX systems var openFileDialog1=new FolderBrowserDialog(); DialogResult result=openFileDialog1.ShowDialog(); if(result==DialogResult.OK) { this.t.Text=openFileDialog1.SelectedPath+"/"; } } void Onterm(object sender,EventArgs e) { this.p.Kill(); //terminate current script reset(); //reset all fields sel="" ; Console.WriteLine("Terminated"); } void Onexit(object sender,EventArgs e) { Close(); //exit app } static public void Main() { Application.Run(new guifrontend()); //run app } }
/* * @author Valentin Simonov / http://va.lent.in/ */ using System; using TouchScript.Editor.EditorUI; using TouchScript.Gestures; using UnityEditor; using UnityEditorInternal; using UnityEngine; using System.Reflection; namespace TouchScript.Editor.Gestures { [CustomEditor(typeof(Gesture), true)] internal class GestureEditor : UnityEditor.Editor { private const string FRIENDLY_GESTURES_PROP = "friendlyGestures"; public static readonly GUIContent TEXT_GENERAL_HEADER = new GUIContent("General settings", "General settings."); public static readonly GUIContent TEXT_LIMITS_HEADER = new GUIContent("Limits", "Properties that limit the gesture."); public static readonly GUIContent TEXT_GESTURES_HEADER = new GUIContent("Interaction with other Gestures", "Settings which allow this gesture to interact with other gestures."); public static readonly GUIContent TEXT_ADVANCED_HEADER = new GUIContent("Advanced", "Advanced properties."); public static readonly GUIContent TEXT_USE_SEND_MESSAGE_HEADER = new GUIContent("Use SendMessage", "Enables sending events through SendMessage. Warnning: this method is slow!"); public static readonly GUIContent TEXT_USE_UNITY_EVENTS_HEADER = new GUIContent("Use Unity Events", "Enables sending events through Unity Events."); public static readonly GUIContent TEXT_FRIENDLY = new GUIContent("Friendly Gestures", "List of gestures which can work together with this gesture."); public static readonly GUIContent TEXT_DEBUG_MODE = new GUIContent("Debug", "Turns on gesture debug mode."); public static readonly GUIContent TEXT_SEND_STATE_CHANGE_MESSAGES = new GUIContent("Send State Change Messages", "If checked, the gesture will send a message for every state change. Gestures usually have their own more specific messages, so you should keep this toggle unchecked unless you really want state change messages."); public static readonly GUIContent TEXT_SEND_MESSAGE_TARGET = new GUIContent("Target", "The GameObject target of Unity Messages. If null, host GameObject is used."); public static readonly GUIContent TEXT_SEND_STATE_CHANGE_EVENTS = new GUIContent("Send State Change Events", "If checked, the gesture will send a events for every state change. Gestures usually have their own more specific messages, so you should keep this toggle unchecked unless you really want state change events."); public static readonly GUIContent TEXT_REQUIRE_GESTURE_TO_FAIL = new GUIContent("Require Other Gesture to Fail", "Another gesture must fail for this gesture to start."); public static readonly GUIContent TEXT_LIMIT_POINTERS = new GUIContent(" Limit Pointers", ""); protected bool shouldDrawAdvanced = false; protected bool shouldDrawGeneral = true; private Gesture instance; private SerializedProperty basicEditor; private SerializedProperty debugMode, friendlyGestures, requireGestureToFail, minPointers, maxPointers, useSendMessage, sendMessageTarget, sendStateChangeMessages, useUnityEvents, sendStateChangeEvents; private SerializedProperty OnStateChange; private SerializedProperty advancedProps, limitsProps, generalProps; private PropertyInfo useUnityEvents_prop, useSendMessage_prop; private ReorderableList friendlyGesturesList; private int indexToRemove = -1; private float minPointersFloat, maxPointersFloat; protected virtual void OnEnable() { instance = target as Gesture; advancedProps = serializedObject.FindProperty("advancedProps"); limitsProps = serializedObject.FindProperty("limitsProps"); generalProps = serializedObject.FindProperty("generalProps"); basicEditor = serializedObject.FindProperty("basicEditor"); debugMode = serializedObject.FindProperty("debugMode"); friendlyGestures = serializedObject.FindProperty("friendlyGestures"); requireGestureToFail = serializedObject.FindProperty("requireGestureToFail"); useSendMessage = serializedObject.FindProperty("useSendMessage"); sendMessageTarget = serializedObject.FindProperty("sendMessageTarget"); sendStateChangeMessages = serializedObject.FindProperty("sendStateChangeMessages"); useUnityEvents = serializedObject.FindProperty("useUnityEvents"); sendStateChangeEvents = serializedObject.FindProperty("sendStateChangeEvents"); minPointers = serializedObject.FindProperty("minPointers"); maxPointers = serializedObject.FindProperty("maxPointers"); OnStateChange = serializedObject.FindProperty("OnStateChange"); var type = instance.GetType(); useUnityEvents_prop = type.GetProperty("UseUnityEvents", BindingFlags.Instance | BindingFlags.Public); useSendMessage_prop = type.GetProperty("UseSendMessage", BindingFlags.Instance | BindingFlags.Public); minPointersFloat = minPointers.intValue; maxPointersFloat = maxPointers.intValue; friendlyGesturesList = new ReorderableList(serializedObject, friendlyGestures, false, true, false, true); friendlyGesturesList.drawHeaderCallback += (rect) => GUI.Label(rect, TEXT_FRIENDLY); friendlyGesturesList.drawElementCallback += (rect, index, active, focused) => { rect.height = 16; var gesture = friendlyGestures.GetArrayElementAtIndex(index).objectReferenceValue as Gesture; if (gesture == null) { // Killing null elements. indexToRemove = index; EditorGUI.LabelField(rect, GUIContent.none); return; } EditorGUI.LabelField(rect, string.Format("{0} @ {1}", gesture.GetType().Name, gesture.name), GUIElements.BoxLabel); }; friendlyGesturesList.onRemoveCallback += list => { indexToRemove = list.index; }; } public override void OnInspectorGUI() { #if UNITY_5_6_OR_NEWER serializedObject.UpdateIfRequiredOrScript(); #else serializedObject.UpdateIfDirtyOrScript(); #endif GUILayout.Space(5); bool display; if (basicEditor.boolValue) { drawBasic(); if (GUIElements.BasicHelpBox(getHelpText())) { basicEditor.boolValue = false; Repaint(); } } else { if (shouldDrawGeneral) { display = GUIElements.Header(TEXT_GENERAL_HEADER, generalProps); if (display) { EditorGUI.indentLevel++; drawGeneral(); EditorGUI.indentLevel--; } } drawOtherGUI(); display = GUIElements.Header(TEXT_LIMITS_HEADER, limitsProps); if (display) { EditorGUI.indentLevel++; drawLimits(); EditorGUI.indentLevel--; } display = GUIElements.Header(TEXT_GESTURES_HEADER, friendlyGestures); if (display) { EditorGUI.indentLevel++; drawFriendlyGestures(); drawRequireToFail(); GUILayout.Space(5); EditorGUI.indentLevel--; } display = GUIElements.Header(TEXT_USE_UNITY_EVENTS_HEADER, useUnityEvents, useUnityEvents, useUnityEvents_prop); if (display) { EditorGUI.indentLevel++; using (new EditorGUI.DisabledGroupScope(!useUnityEvents.boolValue)) { drawUnityEvents(); } EditorGUI.indentLevel--; } display = GUIElements.Header(TEXT_USE_SEND_MESSAGE_HEADER, useSendMessage, useSendMessage, useSendMessage_prop); if (display) { EditorGUI.indentLevel++; using (new EditorGUI.DisabledGroupScope(!useSendMessage.boolValue)) { drawSendMessage(); } EditorGUI.indentLevel--; } if (shouldDrawAdvanced) { display = GUIElements.Header(TEXT_ADVANCED_HEADER, advancedProps); if (display) { EditorGUI.indentLevel++; drawAdvanced(); EditorGUI.indentLevel--; } } drawDebug(); } serializedObject.ApplyModifiedProperties(); } protected virtual void drawBasic() { } protected virtual GUIContent getHelpText() { return new GUIContent(""); } protected virtual void drawOtherGUI() { } protected virtual void drawGeneral() { } protected virtual void drawLimits() { var limitPointers = (minPointers.intValue > 0) || (maxPointers.intValue > 0); var newLimitPointers = EditorGUILayout.ToggleLeft(TEXT_LIMIT_POINTERS, limitPointers); if (newLimitPointers) { if (!limitPointers) { minPointersFloat = 0; maxPointersFloat = 10; } else { minPointersFloat = (float) minPointers.intValue; maxPointersFloat = (float) maxPointers.intValue; } //or this values doesn't change from script properly EditorGUI.indentLevel++; EditorGUILayout.LabelField("Min: " + (int)minPointersFloat + ", Max: " + (int)maxPointersFloat); EditorGUILayout.MinMaxSlider(ref minPointersFloat, ref maxPointersFloat, 0, 10, GUILayout.MaxWidth(150)); EditorGUI.indentLevel--; } else { if (limitPointers) { minPointersFloat = 0; maxPointersFloat = 0; } } minPointers.intValue = (int)minPointersFloat; maxPointers.intValue = (int)maxPointersFloat; } protected virtual void drawFriendlyGestures() { GUILayout.Space(5); drawGestureList(friendlyGestures, addFriendlyGesture); GUILayout.Space(5); } protected virtual void drawUnityEvents() { EditorGUILayout.PropertyField(OnStateChange); EditorGUILayout.PropertyField(sendStateChangeEvents, TEXT_SEND_STATE_CHANGE_EVENTS); } protected virtual void drawSendMessage() { EditorGUILayout.PropertyField(sendMessageTarget, TEXT_SEND_MESSAGE_TARGET); EditorGUILayout.PropertyField(sendStateChangeMessages, TEXT_SEND_STATE_CHANGE_MESSAGES); } protected virtual void drawAdvanced() { } protected virtual void drawDebug() { if (debugMode == null) return; EditorGUILayout.PropertyField(debugMode, TEXT_DEBUG_MODE); } protected virtual void drawRequireToFail() { EditorGUILayout.PropertyField(requireGestureToFail, TEXT_REQUIRE_GESTURE_TO_FAIL); } #region Gesture List private void drawGestureList(SerializedProperty prop, Action<SerializedProperty, Gesture> addGesture) { indexToRemove = -1; // Rect listRect = EditorGUI.IndentedRect(GUILayoutUtility.GetRect(0.0f, (prop.arraySize == 0 ? 0 : prop.arraySize - 1) * 16 + 60, GUILayout.ExpandWidth(true))); // friendlyGesturesList.DoList(listRect); friendlyGesturesList.DoLayoutList(); GUILayout.Space(9); Rect dropArea = GUILayoutUtility.GetRect(0.0f, 50.0f, GUIElements.Box, GUILayout.ExpandWidth(true)); GUI.Box(dropArea, "Drag a Gesture Here", GUIElements.Box); switch (Event.current.type) { case EventType.DragUpdated: if (dropArea.Contains(Event.current.mousePosition)) DragAndDrop.visualMode = DragAndDropVisualMode.Copy; break; case EventType.DragPerform: if (dropArea.Contains(Event.current.mousePosition)) { DragAndDrop.visualMode = DragAndDropVisualMode.Copy; DragAndDrop.AcceptDrag(); foreach (UnityEngine.Object obj in DragAndDrop.objectReferences) { if (obj is GameObject) { var go = obj as GameObject; Gesture[] gestures = go.GetComponents<Gesture>(); foreach (Gesture gesture in gestures) { addGesture(prop, gesture); } } else if (obj is Gesture) { addGesture(prop, obj as Gesture); } } Event.current.Use(); } break; } if (indexToRemove > -1) { removeFriendlyGestureAt(prop, indexToRemove); } } private void addFriendlyGesture(SerializedProperty prop, Gesture value) { if (value == null || value == target) return; // Adding that gesture to this gesture. var shouldAdd = true; for (int i = 0; i < prop.arraySize; i++) { if (prop.GetArrayElementAtIndex(i).objectReferenceValue == value) { shouldAdd = false; break; } } if (shouldAdd) { prop.arraySize++; prop.GetArrayElementAtIndex(prop.arraySize - 1).objectReferenceValue = value; } // Adding this gesture to that gesture. shouldAdd = true; var so = new SerializedObject(value); so.Update(); SerializedProperty p = so.FindProperty(FRIENDLY_GESTURES_PROP); for (int i = 0; i < p.arraySize; i++) { if (p.GetArrayElementAtIndex(i).objectReferenceValue == target) { shouldAdd = false; break; } } if (shouldAdd) { p.arraySize++; p.GetArrayElementAtIndex(p.arraySize - 1).objectReferenceValue = target; so.ApplyModifiedProperties(); EditorUtility.SetDirty(value); } } private Gesture removeFriendlyGestureAt(SerializedProperty prop, int index) { // Removing that gesture from this gesture. var gesture = prop.GetArrayElementAtIndex(index).objectReferenceValue as Gesture; removeFromArray(prop, index); if (gesture == null) return null; // Removing this gesture from that gesture. var so = new SerializedObject(gesture); so.Update(); SerializedProperty p = so.FindProperty(FRIENDLY_GESTURES_PROP); for (int j = 0; j < p.arraySize; j++) { if (p.GetArrayElementAtIndex(j).objectReferenceValue == target) { removeFromArray(p, j); break; } } so.ApplyModifiedProperties(); EditorUtility.SetDirty(gesture); return gesture; } // A hack to remove a gesture from a list. // Was needed because array.DeleteArrayElementAtIndex() wasn't actually deleting an item. private void removeFromArray(SerializedProperty array, int index) { if (index != array.arraySize - 1) { array.GetArrayElementAtIndex(index).objectReferenceValue = array.GetArrayElementAtIndex(array.arraySize - 1).objectReferenceValue; } array.arraySize--; } #endregion } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Xml; using Microsoft.PythonTools.Analysis; using Microsoft.PythonTools.Intellisense; using Microsoft.PythonTools.Interpreter; using Microsoft.PythonTools.Project; using Microsoft.VisualStudio.TestTools.UnitTesting; using TestUtilities; using TestUtilities.Python; namespace PythonToolsTests { [TestClass] public class PythonProjectTests { [ClassInitialize] public static void DoDeployment(TestContext context) { AssertListener.Initialize(); PythonTestData.Deploy(); } public TestContext TestContext { get; set; } [TestMethod, Priority(1)] public void MergeRequirements() { // Comments should be preserved, only package specs should change. AssertUtil.AreEqual( PythonProjectNode.MergeRequirements(new[] { "a # with a comment", "B==0.2", "# just a comment B==01234", "", "x < 1", "d==1.0 e==2.0 f==3.0" }, new[] { "b==0.1", "a==0.2", "c==0.3", "e==4.0", "x==0.8" }, false), "a==0.2 # with a comment", "b==0.1", "# just a comment B==01234", "", "x==0.8", "d==1.0 e==4.0 f==3.0" ); // addNew is true, so the c==0.3 should be added. AssertUtil.AreEqual( PythonProjectNode.MergeRequirements(new[] { "a # with a comment", "b==0.2", "# just a comment B==01234" }, new[] { "B==0.1", // case is updated "a==0.2", "c==0.3" }, true), "a==0.2 # with a comment", "B==0.1", "# just a comment B==01234", "c==0.3" ); // No existing entries, so the new ones are sorted and returned. AssertUtil.AreEqual( PythonProjectNode.MergeRequirements(null, new[] { "b==0.2", "a==0.1", "c==0.3" }, false), "a==0.1", "b==0.2", "c==0.3" ); // Check all the inequalities const string inequalities = "<=|>=|<|>|!=|=="; AssertUtil.AreEqual( PythonProjectNode.MergeRequirements( inequalities.Split('|').Select(s => "a " + s + " 1.2.3"), new[] { "a==0" }, false ), inequalities.Split('|').Select(_ => "a==0").ToArray() ); } [TestMethod, Priority(1)] public void MergeRequirementsMismatchedCase() { AssertUtil.AreEqual( PythonProjectNode.MergeRequirements(new[] { "aaaaaa==0.0", "BbBbBb==0.1", "CCCCCC==0.2" }, new[] { "aaaAAA==0.1", "bbbBBB==0.2", "cccCCC==0.3" }, false), "aaaAAA==0.1", "bbbBBB==0.2", "cccCCC==0.3" ); // https://pytools.codeplex.com/workitem/2465 AssertUtil.AreEqual( PythonProjectNode.MergeRequirements(new[] { "Flask==0.10.1", "itsdangerous==0.24", "Jinja2==2.7.3", "MarkupSafe==0.23", "Werkzeug==0.9.6" }, new[] { "flask==0.10.1", "itsdangerous==0.24", "jinja2==2.7.3", "markupsafe==0.23", "werkzeug==0.9.6" }, false), "flask==0.10.1", "itsdangerous==0.24", "jinja2==2.7.3", "markupsafe==0.23", "werkzeug==0.9.6" ); } [TestMethod, Priority(1)] public void FindRequirementsRegexTest() { var r = PythonProjectNode.FindRequirementRegex; AssertUtil.AreEqual(r.Matches("aaaa bbbb cccc").Cast<Match>().Select(m => m.Value), "aaaa", "bbbb", "cccc" ); AssertUtil.AreEqual(r.Matches("aaaa#a\r\nbbbb#b\r\ncccc#c\r\n").Cast<Match>().Select(m => m.Value), "aaaa", "bbbb", "cccc" ); AssertUtil.AreEqual(r.Matches("a==1 b!=2 c<=3").Cast<Match>().Select(m => m.Value), "a==1", "b!=2", "c<=3" ); AssertUtil.AreEqual(r.Matches("a==1 b!=2 c<=3").Cast<Match>().Select(m => m.Groups["name"].Value), "a", "b", "c" ); AssertUtil.AreEqual(r.Matches("a==1#a\r\nb!=2#b\r\nc<=3#c\r\n").Cast<Match>().Select(m => m.Value), "a==1", "b!=2", "c<=3" ); AssertUtil.AreEqual(r.Matches("a == 1 b != 2 c <= 3").Cast<Match>().Select(m => m.Value), "a == 1", "b != 2", "c <= 3" ); AssertUtil.AreEqual(r.Matches("a == 1 b != 2 c <= 3").Cast<Match>().Select(m => m.Groups["name"].Value), "a", "b", "c" ); AssertUtil.AreEqual(r.Matches("a -u b -f:x c").Cast<Match>().Select(m => m.Groups["name"].Value), "a", "b", "c" ); } [TestMethod, Priority(1)] public void UpdateWorkerRoleServiceDefinitionTest() { var doc = new XmlDocument(); doc.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8""?> <ServiceDefinition name=""Azure1"" xmlns=""http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition"" schemaVersion=""2014-01.2.3""> <WorkerRole name=""PythonApplication1"" vmsize=""Small"" /> <WebRole name=""PythonApplication2"" /> </ServiceDefinition>"); PythonProjectNode.UpdateServiceDefinition(doc, "Worker", "PythonApplication1"); AssertUtil.AreEqual(@"<?xml version=""1.0"" encoding=""utf-8""?> <ServiceDefinition name=""Azure1"" xmlns=""http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition"" schemaVersion=""2014-01.2.3""> <WorkerRole name=""PythonApplication1"" vmsize=""Small""> <Startup> <Task commandLine=""bin\ps.cmd ConfigureCloudService.ps1"" executionContext=""elevated"" taskType=""simple""> <Environment> <Variable name=""EMULATED""> <RoleInstanceValue xpath=""/RoleEnvironment/Deployment/@emulated"" /> </Variable> </Environment> </Task> </Startup> <Runtime> <Environment> <Variable name=""EMULATED""> <RoleInstanceValue xpath=""/RoleEnvironment/Deployment/@emulated"" /> </Variable> </Environment> <EntryPoint> <ProgramEntryPoint commandLine=""bin\ps.cmd LaunchWorker.ps1"" setReadyOnProcessStart=""true"" /> </EntryPoint> </Runtime> </WorkerRole> <WebRole name=""PythonApplication2"" /> </ServiceDefinition>", doc); } [TestMethod, Priority(1)] public void UpdateWebRoleServiceDefinitionTest() { var doc = new XmlDocument(); doc.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8""?> <ServiceDefinition name=""Azure1"" xmlns=""http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition"" schemaVersion=""2014-01.2.3""> <WorkerRole name=""PythonApplication1"" vmsize=""Small"" /> <WebRole name=""PythonApplication2"" /> </ServiceDefinition>"); PythonProjectNode.UpdateServiceDefinition(doc, "Web", "PythonApplication2"); AssertUtil.AreEqual(@"<?xml version=""1.0"" encoding=""utf-8""?> <ServiceDefinition name=""Azure1"" xmlns=""http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition"" schemaVersion=""2014-01.2.3""> <WorkerRole name=""PythonApplication1"" vmsize=""Small"" /> <WebRole name=""PythonApplication2""> <Startup> <Task commandLine=""ps.cmd ConfigureCloudService.ps1"" executionContext=""elevated"" taskType=""simple""> <Environment> <Variable name=""EMULATED""> <RoleInstanceValue xpath=""/RoleEnvironment/Deployment/@emulated"" /> </Variable> </Environment> </Task> </Startup> </WebRole> </ServiceDefinition>", doc); } [TestMethod, Priority(1)] public void LoadAndUnloadModule() { var factories = new[] { InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(new Version(3, 3)) }; using (var analyzer = new VsProjectAnalyzer(PythonToolsTestUtilities.CreateMockServiceProvider(), factories[0])) { var m1Path = TestData.GetPath("TestData\\SimpleImport\\module1.py"); var m2Path = TestData.GetPath("TestData\\SimpleImport\\module2.py"); var entry1 = analyzer.AnalyzeFileAsync(m1Path).Result; var entry2 = analyzer.AnalyzeFileAsync(m2Path).Result; analyzer.WaitForCompleteAnalysis(_ => true); var loc = new Microsoft.PythonTools.Parsing.SourceLocation(0, 1, 1); AssertUtil.ContainsExactly( analyzer.GetEntriesThatImportModuleAsync("module1", true).Result.Select(m => m.moduleName), "module2" ); AssertUtil.ContainsExactly( analyzer.GetValueDescriptions(entry2, "x", loc), "int" ); analyzer.UnloadFileAsync(entry1).Wait(); analyzer.WaitForCompleteAnalysis(_ => true); // Even though module1 has been unloaded, we still know that // module2 imports it. AssertUtil.ContainsExactly( analyzer.GetEntriesThatImportModuleAsync("module1", true).Result.Select(m => m.moduleName), "module2" ); AssertUtil.ContainsExactly( analyzer.GetValueDescriptions(entry2, "x", loc) ); analyzer.AnalyzeFileAsync(m1Path).Wait(); analyzer.WaitForCompleteAnalysis(_ => true); AssertUtil.ContainsExactly( analyzer.GetEntriesThatImportModuleAsync("module1", true).Result.Select(m => m.moduleName), "module2" ); AssertUtil.ContainsExactly( analyzer.GetValueDescriptions(entry2, "x", loc), "int" ); } } [TestMethod, Priority(1)] public void AnalyzeBadEgg() { var factories = new[] { InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(new Version(3, 4)) }; using (var analyzer = new VsProjectAnalyzer(PythonToolsTestUtilities.CreateMockServiceProvider(), factories[0])) { analyzer.AnalyzeZipArchiveAsync(TestData.GetPath(@"TestData\BadEgg.egg")).Wait(); analyzer.WaitForCompleteAnalysis(_ => true); // Analysis result must contain the module for the filename inside the egg that is a valid identifier, // and no entries for the other filename which is not. var moduleNames = analyzer.GetModulesResult(true).Result.Select(x => x.Name); AssertUtil.Contains(moduleNames, "module"); AssertUtil.DoesntContain(moduleNames, "42"); } } } }
// 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.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB { public class PDBIteratorTests : CSharpPDBTestBase { [WorkItem(543376, "DevDiv")] [Fact] public void SimpleIterator1() { var text = @" class Program { System.Collections.Generic.IEnumerable<int> Foo() { yield break; } public void F() { } // needs to be present to work around SymWriter bug #1068894 } "; var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <methods> <method containingType=""Program"" name=""Foo""> <customDebugInfo> <forwardIterator name=""&lt;Foo&gt;d__0"" /> </customDebugInfo> </method> <method containingType=""Program"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""21"" endLine=""9"" endColumn=""22"" document=""0"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""23"" endLine=""9"" endColumn=""24"" document=""0"" /> </sequencePoints> </method> <method containingType=""Program+&lt;Foo&gt;d__0"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""Program"" methodName=""F"" /> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""0"" /> <entry offset=""0x19"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""0"" /> <entry offset=""0x1a"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""21"" document=""0"" /> </sequencePoints> </method> </methods> </symbols>"); } [WorkItem(543376, "DevDiv")] [Fact] public void SimpleIterator2() { var text = @" class Program { System.Collections.Generic.IEnumerable<int> Foo() { yield break; } public void F() { } // needs to be present to work around SymWriter bug #1068894 } "; var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <methods> <method containingType=""Program"" name=""Foo""> <customDebugInfo> <forwardIterator name=""&lt;Foo&gt;d__0"" /> </customDebugInfo> </method> <method containingType=""Program"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""21"" endLine=""9"" endColumn=""22"" document=""0"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""23"" endLine=""9"" endColumn=""24"" document=""0"" /> </sequencePoints> </method> <method containingType=""Program+&lt;Foo&gt;d__0"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""Program"" methodName=""F"" /> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""0"" /> <entry offset=""0x19"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""0"" /> <entry offset=""0x1a"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""21"" document=""0"" /> </sequencePoints> </method> </methods> </symbols>"); } [WorkItem(543490, "DevDiv")] [Fact] public void SimpleIterator3() { var text = @" class Program { System.Collections.Generic.IEnumerable<int> Foo() { yield return 1; //hidden sequence point after this. } public void F() { } // needs to be present to work around SymWriter bug #1068894 } "; var v = CompileAndVerify(text, options: TestOptions.DebugDll); v.VerifyIL("Program.<Foo>d__0.System.Collections.IEnumerator.MoveNext", @" { // Code size 63 (0x3f) .maxstack 2 .locals init (int V_0, bool V_1) ~IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Foo>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_001a IL_0014: br.s IL_0034 IL_0016: ldc.i4.0 IL_0017: stloc.1 IL_0018: ldloc.1 IL_0019: ret IL_001a: ldarg.0 IL_001b: ldc.i4.m1 IL_001c: stfld ""int Program.<Foo>d__0.<>1__state"" -IL_0021: nop -IL_0022: ldarg.0 IL_0023: ldc.i4.1 IL_0024: stfld ""int Program.<Foo>d__0.<>2__current"" IL_0029: ldarg.0 IL_002a: ldc.i4.1 IL_002b: stfld ""int Program.<Foo>d__0.<>1__state"" IL_0030: ldc.i4.1 IL_0031: stloc.1 IL_0032: br.s IL_0018 ~IL_0034: ldarg.0 IL_0035: ldc.i4.m1 IL_0036: stfld ""int Program.<Foo>d__0.<>1__state"" -IL_003b: ldc.i4.0 IL_003c: stloc.1 IL_003d: br.s IL_0018 } ", sequencePoints: "Program+<Foo>d__0.MoveNext"); v.VerifyPdb(@" <symbols> <methods> <method containingType=""Program"" name=""Foo""> <customDebugInfo> <forwardIterator name=""&lt;Foo&gt;d__0"" /> </customDebugInfo> </method> <method containingType=""Program"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""21"" endLine=""9"" endColumn=""22"" document=""0"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""23"" endLine=""9"" endColumn=""24"" document=""0"" /> </sequencePoints> </method> <method containingType=""Program+&lt;Foo&gt;d__0"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""Program"" methodName=""F"" /> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""0"" /> <entry offset=""0x21"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""0"" /> <entry offset=""0x22"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""24"" document=""0"" /> <entry offset=""0x34"" hidden=""true"" document=""0"" /> <entry offset=""0x3b"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""0"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void IteratorWithLocals_ReleasePdb() { var text = @" class Program { System.Collections.Generic.IEnumerable<int> IEI<T>(int i0, int i1) { int x = i0; yield return x; yield return x; { int y = i1; yield return y; yield return y; } yield break; } public void F() { } // needs to be present to work around SymWriter bug #1068894 } "; var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.ReleaseDll); c.VerifyPdb(@" <symbols> <methods> <method containingType=""Program"" name=""IEI"" parameterNames=""i0, i1""> <customDebugInfo> <forwardIterator name=""&lt;IEI&gt;d__0"" /> </customDebugInfo> </method> <method containingType=""Program"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""17"" startColumn=""23"" endLine=""17"" endColumn=""24"" document=""0"" /> </sequencePoints> </method> <method containingType=""Program+&lt;IEI&gt;d__0`1"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""Program"" methodName=""F"" /> <hoistedLocalScopes> <slot startOffset=""0x2a"" endOffset=""0xb3"" /> <slot startOffset=""0x6e"" endOffset=""0xb1"" /> </hoistedLocalScopes> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""0"" /> <entry offset=""0x2a"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""20"" document=""0"" /> <entry offset=""0x36"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""24"" document=""0"" /> <entry offset=""0x4b"" hidden=""true"" document=""0"" /> <entry offset=""0x52"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""24"" document=""0"" /> <entry offset=""0x67"" hidden=""true"" document=""0"" /> <entry offset=""0x6e"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""24"" document=""0"" /> <entry offset=""0x7a"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""28"" document=""0"" /> <entry offset=""0x8f"" hidden=""true"" document=""0"" /> <entry offset=""0x96"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""28"" document=""0"" /> <entry offset=""0xab"" hidden=""true"" document=""0"" /> <entry offset=""0xb2"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""21"" document=""0"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void IteratorWithLocals_DebugPdb() { var text = @" class Program { System.Collections.Generic.IEnumerable<int> IEI<T>(int i0, int i1) { int x = i0; yield return x; yield return x; { int y = i1; yield return y; yield return y; } yield break; } public void F() { } // needs to be present to work around SymWriter bug #1068894 } "; var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <methods> <method containingType=""Program"" name=""IEI"" parameterNames=""i0, i1""> <customDebugInfo> <forwardIterator name=""&lt;IEI&gt;d__0"" /> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""0"" offset=""101"" /> </encLocalSlotMap> </customDebugInfo> </method> <method containingType=""Program"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""17"" startColumn=""21"" endLine=""17"" endColumn=""22"" document=""0"" /> <entry offset=""0x1"" startLine=""17"" startColumn=""23"" endLine=""17"" endColumn=""24"" document=""0"" /> </sequencePoints> </method> <method containingType=""Program+&lt;IEI&gt;d__0`1"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""Program"" methodName=""F"" /> <hoistedLocalScopes> <slot startOffset=""0x3b"" endOffset=""0xd7"" /> <slot startOffset=""0x84"" endOffset=""0xd0"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""0"" /> <entry offset=""0x3b"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""0"" /> <entry offset=""0x3c"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""20"" document=""0"" /> <entry offset=""0x48"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""24"" document=""0"" /> <entry offset=""0x5f"" hidden=""true"" document=""0"" /> <entry offset=""0x66"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""24"" document=""0"" /> <entry offset=""0x7d"" hidden=""true"" document=""0"" /> <entry offset=""0x84"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""0"" /> <entry offset=""0x85"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""24"" document=""0"" /> <entry offset=""0x91"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""28"" document=""0"" /> <entry offset=""0xa8"" hidden=""true"" document=""0"" /> <entry offset=""0xaf"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""28"" document=""0"" /> <entry offset=""0xc9"" hidden=""true"" document=""0"" /> <entry offset=""0xd0"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""0"" /> <entry offset=""0xd1"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""21"" document=""0"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void IteratorWithCapturedSyntheticVariables() { // this iterator captures the synthetic variable generated from the expansion of the foreach loop var text = @"// Based on LegacyTest csharp\Source\Conformance\iterators\blocks\using001.cs using System; using System.Collections.Generic; class Test<T> { public static IEnumerator<T> M(IEnumerable<T> items) { T val = default(T); foreach (T item in items) { val = item; yield return val; } yield return val; } public void F() { } // needs to be present to work around SymWriter bug #1068894 }"; var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <methods> <method containingType=""Test`1"" name=""M"" parameterNames=""items""> <customDebugInfo> <forwardIterator name=""&lt;M&gt;d__0"" /> <encLocalSlotMap> <slot kind=""0"" offset=""13"" /> <slot kind=""5"" offset=""42"" /> <slot kind=""0"" offset=""42"" /> </encLocalSlotMap> </customDebugInfo> </method> <method containingType=""Test`1"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""19"" startColumn=""21"" endLine=""19"" endColumn=""22"" document=""0"" /> <entry offset=""0x1"" startLine=""19"" startColumn=""23"" endLine=""19"" endColumn=""24"" document=""0"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> </scope> </method> <method containingType=""Test`1+&lt;M&gt;d__0"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""Test`1"" methodName=""F"" /> <hoistedLocalScopes> <slot startOffset=""0x32"" endOffset=""0xe1"" /> <slot startOffset=""0x0"" endOffset=""0x0"" /> <slot startOffset=""0x5b"" endOffset=""0xa4"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""temp"" /> <slot kind=""27"" offset=""0"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""0"" /> <entry offset=""0x32"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""0"" /> <entry offset=""0x33"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""28"" document=""0"" /> <entry offset=""0x3f"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""16"" document=""0"" /> <entry offset=""0x40"" startLine=""11"" startColumn=""28"" endLine=""11"" endColumn=""33"" document=""0"" /> <entry offset=""0x59"" hidden=""true"" document=""0"" /> <entry offset=""0x5b"" startLine=""11"" startColumn=""18"" endLine=""11"" endColumn=""24"" document=""0"" /> <entry offset=""0x6c"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""0"" /> <entry offset=""0x6d"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""24"" document=""0"" /> <entry offset=""0x79"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""30"" document=""0"" /> <entry offset=""0x90"" hidden=""true"" document=""0"" /> <entry offset=""0x98"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""0"" /> <entry offset=""0xa5"" startLine=""11"" startColumn=""25"" endLine=""11"" endColumn=""27"" document=""0"" /> <entry offset=""0xc0"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""26"" document=""0"" /> <entry offset=""0xd7"" hidden=""true"" document=""0"" /> <entry offset=""0xde"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""0"" /> <entry offset=""0xe2"" hidden=""true"" document=""0"" /> </sequencePoints> </method> </methods> </symbols>"); } [WorkItem(542705, "DevDiv"), WorkItem(528790, "DevDiv"), WorkItem(543490, "DevDiv")] [Fact()] public void IteratorBackToNextStatementAfterYieldReturn() { var text = @" using System.Collections.Generic; class C { IEnumerable<decimal> M() { const decimal d1 = 0.1M; yield return d1; const decimal dx = 1.23m; yield return dx; { const decimal d2 = 0.2M; yield return d2; } yield break; } static void Main() { foreach (var i in new C().M()) { System.Console.WriteLine(i); } } } "; using (new CultureContext("en-US")) { var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.ReleaseExe); c.VerifyPdb(@" <symbols> <entryPoint declaringType=""C"" methodName=""Main"" /> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forwardIterator name=""&lt;M&gt;d__0"" /> </customDebugInfo> </method> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""21"" startColumn=""27"" endLine=""21"" endColumn=""38"" document=""0"" /> <entry offset=""0x10"" hidden=""true"" document=""0"" /> <entry offset=""0x12"" startLine=""21"" startColumn=""18"" endLine=""21"" endColumn=""23"" document=""0"" /> <entry offset=""0x18"" startLine=""23"" startColumn=""13"" endLine=""23"" endColumn=""41"" document=""0"" /> <entry offset=""0x1d"" startLine=""21"" startColumn=""24"" endLine=""21"" endColumn=""26"" document=""0"" /> <entry offset=""0x27"" hidden=""true"" document=""0"" /> <entry offset=""0x31"" startLine=""25"" startColumn=""5"" endLine=""25"" endColumn=""6"" document=""0"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x32""> <namespace name=""System.Collections.Generic"" /> </scope> </method> <method containingType=""C+&lt;M&gt;d__0"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""C"" methodName=""Main"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""0"" /> <entry offset=""0x26"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""25"" document=""0"" /> <entry offset=""0x3f"" hidden=""true"" document=""0"" /> <entry offset=""0x46"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""25"" document=""0"" /> <entry offset=""0x60"" hidden=""true"" document=""0"" /> <entry offset=""0x67"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""29"" document=""0"" /> <entry offset=""0x80"" hidden=""true"" document=""0"" /> <entry offset=""0x87"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""21"" document=""0"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x89""> <scope startOffset=""0x26"" endOffset=""0x89""> <constant name=""d1"" value=""0.1"" type=""Decimal"" /> <constant name=""dx"" value=""1.23"" type=""Decimal"" /> <scope startOffset=""0x67"" endOffset=""0x87""> <constant name=""d2"" value=""0.2"" type=""Decimal"" /> </scope> </scope> </scope> </method> </methods> </symbols>"); } } [WorkItem(543490, "DevDiv")] [Fact()] public void IteratorMultipleEnumerables() { var text = @" using System; using System.Collections; using System.Collections.Generic; public class Test<T> : IEnumerable<T> where T : class { System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } public IEnumerator<T> GetEnumerator() { foreach (var v in this.IterProp) { yield return v; } foreach (var v in IterMethod()) { yield return v; } } public IEnumerable<T> IterProp { get { yield return null; yield return null; } } public IEnumerable<T> IterMethod() { yield return default(T); yield return null; yield break; } } public class Test { public static void Main() { foreach (var v in new Test<string>()) { } } } "; var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugExe); c.VerifyPdb(@" <symbols> <entryPoint declaringType=""Test"" methodName=""Main"" /> <methods> <method containingType=""Test`1"" name=""System.Collections.IEnumerable.GetEnumerator""> <customDebugInfo> <using> <namespace usingCount=""3"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""0"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""32"" document=""0"" /> <entry offset=""0xa"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""0"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xc""> <namespace name=""System"" /> <namespace name=""System.Collections"" /> <namespace name=""System.Collections.Generic"" /> </scope> </method> <method containingType=""Test`1"" name=""GetEnumerator""> <customDebugInfo> <forwardIterator name=""&lt;GetEnumerator&gt;d__1"" /> <encLocalSlotMap> <slot kind=""5"" offset=""11"" /> <slot kind=""0"" offset=""11"" /> <slot kind=""5"" offset=""104"" /> <slot kind=""0"" offset=""104"" /> </encLocalSlotMap> </customDebugInfo> </method> <method containingType=""Test`1"" name=""get_IterProp""> <customDebugInfo> <forwardIterator name=""&lt;get_IterProp&gt;d__3"" /> </customDebugInfo> </method> <method containingType=""Test`1"" name=""IterMethod""> <customDebugInfo> <forwardIterator name=""&lt;IterMethod&gt;d__4"" /> </customDebugInfo> </method> <method containingType=""Test"" name=""Main""> <customDebugInfo> <forward declaringType=""Test`1"" methodName=""System.Collections.IEnumerable.GetEnumerator"" /> <encLocalSlotMap> <slot kind=""5"" offset=""11"" /> <slot kind=""0"" offset=""11"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""45"" startColumn=""5"" endLine=""45"" endColumn=""6"" document=""0"" /> <entry offset=""0x1"" startLine=""46"" startColumn=""9"" endLine=""46"" endColumn=""16"" document=""0"" /> <entry offset=""0x2"" startLine=""46"" startColumn=""27"" endLine=""46"" endColumn=""45"" document=""0"" /> <entry offset=""0xd"" hidden=""true"" document=""0"" /> <entry offset=""0xf"" startLine=""46"" startColumn=""18"" endLine=""46"" endColumn=""23"" document=""0"" /> <entry offset=""0x16"" startLine=""46"" startColumn=""47"" endLine=""46"" endColumn=""48"" document=""0"" /> <entry offset=""0x17"" startLine=""46"" startColumn=""49"" endLine=""46"" endColumn=""50"" document=""0"" /> <entry offset=""0x18"" startLine=""46"" startColumn=""24"" endLine=""46"" endColumn=""26"" document=""0"" /> <entry offset=""0x22"" hidden=""true"" document=""0"" /> <entry offset=""0x2d"" startLine=""47"" startColumn=""5"" endLine=""47"" endColumn=""6"" document=""0"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2e""> <scope startOffset=""0xf"" endOffset=""0x18""> <local name=""v"" il_index=""1"" il_start=""0xf"" il_end=""0x18"" attributes=""0"" /> </scope> </scope> </method> <method containingType=""Test`1+&lt;GetEnumerator&gt;d__1"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""Test`1"" methodName=""System.Collections.IEnumerable.GetEnumerator"" /> <hoistedLocalScopes> <slot startOffset=""0x0"" endOffset=""0x0"" /> <slot startOffset=""0x54"" endOffset=""0x94"" /> <slot startOffset=""0x0"" endOffset=""0x0"" /> <slot startOffset=""0xd1"" endOffset=""0x10e"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""temp"" /> <slot kind=""27"" offset=""0"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""0"" /> <entry offset=""0x32"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""0"" /> <entry offset=""0x33"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""16"" document=""0"" /> <entry offset=""0x34"" startLine=""15"" startColumn=""27"" endLine=""15"" endColumn=""40"" document=""0"" /> <entry offset=""0x52"" hidden=""true"" document=""0"" /> <entry offset=""0x54"" startLine=""15"" startColumn=""18"" endLine=""15"" endColumn=""23"" document=""0"" /> <entry offset=""0x65"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" document=""0"" /> <entry offset=""0x66"" startLine=""17"" startColumn=""13"" endLine=""17"" endColumn=""28"" document=""0"" /> <entry offset=""0x80"" hidden=""true"" document=""0"" /> <entry offset=""0x88"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""10"" document=""0"" /> <entry offset=""0x95"" startLine=""15"" startColumn=""24"" endLine=""15"" endColumn=""26"" document=""0"" /> <entry offset=""0xb0"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""16"" document=""0"" /> <entry offset=""0xb1"" startLine=""19"" startColumn=""27"" endLine=""19"" endColumn=""39"" document=""0"" /> <entry offset=""0xcf"" hidden=""true"" document=""0"" /> <entry offset=""0xd1"" startLine=""19"" startColumn=""18"" endLine=""19"" endColumn=""23"" document=""0"" /> <entry offset=""0xe2"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""10"" document=""0"" /> <entry offset=""0xe3"" startLine=""21"" startColumn=""13"" endLine=""21"" endColumn=""28"" document=""0"" /> <entry offset=""0xfa"" hidden=""true"" document=""0"" /> <entry offset=""0x102"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""0"" /> <entry offset=""0x10f"" startLine=""19"" startColumn=""24"" endLine=""19"" endColumn=""26"" document=""0"" /> <entry offset=""0x12a"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""0"" /> <entry offset=""0x12e"" hidden=""true"" document=""0"" /> </sequencePoints> </method> <method containingType=""Test`1+&lt;get_IterProp&gt;d__3"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""Test`1"" methodName=""System.Collections.IEnumerable.GetEnumerator"" /> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""0"" /> <entry offset=""0x2c"" startLine=""28"" startColumn=""9"" endLine=""28"" endColumn=""10"" document=""0"" /> <entry offset=""0x2d"" startLine=""29"" startColumn=""13"" endLine=""29"" endColumn=""31"" document=""0"" /> <entry offset=""0x44"" hidden=""true"" document=""0"" /> <entry offset=""0x4b"" startLine=""30"" startColumn=""13"" endLine=""30"" endColumn=""31"" document=""0"" /> <entry offset=""0x62"" hidden=""true"" document=""0"" /> <entry offset=""0x69"" startLine=""31"" startColumn=""9"" endLine=""31"" endColumn=""10"" document=""0"" /> </sequencePoints> </method> <method containingType=""Test`1+&lt;IterMethod&gt;d__4"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""Test`1"" methodName=""System.Collections.IEnumerable.GetEnumerator"" /> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""0"" /> <entry offset=""0x2c"" startLine=""35"" startColumn=""5"" endLine=""35"" endColumn=""6"" document=""0"" /> <entry offset=""0x2d"" startLine=""36"" startColumn=""9"" endLine=""36"" endColumn=""33"" document=""0"" /> <entry offset=""0x44"" hidden=""true"" document=""0"" /> <entry offset=""0x4b"" startLine=""37"" startColumn=""9"" endLine=""37"" endColumn=""27"" document=""0"" /> <entry offset=""0x62"" hidden=""true"" document=""0"" /> <entry offset=""0x69"" startLine=""38"" startColumn=""9"" endLine=""38"" endColumn=""21"" document=""0"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void VariablesWithSubstitutedType1() { var text = @" using System.Collections.Generic; class C { static IEnumerable<T> F<T>(T[] o) { int i = 0; T t = default(T); yield return t; yield return o[i]; } } "; var v = CompileAndVerify(text, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(new[] { "<>1__state", "<>2__current", "<>l__initialThreadId", "o", "<>3__o", "<i>5__1", "<t>5__2" }, module.GetFieldNames("C.<F>d__0")); }); v.VerifyPdb("C+<F>d__0`1.MoveNext", @" <symbols> <methods> <method containingType=""C+&lt;F&gt;d__0`1"" name=""MoveNext""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <hoistedLocalScopes> <slot startOffset=""0x2c"" endOffset=""0x8a"" /> <slot startOffset=""0x2c"" endOffset=""0x8a"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""0"" /> <entry offset=""0x2c"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""0"" /> <entry offset=""0x2d"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""19"" document=""0"" /> <entry offset=""0x34"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""26"" document=""0"" /> <entry offset=""0x40"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""24"" document=""0"" /> <entry offset=""0x57"" hidden=""true"" document=""0"" /> <entry offset=""0x5e"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""27"" document=""0"" /> <entry offset=""0x80"" hidden=""true"" document=""0"" /> <entry offset=""0x87"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""0"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x8b""> <namespace name=""System.Collections.Generic"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void IteratorWithConditionalBranchDiscriminator1() { var text = @" using System.Collections.Generic; class C { static bool B() => false; static IEnumerable<int> F() { if (B()) { yield return 1; } } } "; // Note that conditional branch discriminator is not hoisted. var v = CompileAndVerify(text, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(new[] { "<>1__state", "<>2__current", "<>l__initialThreadId", }, module.GetFieldNames("C.<F>d__1")); }); v.VerifyIL("C.<F>d__1.System.Collections.IEnumerator.MoveNext", @" { // Code size 74 (0x4a) .maxstack 2 .locals init (int V_0, bool V_1, bool V_2) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__1.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_001a IL_0014: br.s IL_003e IL_0016: ldc.i4.0 IL_0017: stloc.1 IL_0018: ldloc.1 IL_0019: ret IL_001a: ldarg.0 IL_001b: ldc.i4.m1 IL_001c: stfld ""int C.<F>d__1.<>1__state"" IL_0021: nop IL_0022: call ""bool C.B()"" IL_0027: stloc.2 IL_0028: ldloc.2 IL_0029: brfalse.s IL_0046 IL_002b: nop IL_002c: ldarg.0 IL_002d: ldc.i4.1 IL_002e: stfld ""int C.<F>d__1.<>2__current"" IL_0033: ldarg.0 IL_0034: ldc.i4.1 IL_0035: stfld ""int C.<F>d__1.<>1__state"" IL_003a: ldc.i4.1 IL_003b: stloc.1 IL_003c: br.s IL_0018 IL_003e: ldarg.0 IL_003f: ldc.i4.m1 IL_0040: stfld ""int C.<F>d__1.<>1__state"" IL_0045: nop IL_0046: ldc.i4.0 IL_0047: stloc.1 IL_0048: br.s IL_0018 } "); v.VerifyPdb("C+<F>d__1.MoveNext", @" <symbols> <methods> <method containingType=""C+&lt;F&gt;d__1"" name=""MoveNext""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""temp"" /> <slot kind=""1"" offset=""11"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""0"" /> <entry offset=""0x21"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""0"" /> <entry offset=""0x22"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""17"" document=""0"" /> <entry offset=""0x28"" hidden=""true"" document=""0"" /> <entry offset=""0x2b"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""0"" /> <entry offset=""0x2c"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""28"" document=""0"" /> <entry offset=""0x3e"" hidden=""true"" document=""0"" /> <entry offset=""0x45"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""0"" /> <entry offset=""0x46"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""0"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x4a""> <namespace name=""System.Collections.Generic"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void SynthesizedVariables1() { var source = @" using System; using System.Collections.Generic; class C { public IEnumerable<int> M(IDisposable disposable) { foreach (var item in new[] { 1, 2, 3 }) { lock (this) { yield return 1; } } foreach (var item in new[] { 1, 2, 3 }) { } lock (this) { yield return 2; } if (disposable != null) { using (disposable) { yield return 3; } } lock (this) { yield return 4; } if (disposable != null) { using (disposable) { } } lock (this) { } } public void F() { } // needs to be present to work around SymWriter bug #1068894 }"; CompileAndVerify(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { AssertEx.Equal(new[] { "<>1__state", "<>2__current", "<>l__initialThreadId", "<>4__this", "disposable", "<>3__disposable", "<>7__wrap1", "<>7__wrap2", "<>7__wrap3", "<>7__wrap4", "<>7__wrap5", }, module.GetFieldNames("C.<M>d__0")); }); var v = CompileAndVerify(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { AssertEx.Equal(new[] { "<>1__state", "<>2__current", "<>l__initialThreadId", "disposable", "<>3__disposable", "<>4__this", "<>s__1", "<>s__2", "<item>5__3", "<>s__4", "<>s__5", "<>s__6", "<>s__7", "<item>5__8", "<>s__9", "<>s__10", "<>s__11", "<>s__12", "<>s__13", "<>s__14", "<>s__15", "<>s__16" }, module.GetFieldNames("C.<M>d__0")); }); v.VerifyPdb("C.M", @" <symbols> <methods> <method containingType=""C"" name=""M"" parameterNames=""disposable""> <customDebugInfo> <forwardIterator name=""&lt;M&gt;d__0"" /> <encLocalSlotMap> <slot kind=""6"" offset=""11"" /> <slot kind=""8"" offset=""11"" /> <slot kind=""0"" offset=""11"" /> <slot kind=""3"" offset=""53"" /> <slot kind=""2"" offset=""53"" /> <slot kind=""6"" offset=""96"" /> <slot kind=""8"" offset=""96"" /> <slot kind=""0"" offset=""96"" /> <slot kind=""3"" offset=""149"" /> <slot kind=""2"" offset=""149"" /> <slot kind=""4"" offset=""216"" /> <slot kind=""3"" offset=""266"" /> <slot kind=""2"" offset=""266"" /> <slot kind=""4"" offset=""333"" /> <slot kind=""3"" offset=""367"" /> <slot kind=""2"" offset=""367"" /> </encLocalSlotMap> </customDebugInfo> </method> </methods> </symbols>"); } [WorkItem(836491, "DevDiv")] [WorkItem(827337, "DevDiv")] [Fact] public void DisplayClass_AccrossSuspensionPoints_Debug() { string source = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> M() { byte x1 = 1; byte x2 = 1; byte x3 = 1; ((Action)(() => { x1 = x2 = x3; }))(); yield return x1 + x2 + x3; yield return x1 + x2 + x3; } } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(new[] { "<>1__state", "<>2__current", "<>l__initialThreadId", "<>8__1", // hoisted display class }, module.GetFieldNames("C.<M>d__0")); }); // One iterator local entry for the lambda local. v.VerifyPdb("C+<M>d__0.MoveNext", @" <symbols> <methods> <method containingType=""C+&lt;M&gt;d__0"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""C+&lt;&gt;c__DisplayClass0_0"" methodName=""&lt;M&gt;b__0"" /> <hoistedLocalScopes> <slot startOffset=""0x32"" endOffset=""0xfa"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""0"" /> <entry offset=""0x32"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""0"" /> <entry offset=""0x3d"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""21"" document=""0"" /> <entry offset=""0x49"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""21"" document=""0"" /> <entry offset=""0x55"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""21"" document=""0"" /> <entry offset=""0x61"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""47"" document=""0"" /> <entry offset=""0x78"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""35"" document=""0"" /> <entry offset=""0xaf"" hidden=""true"" document=""0"" /> <entry offset=""0xb6"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""35"" document=""0"" /> <entry offset=""0xed"" hidden=""true"" document=""0"" /> <entry offset=""0xf4"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""0"" /> </sequencePoints> </method> </methods> </symbols>"); } [WorkItem(836491, "DevDiv")] [WorkItem(827337, "DevDiv")] [Fact] public void DisplayClass_InBetweenSuspensionPoints_Release() { string source = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> M() { byte x1 = 1; byte x2 = 1; byte x3 = 1; ((Action)(() => { x1 = x2 = x3; }))(); yield return 1; } public void F() { } // needs to be present to work around SymWriter bug #1068894 } "; // TODO: Currently we don't have means neccessary to pass information about the display // class being pushed on evaluation stack, so that EE could find the locals. // Thus the locals are not available in EE. var v = CompileAndVerify(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(new[] { "<>1__state", "<>2__current", "<>l__initialThreadId", }, module.GetFieldNames("C.<M>d__0")); }); v.VerifyIL("C.<M>d__0.System.Collections.IEnumerator.MoveNext", @" { // Code size 90 (0x5a) .maxstack 3 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<M>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0010 IL_000a: ldloc.0 IL_000b: ldc.i4.1 IL_000c: beq.s IL_0051 IL_000e: ldc.i4.0 IL_000f: ret IL_0010: ldarg.0 IL_0011: ldc.i4.m1 IL_0012: stfld ""int C.<M>d__0.<>1__state"" IL_0017: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_001c: dup IL_001d: ldc.i4.1 IL_001e: stfld ""byte C.<>c__DisplayClass0_0.x1"" IL_0023: dup IL_0024: ldc.i4.1 IL_0025: stfld ""byte C.<>c__DisplayClass0_0.x2"" IL_002a: dup IL_002b: ldc.i4.1 IL_002c: stfld ""byte C.<>c__DisplayClass0_0.x3"" IL_0031: ldftn ""void C.<>c__DisplayClass0_0.<M>b__0()"" IL_0037: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_003c: callvirt ""void System.Action.Invoke()"" IL_0041: ldarg.0 IL_0042: ldc.i4.1 IL_0043: stfld ""int C.<M>d__0.<>2__current"" IL_0048: ldarg.0 IL_0049: ldc.i4.1 IL_004a: stfld ""int C.<M>d__0.<>1__state"" IL_004f: ldc.i4.1 IL_0050: ret IL_0051: ldarg.0 IL_0052: ldc.i4.m1 IL_0053: stfld ""int C.<M>d__0.<>1__state"" IL_0058: ldc.i4.0 IL_0059: ret } "); v.VerifyPdb("C+<M>d__0.MoveNext", @" <symbols> <methods> <method containingType=""C+&lt;M&gt;d__0"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""0"" /> <entry offset=""0x17"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""0"" /> <entry offset=""0x1c"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""21"" document=""0"" /> <entry offset=""0x23"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""21"" document=""0"" /> <entry offset=""0x2a"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""21"" document=""0"" /> <entry offset=""0x31"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""47"" document=""0"" /> <entry offset=""0x41"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""24"" document=""0"" /> <entry offset=""0x51"" hidden=""true"" document=""0"" /> <entry offset=""0x58"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""0"" /> </sequencePoints> </method> </methods> </symbols>"); v.VerifyPdb("C.M", @" <symbols> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forwardIterator name=""&lt;M&gt;d__0"" /> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""0"" /> <lambda offset=""95"" closure=""0"" /> </encLambdaMap> </customDebugInfo> </method> </methods> </symbols>"); } [Fact] public void DisplayClass_InBetweenSuspensionPoints_Debug() { string source = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> M() { byte x1 = 1; byte x2 = 1; byte x3 = 1; ((Action)(() => { x1 = x2 = x3; }))(); yield return 1; // Possible EnC edit - add lambda: // () => { x1 } } public void F() { } // needs to be present to work around SymWriter bug #1068894 } "; // We need to hoist display class variable to allow adding a new lambda after yield return // that shares closure with the existing lambda. var v = CompileAndVerify(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(new[] { "<>1__state", "<>2__current", "<>l__initialThreadId", "<>8__1", // hoisted display class }, module.GetFieldNames("C.<M>d__0")); }); v.VerifyIL("C.<M>d__0.System.Collections.IEnumerator.MoveNext", @" { // Code size 132 (0x84) .maxstack 2 .locals init (int V_0, bool V_1) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<M>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_001a IL_0014: br.s IL_0079 IL_0016: ldc.i4.0 IL_0017: stloc.1 IL_0018: ldloc.1 IL_0019: ret IL_001a: ldarg.0 IL_001b: ldc.i4.m1 IL_001c: stfld ""int C.<M>d__0.<>1__state"" IL_0021: ldarg.0 IL_0022: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0027: stfld ""C.<>c__DisplayClass0_0 C.<M>d__0.<>8__1"" IL_002c: ldarg.0 IL_002d: ldfld ""C.<>c__DisplayClass0_0 C.<M>d__0.<>8__1"" IL_0032: ldc.i4.1 IL_0033: stfld ""byte C.<>c__DisplayClass0_0.x1"" IL_0038: ldarg.0 IL_0039: ldfld ""C.<>c__DisplayClass0_0 C.<M>d__0.<>8__1"" IL_003e: ldc.i4.1 IL_003f: stfld ""byte C.<>c__DisplayClass0_0.x2"" IL_0044: ldarg.0 IL_0045: ldfld ""C.<>c__DisplayClass0_0 C.<M>d__0.<>8__1"" IL_004a: ldc.i4.1 IL_004b: stfld ""byte C.<>c__DisplayClass0_0.x3"" IL_0050: ldarg.0 IL_0051: ldfld ""C.<>c__DisplayClass0_0 C.<M>d__0.<>8__1"" IL_0056: ldftn ""void C.<>c__DisplayClass0_0.<M>b__0()"" IL_005c: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0061: callvirt ""void System.Action.Invoke()"" IL_0066: nop IL_0067: ldarg.0 IL_0068: ldc.i4.1 IL_0069: stfld ""int C.<M>d__0.<>2__current"" IL_006e: ldarg.0 IL_006f: ldc.i4.1 IL_0070: stfld ""int C.<M>d__0.<>1__state"" IL_0075: ldc.i4.1 IL_0076: stloc.1 IL_0077: br.s IL_0018 IL_0079: ldarg.0 IL_007a: ldc.i4.m1 IL_007b: stfld ""int C.<M>d__0.<>1__state"" IL_0080: ldc.i4.0 IL_0081: stloc.1 IL_0082: br.s IL_0018 } "); v.VerifyPdb("C+<M>d__0.MoveNext", @" <symbols> <methods> <method containingType=""C+&lt;M&gt;d__0"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> <hoistedLocalScopes> <slot startOffset=""0x21"" endOffset=""0x83"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""0"" /> <entry offset=""0x21"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""0"" /> <entry offset=""0x2c"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""21"" document=""0"" /> <entry offset=""0x38"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""21"" document=""0"" /> <entry offset=""0x44"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""21"" document=""0"" /> <entry offset=""0x50"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""47"" document=""0"" /> <entry offset=""0x67"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""24"" document=""0"" /> <entry offset=""0x79"" hidden=""true"" document=""0"" /> <entry offset=""0x80"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""0"" /> </sequencePoints> </method> </methods> </symbols>"); v.VerifyPdb("C.M", @" <symbols> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forwardIterator name=""&lt;M&gt;d__0"" /> <encLocalSlotMap> <slot kind=""30"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""0"" /> <lambda offset=""95"" closure=""0"" /> </encLambdaMap> </customDebugInfo> </method> </methods> </symbols>"); } [WorkItem(836491, "DevDiv")] [WorkItem(827337, "DevDiv")] [Fact] public void DynamicLocal_AccrossSuspensionPoints_Debug() { string source = @" using System.Collections.Generic; class C { static IEnumerable<int> M() { dynamic d = 1; yield return d; d.ToString(); } public void F() { } // needs to be present to work around SymWriter bug #1068894 } "; var v = CompileAndVerify(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(new[] { "<>1__state", "<>2__current", "<>l__initialThreadId", "<d>5__1" }, module.GetFieldNames("C.<M>d__0")); }); // CHANGE: Dev12 emits a <dynamiclocal> entry for "d", but gives it slot "-1", preventing it from matching // any locals when consumed by the EE (i.e. it has no effect). See FUNCBRECEE::IsLocalDynamic. v.VerifyPdb("C+<M>d__0.MoveNext", @" <symbols> <methods> <method containingType=""C+&lt;M&gt;d__0"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> <hoistedLocalScopes> <slot startOffset=""0x21"" endOffset=""0xeb"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""0"" /> <entry offset=""0x21"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""0"" /> <entry offset=""0x22"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""23"" document=""0"" /> <entry offset=""0x2e"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""24"" document=""0"" /> <entry offset=""0x86"" hidden=""true"" document=""0"" /> <entry offset=""0x8d"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""22"" document=""0"" /> <entry offset=""0xe5"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""0"" /> </sequencePoints> </method> </methods> </symbols>"); v.VerifyPdb("C.M", @" <symbols> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forwardIterator name=""&lt;M&gt;d__0"" /> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> </encLocalSlotMap> </customDebugInfo> </method> </methods> </symbols> "); } [WorkItem(836491, "DevDiv")] [WorkItem(827337, "DevDiv")] [WorkItem(1070519, "DevDiv")] [Fact] public void DynamicLocal_InBetweenSuspensionPoints_Release() { string source = @" using System.Collections.Generic; class C { static IEnumerable<int> M() { dynamic d = 1; yield return d; } public void F() { } // needs to be present to work around SymWriter bug #1068894 } "; var v = CompileAndVerify(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(new[] { "<>1__state", "<>2__current", "<>l__initialThreadId", }, module.GetFieldNames("C.<M>d__0")); }); v.VerifyPdb("C+<M>d__0.MoveNext", @" <symbols> <methods> <method containingType=""C+&lt;M&gt;d__0"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> <dynamicLocals> <bucket flagCount=""1"" flags=""1"" slotId=""1"" localName=""d"" /> </dynamicLocals> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""0"" /> <entry offset=""0x17"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""23"" document=""0"" /> <entry offset=""0x1e"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""24"" document=""0"" /> <entry offset=""0x6d"" hidden=""true"" document=""0"" /> <entry offset=""0x74"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""0"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x76""> <scope startOffset=""0x17"" endOffset=""0x76""> <local name=""d"" il_index=""1"" il_start=""0x17"" il_end=""0x76"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [WorkItem(1070519, "DevDiv")] [Fact] public void DynamicLocal_InBetweenSuspensionPoints_Debug() { string source = @" using System.Collections.Generic; class C { static IEnumerable<int> M() { dynamic d = 1; yield return d; // Possible EnC edit: // System.Console.WriteLine(d); } public void F() { } // needs to be present to work around SymWriter bug #1068894 } "; var v = CompileAndVerify(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(new[] { "<>1__state", "<>2__current", "<>l__initialThreadId", "<d>5__1", }, module.GetFieldNames("C.<M>d__0")); }); v.VerifyPdb("C+<M>d__0.MoveNext", @" <symbols> <methods> <method containingType=""C+&lt;M&gt;d__0"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> <hoistedLocalScopes> <slot startOffset=""0x21"" endOffset=""0x90"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""0"" /> <entry offset=""0x21"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""0"" /> <entry offset=""0x22"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""23"" document=""0"" /> <entry offset=""0x2e"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""24"" document=""0"" /> <entry offset=""0x86"" hidden=""true"" document=""0"" /> <entry offset=""0x8d"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""0"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact, WorkItem(667579, "DevDiv")] public void DebuggerHiddenIterator() { var text = @" using System; using System.Collections.Generic; using System.Diagnostics; class C { static void Main(string[] args) { foreach (var x in F()) ; } [DebuggerHidden] static IEnumerable<int> F() { throw new Exception(); yield break; } }"; var c = CreateCompilationWithMscorlibAndSystemCore(text, options: TestOptions.DebugDll); c.VerifyPdb("C+<F>d__1.MoveNext", @" <symbols> <methods> <method containingType=""C+&lt;F&gt;d__1"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""C"" methodName=""Main"" parameterNames=""args"" /> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""0"" /> <entry offset=""0x19"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""0"" /> <entry offset=""0x1a"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""31"" document=""0"" /> </sequencePoints> </method> </methods> </symbols>"); } } }
using System; using System.Collections.Generic; using System.IO; using System.Reflection; namespace Gaming.Game { public class DataAssetCache { private DataAssetTree m_DataAssetTree; private Dictionary<Type, Dictionary<String, GameObject>> m_AssetCache = new Dictionary<Type, Dictionary<string, GameObject>>(); private static DataAssetCache s_GlobalAssetCache = new DataAssetCache(); public static DataAssetCache Instance { get { return s_GlobalAssetCache; } } private DataAssetCache() { } public void SetAssetTree(DataAssetTree dataAssetTree) { m_DataAssetTree = dataAssetTree; } public bool AssetExists(Type GameObjectType, String AssetName) { String PathToAsset = m_DataAssetTree.GetPathToAsset(GameObjectType.Name, AssetName); if (PathToAsset == null) { return false; } return true; } public GameObject GetCopyOfAsset(Type GameObjectType, String AssetName) { // TODO: this code below seems like it should work and would be better (use the copy of the asset in the cache). /* GameObject asset = GetAsset(GameObjectType, AssetName); MemoryStream memoryStream = new MemoryStream(); XmlTextWriter xmlWriter = new XmlTextWriter(memoryStream, Encoding.UTF8); asset.SaveXML(xmlWriter); memoryStream.Position = 0; XmlTextReader xmlReader = new XmlTextReader(memoryStream); return GameObject.Load(xmlReader); */ String PathToAsset = m_DataAssetTree.GetPathToAsset(GameObjectType.Name, AssetName); return LoadGameObjectFromDisk(GameObjectType, AssetName, PathToAsset); } public GameObject GetAsset(Type GameObjectType, String AssetName) { if (AssetName == null) { AssetName = "!Default"; } GameObject Asset = GetAssetFromCache(GameObjectType, AssetName); if (Asset == null) { String PathToAsset = m_DataAssetTree.GetPathToAsset(GameObjectType.Name, AssetName); if (PathToAsset == null) { if (AssetName == "!Default") { // we are trying to load the default item and we don't have one yet. ConstructorInfo constructInfo = GameObjectType.GetConstructor(Type.EmptyTypes); if (constructInfo == null) { throw new System.Exception("You must have a default constructor defined for '" + GameObjectType.Name + "' for default game object creation to work."); } GameObject defaultGameObjectItem = (GameObject)constructInfo.Invoke(null); String DefaultAssetPath = m_DataAssetTree.Root + Path.DirectorySeparatorChar + "Default"; if (!Directory.Exists(DefaultAssetPath)) { Directory.CreateDirectory(DefaultAssetPath); } String PathName = DefaultAssetPath + Path.DirectorySeparatorChar + AssetName + "." + GameObjectType.Name; defaultGameObjectItem.SaveXML(PathName); AddAssetToCache(GameObjectType, AssetName, defaultGameObjectItem); return defaultGameObjectItem; } else { throw new System.Exception("'" + GameObjectType.Name + "' named '" + AssetName + "' does not exist."); } } GameObject gameObjectItem = LoadGameObjectFromDisk(GameObjectType, AssetName, PathToAsset); AddAssetToCache(GameObjectType, AssetName, gameObjectItem); return gameObjectItem; } return Asset; } private static GameObject LoadGameObjectFromDisk(Type GameObjectType, String AssetName, String PathToAsset) { Type[] ParamsLoadTakes = new Type[] { typeof(String) }; // TODO: more checking for right function. Must be static must return a GameObject. MethodInfo LoadFunction = GameObjectType.GetMethod("Load", ParamsLoadTakes); if (LoadFunction == null) { throw new System.Exception("You must implement the load function on '" + GameObjectType.Name + "'.\n" + "It will look like this, \n 'public new static GameObject Load(String PathName)'."); } object[] ParamsToCallLoadWith = new object[] { PathToAsset }; GameObject gameObjectItem; try { gameObjectItem = (GameObject)LoadFunction.Invoke(null, ParamsToCallLoadWith); } catch (Exception e) { throw e.InnerException; } if (gameObjectItem == null) { throw new System.Exception("The load failed for the '" + GameObjectType.Name + "' named '" + AssetName + "'."); } return gameObjectItem; } private GameObject GetAssetFromCache(Type GameObjectType, String AssetName) { Dictionary<string, GameObject> gameObjectClassDictionary; if (m_AssetCache.TryGetValue(GameObjectType, out gameObjectClassDictionary)) { GameObject gameObjectItem; if (gameObjectClassDictionary.TryGetValue(AssetName, out gameObjectItem)) { return gameObjectItem; } } return null; } private void AddAssetToCache(Type GameObjectType, String AssetName, GameObject Asset) { Dictionary<string, GameObject> gameObjectClassDictionary; if (!m_AssetCache.TryGetValue(GameObjectType, out gameObjectClassDictionary)) { // create the dictionary gameObjectClassDictionary = new Dictionary<string, GameObject>(); m_AssetCache.Add(GameObjectType, gameObjectClassDictionary); } GameObject itemInCach; if (gameObjectClassDictionary.TryGetValue(AssetName, out itemInCach)) { throw new System.Exception("The '" + GameObjectType.Name + "' asset named '" + AssetName + "' is already in the cache."); } gameObjectClassDictionary.Add(AssetName, Asset); } public void ModifyOrCreateAsset(GameObject AssetToSave, string DesiredPathHint, string AssetName) { if (AssetExists(AssetToSave.GetType(), AssetName)) { // re-save it String PathToAsset = m_DataAssetTree.GetPathToAsset(AssetToSave.GetType().Name, AssetName); AssetToSave.SaveXML(PathToAsset); } else { // create the file and save the asset String DesiredAssetPath = m_DataAssetTree.Root + Path.DirectorySeparatorChar + DesiredPathHint; if (!Directory.Exists(DesiredAssetPath)) { Directory.CreateDirectory(DesiredAssetPath); } String PathName = DesiredAssetPath + Path.DirectorySeparatorChar + AssetName + "." + AssetToSave.GetType().Name; AssetToSave.SaveXML(PathName); AddAssetToCache(AssetToSave.GetType(), AssetName, AssetToSave); m_DataAssetTree.AddItemToTree(PathName); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Threading; namespace System.Collections.Generic.Internal { /// <summary> /// Simplified version of Dictionary<K,V> /// 1. Deriving from DictionaryBase to share common code /// 2. Hashing/bucket moved to DictionaryBase /// 3. Seperate TKey,TValue array. This will get rid of array with both TKey and TValue /// 4. No interface implementation. You pay for the methods called /// 5. Support FindFirstKey/FindNextKey, hash code based search (returning key to caller for key comparison) /// 6. If comparer is provided, it has to be non null. This allows reducing dependency on EqualityComparer<TKey>.Default /// </summary> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TValue"></typeparam> internal class Dictionary<TKey, TValue> : DictionaryBase { private TKey[] keyArray; private TValue[] valueArray; private IEqualityComparer<TKey> comparer; private Lock m_lock; public Dictionary() : this(0, EqualityComparer<TKey>.Default, false) { } public Dictionary(bool sync) : this(0, EqualityComparer<TKey>.Default, sync) { } public Dictionary(int capacity) : this(capacity, EqualityComparer<TKey>.Default, false) { } public Dictionary(int capacity, bool sync) : this(capacity, EqualityComparer<TKey>.Default, sync) { } public Dictionary(IEqualityComparer<TKey> comparer) : this(0, comparer, false) { } public Dictionary(IEqualityComparer<TKey> comparer, bool sync) : this(0, comparer, sync) { } public Dictionary(int capacity, IEqualityComparer<TKey> comparer) : this(capacity, comparer, false) { } public Dictionary(int capacity, IEqualityComparer<TKey> comparer, bool sync) { // If comparer parameter is passed in, it can't be null // This removes dependency on EqualityComparer<TKey>.Default which brings bunch of cost Debug.Assert(comparer != null); if (capacity > 0) { Initialize(capacity); } this.comparer = comparer; if (sync) { m_lock = new Lock(); } } public Dictionary(IDictionary<TKey, TValue> dictionary) : this(dictionary, EqualityComparer<TKey>.Default) { } public Dictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer) : this(dictionary != null ? dictionary.Count : 0, comparer) { if (dictionary == null) { throw new ArgumentNullException("dictionary"); } foreach (KeyValuePair<TKey, TValue> pair in dictionary) { Add(pair.Key, pair.Value); } } public void LockAcquire() { Debug.Assert(m_lock != null); m_lock.Acquire(); } public void LockRelease() { Debug.Assert(m_lock != null); m_lock.Release(); } public IEqualityComparer<TKey> Comparer { get { return comparer; } } public KeyCollection Keys { get { Contract.Ensures(Contract.Result<KeyCollection>() != null); return new KeyCollection(this); } } public ValueCollection Values { get { Contract.Ensures(Contract.Result<ValueCollection>() != null); return new ValueCollection(this); } } public Enumerator GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } public TValue this[TKey key] { get { int i = FindEntry(key); if (i >= 0) { return valueArray[i]; } throw new KeyNotFoundException(); } set { Insert(key, value, false); } } public void Add(TKey key, TValue value) { if (!Insert(key, value, true)) { throw new ArgumentException(SR.Argument_AddingDuplicate); } } public void Add(TKey key, TValue value, int hashCode) { if (!Insert(key, value, true, hashCode)) { throw new ArgumentException(SR.Argument_AddingDuplicate); } } public void Clear() { if (count > 0) { ClearBase(); Array.Clear(keyArray, 0, count); Array.Clear(valueArray, 0, count); } } public bool ContainsKey(TKey key) { return FindEntry(key) >= 0; } public bool ContainsValue(TValue value) { if (value == null) { for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0 && valueArray[i] == null) { return true; } } } else { EqualityComparer<TValue> c = EqualityComparer<TValue>.Default; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0 && c.Equals(valueArray[i], value)) { return true; } } } return false; } private void CopyTo(KeyValuePair<TKey, TValue>[] array, int index) { if (array == null) { throw new ArgumentNullException("array"); } if (index < 0 || index > array.Length) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < Count) { throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); } int count = this.count; Entry[] entries = this.entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) { array[index++] = new KeyValuePair<TKey, TValue>(keyArray[i], valueArray[i]); } } } /// <summary> /// Get total count of items, including free cells /// </summary> /// <remarks> /// WARNING: This function will be called under a GC callback. Please read the comments in /// GCCallbackAttribute to understand all the implications before you make any changes /// </remarks> [System.Runtime.InteropServices.GCCallback] public int GetMaxCount() { return this.count; } /// <summary> /// Get Key[i], return true if not free /// </summary> public bool GetKey(int index, ref TKey key) { Debug.Assert((index >= 0) && (index < this.count)); if (entries[index].hashCode >= 0) { key = keyArray[index]; return true; } return false; } /// <summary> /// Get Value[i], return true if not free /// </summary> /// <remarks> /// WARNING: This function will be called under a GC callback. Please read the comments in /// GCCallbackAttribute to understand all the implications before you make any changes /// </remarks> [System.Runtime.InteropServices.GCCallback] public bool GetValue(int index, ref TValue value) { Debug.Assert((index >= 0) && (index < this.count)); if (entries[index].hashCode >= 0) { value = valueArray[index]; return true; } return false; } private int FindEntry(TKey key) { if (entries != null) { int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF; for (int i = entries[ModLength(hashCode)].bucket; i >= 0; i = entries[i].next) { if (entries[i].hashCode == hashCode && comparer.Equals(keyArray[i], key)) { return i; } } } return -1; } private int FindEntry(TKey key, int hashCode) { if (entries != null) { hashCode = hashCode & 0x7FFFFFFF; for (int i = entries[ModLength(hashCode)].bucket; i >= 0; i = entries[i].next) { if (entries[i].hashCode == hashCode && comparer.Equals(keyArray[i], key)) { return i; } } } return -1; } /// <summary> /// First first matching entry, returning index, update key /// </summary> /// <param name="key"></param> /// <returns></returns> public int FindFirstKey(ref TKey key) { int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF; int entry = FindFirstEntry(hashCode); if (entry >= 0) { key = keyArray[entry]; } return entry; } /// <summary> /// Find next matching entry, returning index, update key /// </summary> /// <param name="key"></param> /// <param name="entry"></param> /// <returns></returns> public int FindNextKey(ref TKey key, int entry) { entry = FindNextEntry(entry); if (entry >= 0) { key = keyArray[entry]; } return entry; } [MethodImpl(MethodImplOptions.NoInlining)] private void Initialize(int capacity) { int size = InitializeBase(capacity); keyArray = new TKey[size]; valueArray = new TValue[size]; } private bool Insert(TKey key, TValue value, bool add) { return Insert(key, value, add, comparer.GetHashCode(key)); } private bool Insert(TKey key, TValue value, bool add, int hashCode) { if (entries == null) { Initialize(0); } hashCode = hashCode & 0x7FFFFFFF; int targetBucket = ModLength(hashCode); for (int i = entries[targetBucket].bucket; i >= 0; i = entries[i].next) { if (entries[i].hashCode == hashCode && comparer.Equals(keyArray[i], key)) { if (add) { return false; } valueArray[i] = value; version++; return true; } } int index; if (freeCount > 0) { index = freeList; freeList = entries[index].next; freeCount--; } else { if (count == entries.Length) { Resize(); targetBucket = ModLength(hashCode); } index = count; count++; } entries[index].hashCode = hashCode; entries[index].next = entries[targetBucket].bucket; keyArray[index] = key; valueArray[index] = value; entries[targetBucket].bucket = index; version++; return true; } private void Resize() { Resize(HashHelpers.ExpandPrime(count)); } private void Resize(int newSize) { #if !RHTESTCL Contract.Assert(newSize >= entries.Length); #endif Entry[] newEntries = ResizeBase1(newSize); TKey[] newKeys = new TKey[newSize]; Array.Copy(keyArray, 0, newKeys, 0, count); TValue[] newValues = new TValue[newSize]; Array.Copy(valueArray, 0, newValues, 0, count); ResizeBase2(newEntries, newSize); keyArray = newKeys; valueArray = newValues; } public bool Remove(TKey key) { if (entries != null) { int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF; int bucket = ModLength(hashCode); int last = -1; for (int i = entries[bucket].bucket; i >= 0; last = i, i = entries[i].next) { if (entries[i].hashCode == hashCode && comparer.Equals(keyArray[i], key)) { if (last < 0) { entries[bucket].bucket = entries[i].next; } else { entries[last].next = entries[i].next; } entries[i].hashCode = -1; entries[i].next = freeList; keyArray[i] = default(TKey); valueArray[i] = default(TValue); freeList = i; freeCount++; version++; return true; } } } return false; } public bool TryGetValue(TKey key, out TValue value) { int i = FindEntry(key); if (i >= 0) { value = valueArray[i]; return true; } value = default(TValue); return false; } public bool TryGetValue(TKey key, int hashCode, out TValue value) { int i = FindEntry(key, hashCode); if (i >= 0) { value = valueArray[i]; return true; } value = default(TValue); return false; } /// <summary> /// Return matching key /// </summary> public bool TryGetKey(ref TKey key) { int i = FindEntry(key); if (i >= 0) { key = keyArray[i]; return true; } return false; } public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDictionaryEnumerator { private Dictionary<TKey, TValue> dictionary; private int version; private int index; private KeyValuePair<TKey, TValue> current; private int getEnumeratorRetType; // What should Enumerator.Current return? internal const int DictEntry = 1; internal const int KeyValuePair = 2; internal Enumerator(Dictionary<TKey, TValue> dictionary, int getEnumeratorRetType) { this.dictionary = dictionary; version = dictionary.version; index = 0; this.getEnumeratorRetType = getEnumeratorRetType; current = new KeyValuePair<TKey, TValue>(); } public bool MoveNext() { if (version != dictionary.version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } // Use unsigned comparison since we set index to dictionary.count+1 when the enumeration ends. // dictionary.count+1 could be negative if dictionary.count is Int32.MaxValue while ((uint)index < (uint)dictionary.count) { if (dictionary.entries[index].hashCode >= 0) { current = new KeyValuePair<TKey, TValue>(dictionary.keyArray[index], dictionary.valueArray[index]); index++; return true; } index++; } index = dictionary.count + 1; current = new KeyValuePair<TKey, TValue>(); return false; } public KeyValuePair<TKey, TValue> Current { get { return current; } } public void Dispose() { } object IEnumerator.Current { get { if (index == 0 || (index == dictionary.count + 1)) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } if (getEnumeratorRetType == DictEntry) { return new System.Collections.DictionaryEntry(current.Key, current.Value); } else { return new KeyValuePair<TKey, TValue>(current.Key, current.Value); } } } void IEnumerator.Reset() { if (version != dictionary.version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } index = 0; current = new KeyValuePair<TKey, TValue>(); } DictionaryEntry IDictionaryEnumerator.Entry { get { if (index == 0 || (index == dictionary.count + 1)) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return new DictionaryEntry(current.Key, current.Value); } } object IDictionaryEnumerator.Key { get { if (index == 0 || (index == dictionary.count + 1)) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return current.Key; } } object IDictionaryEnumerator.Value { get { if (index == 0 || (index == dictionary.count + 1)) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return current.Value; } } } public sealed class KeyCollection : ICollection<TKey>, ICollection { private Dictionary<TKey, TValue> dictionary; public KeyCollection(Dictionary<TKey, TValue> dictionary) { if (dictionary == null) { throw new ArgumentNullException("dictionary"); } this.dictionary = dictionary; } public Enumerator GetEnumerator() { return new Enumerator(dictionary); } public void CopyTo(TKey[] array, int index) { if (array == null) { throw new ArgumentNullException("array"); } if (index < 0 || index > array.Length) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < dictionary.Count) { throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); } int count = dictionary.count; TKey[] keys = dictionary.keyArray; Entry[] entries = dictionary.entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) { array[index++] = keys[i]; } } } public int Count { get { return dictionary.Count; } } bool ICollection<TKey>.IsReadOnly { get { return true; } } void ICollection<TKey>.Add(TKey item) { throw new NotSupportedException(SR.NotSupported_KeyCollectionSet); } void ICollection<TKey>.Clear() { throw new NotSupportedException(SR.NotSupported_KeyCollectionSet); } bool ICollection<TKey>.Contains(TKey item) { return dictionary.ContainsKey(item); } bool ICollection<TKey>.Remove(TKey item) { throw new NotSupportedException(SR.NotSupported_KeyCollectionSet); } IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator() { return new Enumerator(dictionary); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(dictionary); } void ICollection.CopyTo(Array array, int index) { if (array == null) { throw new ArgumentNullException("array"); } if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); } if (array.GetLowerBound(0) != 0) { throw new ArgumentException(SR.Arg_NonZeroLowerBound); } if (index < 0 || index > array.Length) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < dictionary.Count) { throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); } TKey[] keys = array as TKey[]; if (keys != null) { CopyTo(keys, index); } else { object[] objects = array as object[]; if (objects == null) { throw new ArgumentException(SR.Argument_InvalidArrayType); } int count = dictionary.count; Entry[] entries = dictionary.entries; TKey[] ks = dictionary.keyArray; try { for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) { objects[index++] = ks[i]; } } } catch (ArrayTypeMismatchException) { throw new ArgumentException(SR.Argument_InvalidArrayType); } } } bool ICollection.IsSynchronized { get { return false; } } Object ICollection.SyncRoot { get { return ((ICollection)dictionary).SyncRoot; } } public struct Enumerator : IEnumerator<TKey>, System.Collections.IEnumerator { private Dictionary<TKey, TValue> dictionary; private int index; private int version; private TKey currentKey; internal Enumerator(Dictionary<TKey, TValue> dictionary) { this.dictionary = dictionary; version = dictionary.version; index = 0; currentKey = default(TKey); } public void Dispose() { } public bool MoveNext() { if (version != dictionary.version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } while ((uint)index < (uint)dictionary.count) { if (dictionary.entries[index].hashCode >= 0) { currentKey = dictionary.keyArray[index]; index++; return true; } index++; } index = dictionary.count + 1; currentKey = default(TKey); return false; } public TKey Current { get { return currentKey; } } Object System.Collections.IEnumerator.Current { get { if (index == 0 || (index == dictionary.count + 1)) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return currentKey; } } void System.Collections.IEnumerator.Reset() { if (version != dictionary.version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } index = 0; currentKey = default(TKey); } } } public sealed class ValueCollection : ICollection<TValue>, ICollection { private Dictionary<TKey, TValue> dictionary; public ValueCollection(Dictionary<TKey, TValue> dictionary) { if (dictionary == null) { throw new ArgumentNullException("dictionary"); } this.dictionary = dictionary; } public Enumerator GetEnumerator() { return new Enumerator(dictionary); } public void CopyTo(TValue[] array, int index) { if (array == null) { throw new ArgumentNullException("array"); } if (index < 0 || index > array.Length) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < dictionary.Count) { throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); } int count = dictionary.count; Entry[] entries = dictionary.entries; TValue[] values = dictionary.valueArray; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) { array[index++] = values[i]; } } } public int Count { get { return dictionary.Count; } } bool ICollection<TValue>.IsReadOnly { get { return true; } } void ICollection<TValue>.Add(TValue item) { throw new NotSupportedException(SR.NotSupported_ValueCollectionSet); } bool ICollection<TValue>.Remove(TValue item) { throw new NotSupportedException(SR.NotSupported_ValueCollectionSet); } void ICollection<TValue>.Clear() { throw new NotSupportedException(SR.NotSupported_ValueCollectionSet); } bool ICollection<TValue>.Contains(TValue item) { return dictionary.ContainsValue(item); } IEnumerator<TValue> IEnumerable<TValue>.GetEnumerator() { return new Enumerator(dictionary); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(dictionary); } void ICollection.CopyTo(Array array, int index) { if (array == null) { throw new ArgumentNullException("array"); } if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); } if (array.GetLowerBound(0) != 0) { throw new ArgumentException(SR.Arg_NonZeroLowerBound); } if (index < 0 || index > array.Length) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < dictionary.Count) throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); TValue[] values = array as TValue[]; if (values != null) { CopyTo(values, index); } else { object[] objects = array as object[]; if (objects == null) { throw new ArgumentException(SR.Argument_InvalidArrayType); } int count = dictionary.count; Entry[] entries = dictionary.entries; TValue[] vs = dictionary.valueArray; try { for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) { objects[index++] = vs[i]; } } } catch (ArrayTypeMismatchException) { throw new ArgumentException(SR.Argument_InvalidArrayType); } } } bool ICollection.IsSynchronized { get { return false; } } Object ICollection.SyncRoot { get { return ((ICollection)dictionary).SyncRoot; } } public struct Enumerator : IEnumerator<TValue>, System.Collections.IEnumerator { private Dictionary<TKey, TValue> dictionary; private int index; private int version; private TValue currentValue; internal Enumerator(Dictionary<TKey, TValue> dictionary) { this.dictionary = dictionary; version = dictionary.version; index = 0; currentValue = default(TValue); } public void Dispose() { } public bool MoveNext() { if (version != dictionary.version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } while ((uint)index < (uint)dictionary.count) { if (dictionary.entries[index].hashCode >= 0) { currentValue = dictionary.valueArray[index]; index++; return true; } index++; } index = dictionary.count + 1; currentValue = default(TValue); return false; } public TValue Current { get { return currentValue; } } Object System.Collections.IEnumerator.Current { get { if (index == 0 || (index == dictionary.count + 1)) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return currentValue; } } void System.Collections.IEnumerator.Reset() { if (version != dictionary.version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } index = 0; currentValue = default(TValue); } } } } }
// 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 CompareLessThanSByte() { var test = new SimpleBinaryOpTest__CompareLessThanSByte(); 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(); // 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 works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareLessThanSByte { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(SByte); private const int Op2ElementCount = VectorSize / sizeof(SByte); private const int RetElementCount = VectorSize / sizeof(SByte); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector128<SByte> _clsVar1; private static Vector128<SByte> _clsVar2; private Vector128<SByte> _fld1; private Vector128<SByte> _fld2; private SimpleBinaryOpTest__DataTable<SByte, SByte, SByte> _dataTable; static SimpleBinaryOpTest__CompareLessThanSByte() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__CompareLessThanSByte() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<SByte, SByte, SByte>(_data1, _data2, new SByte[RetElementCount], VectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse2.CompareLessThan( Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse2.CompareLessThan( Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse2.CompareLessThan( Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareLessThan), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareLessThan), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareLessThan), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse2.CompareLessThan( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr); var result = Sse2.CompareLessThan(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareLessThan(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareLessThan(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__CompareLessThanSByte(); var result = Sse2.CompareLessThan(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse2.CompareLessThan(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<SByte> left, Vector128<SByte> right, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "") { if (result[0] != ((left[0] < right[0]) ? unchecked((sbyte)(-1)) : 0)) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((left[i] < right[i]) ? unchecked((sbyte)(-1)) : 0)) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.CompareLessThan)}<SByte>(Vector128<SByte>, Vector128<SByte>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// 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; 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', '/' }; private static readonly int MaxPath = Interop.Sys.MaxPath; private static readonly int MaxLongPath = MaxPath; private static bool IsDirectoryOrVolumeSeparator(char c) { // The directory separator is the same as the volume separator, // so we only need to check one. Debug.Assert(DirectorySeparatorChar == VolumeSeparatorChar); return PathInternal.IsDirectorySeparator(c); } // Expands the given path to a fully qualified path. public static string GetFullPath(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); if (path.Length == 0) throw new ArgumentException(SR.Arg_PathIllegal); PathInternal.CheckInvalidPathChars(path); // Expand with current directory if necessary if (!IsPathRooted(path)) { path = Combine(Interop.Sys.GetCwd(), path); } // We would ideally use realpath to do this, but it resolves symlinks, requires that the file actually exist, // and turns it into a full path, which we only want if fullCheck is true. string collapsedString = RemoveRelativeSegments(path); Debug.Assert(collapsedString.Length < path.Length || collapsedString.ToString() == path, "Either we've removed characters, or the string should be unmodified from the input path."); if (collapsedString.Length > MaxPath) { throw new PathTooLongException(SR.IO_PathTooLong); } string result = collapsedString.Length == 0 ? DirectorySeparatorCharAsString : collapsedString; return result; } /// <summary> /// Try to remove relative segments from the given path (without combining with a root). /// </summary> /// <param name="skip">Skip the specified number of characters before evaluating.</param> private static string RemoveRelativeSegments(string path, int skip = 0) { bool flippedSeparator = false; // Remove "//", "/./", and "/../" from the path by copying each character to the output, // except the ones we're removing, such that the builder contains the normalized path // at the end. var sb = StringBuilderCache.Acquire(path.Length); if (skip > 0) { sb.Append(path, 0, skip); } int componentCharCount = 0; for (int i = skip; i < path.Length; i++) { char c = path[i]; if (PathInternal.IsDirectorySeparator(c) && i + 1 < path.Length) { componentCharCount = 0; // Skip this character if it's a directory separator and if the next character is, too, // e.g. "parent//child" => "parent/child" if (PathInternal.IsDirectorySeparator(path[i + 1])) { continue; } // Skip this character and the next if it's referring to the current directory, // e.g. "parent/./child" =? "parent/child" if ((i + 2 == path.Length || PathInternal.IsDirectorySeparator(path[i + 2])) && path[i + 1] == '.') { i++; continue; } // Skip this character and the next two if it's referring to the parent directory, // e.g. "parent/child/../grandchild" => "parent/grandchild" if (i + 2 < path.Length && (i + 3 == path.Length || PathInternal.IsDirectorySeparator(path[i + 3])) && path[i + 1] == '.' && path[i + 2] == '.') { // Unwind back to the last slash (and if there isn't one, clear out everything). int s; for (s = sb.Length - 1; s >= 0; s--) { if (PathInternal.IsDirectorySeparator(sb[s])) { sb.Length = s; break; } } if (s < 0) { sb.Length = 0; } i += 2; continue; } } if (++componentCharCount > PathInternal.MaxComponentLength) { throw new PathTooLongException(SR.IO_PathTooLong); } // Normalize the directory separator if needed if (c != Path.DirectorySeparatorChar && c == Path.AltDirectorySeparatorChar) { c = Path.DirectorySeparatorChar; flippedSeparator = true; } sb.Append(c); } if (flippedSeparator || sb.Length != path.Length) { return StringBuilderCache.GetStringAndRelease(sb); } else { // We haven't changed the source path, return the original StringBuilderCache.Release(sb); return path; } } private static string RemoveLongPathPrefix(string path) { return path; // nop. There's nothing special about "long" paths on Unix. } public static string GetTempPath() { const string TempEnvVar = "TMPDIR"; const string DefaultTempPath = "/tmp/"; // Get the temp path from the TMPDIR environment variable. // If it's not set, just return the default path. // If it is, return it, ensuring it ends with a slash. string path = Environment.GetEnvironmentVariable(TempEnvVar); return string.IsNullOrEmpty(path) ? DefaultTempPath : PathInternal.IsDirectorySeparator(path[path.Length - 1]) ? path : path + DirectorySeparatorChar; } private static string InternalGetTempFileName(bool checkHost) { const string Suffix = ".tmp"; const int SuffixByteLength = 4; // mkstemps takes a char* and overwrites the XXXXXX with six characters // that'll result in a unique file name. string template = GetTempPath() + "tmpXXXXXX" + Suffix + "\0"; byte[] name = Encoding.UTF8.GetBytes(template); // Create, open, and close the temp file. IntPtr fd = Interop.CheckIo(Interop.Sys.MksTemps(name, SuffixByteLength)); Interop.Sys.Close(fd); // ignore any errors from close; nothing to do if cleanup isn't possible // 'name' is now the name of the file Debug.Assert(name[name.Length - 1] == '\0'); return Encoding.UTF8.GetString(name, 0, name.Length - 1); // trim off the trailing '\0' } public static bool IsPathRooted(string path) { if (path == null) return false; PathInternal.CheckInvalidPathChars(path); return path.Length > 0 && path[0] == DirectorySeparatorChar; } public static string GetPathRoot(string path) { if (path == null) return null; return IsPathRooted(path) ? DirectorySeparatorCharAsString : String.Empty; } private static byte[] CreateCryptoRandomByteArray(int byteLength) { var arr = new byte[byteLength]; if (!Interop.Crypto.GetRandomBytes(arr, arr.Length)) { throw new InvalidOperationException(SR.InvalidOperation_Cryptography); } return arr; } } }
using System; using System.Linq.Expressions; using AutoMapper.Mappers; using Shouldly; using Xunit; namespace AutoMapper.UnitTests { public class CustomValidations { public class Source { } public class Destination { } public class When_using_custom_validation { bool _calledForRoot = false; bool _calledForValues = false; bool _calledForInt = false; public class Source { public int[] Values { get; set; } } public class Dest { public int[] Values { get; set; } } [Fact] public void Should_call_the_validator() { var config = new MapperConfiguration(cfg => { cfg.Advanced.Validator(Validator); cfg.CreateMap<Source, Dest>(); }); config.AssertConfigurationIsValid(); _calledForRoot.ShouldBeTrue(); _calledForValues.ShouldBeTrue(); _calledForInt.ShouldBeTrue(); } private void Validator(ValidationContext context) { if (context.TypeMap != null) { _calledForRoot = true; context.TypeMap.Types.ShouldBe(context.Types); context.Types.SourceType.ShouldBe(typeof(Source)); context.Types.DestinationType.ShouldBe(typeof(Dest)); context.ObjectMapper.ShouldBeNull(); context.MemberMap.ShouldBeNull(); } else { context.MemberMap.SourceMember.Name.ShouldBe("Values"); context.MemberMap.DestinationName.ShouldBe("Values"); if (context.Types.Equals(new TypePair(typeof(int), typeof(int)))) { _calledForInt = true; context.ObjectMapper.ShouldBeOfType<AssignableMapper>(); } else { _calledForValues = true; context.ObjectMapper.ShouldBeOfType<ArrayCopyMapper>(); context.Types.SourceType.ShouldBe(typeof(int[])); context.Types.DestinationType.ShouldBe(typeof(int[])); } } } } public class When_using_custom_validation_for_convertusing_with_mappingfunction : NonValidatingSpecBase { // Nullable so can see a false state private static bool? _validated; protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { Func<Source, Destination, Destination> mappingFunction = (source, destination) => new Destination(); cfg.CreateMap<Source, Destination>().ConvertUsing(mappingFunction); cfg.Advanced.Validator(SetValidated); }); private static void SetValidated(ValidationContext context) { if (context.TypeMap.SourceType == typeof(Source) && context.TypeMap.DestinationTypeToUse == typeof(Destination)) { _validated = true; } } [Fact] public void Validator_should_be_called_by_AssertConfigurationIsValid() { _validated.ShouldBeNull(); Configuration.AssertConfigurationIsValid(); _validated.ShouldBe(true); } } public class When_using_custom_validation_for_convertusing_with_typeconvertertype : NonValidatingSpecBase { // Nullable so can see a false state private static bool? _validated; protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>().ConvertUsing<CustomTypeConverter>(); cfg.Advanced.Validator(SetValidated); }); private static void SetValidated(ValidationContext context) { if (context.TypeMap.SourceType == typeof(Source) && context.TypeMap.DestinationTypeToUse == typeof(Destination)) { _validated = true; } } [Fact] public void Validator_should_be_called_by_AssertConfigurationIsValid() { _validated.ShouldBeNull(); Configuration.AssertConfigurationIsValid(); _validated.ShouldBe(true); } internal class CustomTypeConverter : ITypeConverter<Source, Destination> { public Destination Convert(Source source, Destination destination, ResolutionContext context) { return new Destination(); } } } public class When_using_custom_validation_for_convertusing_with_typeconverter_instance : NonValidatingSpecBase { // Nullable so can see a false state private static bool? _validated; protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { cfg.CreateMap<Source, Destination>().ConvertUsing(new CustomTypeConverter()); cfg.Advanced.Validator(SetValidated); }); private static void SetValidated(ValidationContext context) { if (context.TypeMap.SourceType == typeof(Source) && context.TypeMap.DestinationTypeToUse == typeof(Destination)) { _validated = true; } } [Fact] public void Validator_should_be_called_by_AssertConfigurationIsValid() { _validated.ShouldBeNull(); Configuration.AssertConfigurationIsValid(); _validated.ShouldBe(true); } internal class CustomTypeConverter : ITypeConverter<Source, Destination> { public Destination Convert(Source source, Destination destination, ResolutionContext context) { return new Destination(); } } } public class When_using_custom_validation_for_convertusing_with_mappingexpression : NonValidatingSpecBase { // Nullable so can see a false state private static bool? _validated; protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { Expression<Func<Source, Destination>> mappingExpression = source => new Destination(); cfg.CreateMap<Source, Destination>().ConvertUsing(mappingExpression); cfg.Advanced.Validator(SetValidated); }); private static void SetValidated(ValidationContext context) { if (context.TypeMap.SourceType == typeof(Source) && context.TypeMap.DestinationTypeToUse == typeof(Destination)) { _validated = true; } } [Fact] public void Validator_should_be_called_by_AssertConfigurationIsValid() { _validated.ShouldBeNull(); Configuration.AssertConfigurationIsValid(); _validated.ShouldBe(true); } } } }
namespace NArrange.Tests.CSharp { using System.Collections.Generic; using System.IO; using NArrange.Core; using NArrange.Core.CodeElements; using NArrange.Core.Configuration; using NArrange.CSharp; using NArrange.Tests.Core; using NUnit.Framework; /// <summary> /// Test fixture for the CSharpWriter class. /// </summary> [TestFixture] public class CSharpWriterTests : CodeWriterTests<CSharpWriter> { #region Methods /// <summary> /// Tests writing an element with closing comments. /// </summary> [Test] public void ClosingCommentsTest() { TypeElement classElement = new TypeElement(); classElement.Name = "TestClass"; classElement.Type = TypeElementType.Class; classElement.Access = CodeAccess.Public; MethodElement methodElement = new MethodElement(); methodElement.Name = "DoSomething"; methodElement.Access = CodeAccess.Public; methodElement.Type = "bool"; methodElement.BodyText = "\treturn false;"; classElement.AddChild(methodElement); List<ICodeElement> codeElements = new List<ICodeElement>(); StringWriter writer; codeElements.Add(classElement); CodeConfiguration configuration = new CodeConfiguration(); CSharpWriter csharpWriter = new CSharpWriter(); csharpWriter.Configuration = configuration; configuration.Formatting.ClosingComments.Enabled = true; configuration.Formatting.ClosingComments.Format = "End $(ElementType) $(Name)"; writer = new StringWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "public class TestClass\r\n" + "{\r\n" + " public bool DoSomething()\r\n" + " {\r\n" + " return false;\r\n" + " } // End Method DoSomething\r\n" + "} // End Type TestClass", text, "Unexpected element text."); } /// <summary> /// Tests removal of consecutive blank lines. /// </summary> [Test] public void ConsecutiveBlankLineTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); MethodElement methodElement = new MethodElement(); methodElement.Access = CodeAccess.Public; methodElement.Type = "int"; methodElement.Name = "DoSomething"; methodElement.BodyText = "\tint val = 0;\r\n\r\n\r\n \r\n\t\t\t\r\n\treturn val;"; codeElements.Add(methodElement); CodeConfiguration configuration = CodeConfiguration.Default.Clone() as CodeConfiguration; configuration.Formatting.LineSpacing.RemoveConsecutiveBlankLines = true; CSharpWriter codeWriter = new CSharpWriter(); codeWriter.Configuration = configuration; StringWriter writer = new StringWriter(); codeWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "public int DoSomething()\r\n" + "{\r\n" + " int val = 0;\r\n" + "\r\n" + " return val;\r\n" + "}", text, "Method element was not written correctly."); configuration.Formatting.LineSpacing.RemoveConsecutiveBlankLines = false; writer = new StringWriter(); codeWriter.Write(codeElements.AsReadOnly(), writer); text = writer.ToString(); Assert.AreEqual( "public int DoSomething()\r\n" + "{\r\n" + " int val = 0;\r\n" + "\r\n" + "\r\n" + "\r\n" + "\r\n" + " return val;\r\n" + "}", text, "Method element was not written correctly."); } /// <summary> /// Tests writing an element with different tab styles. /// </summary> [Test] public void TabStyleTest() { TypeElement classElement = new TypeElement(); classElement.Name = "TestClass"; classElement.Type = TypeElementType.Class; classElement.Access = CodeAccess.Public; MethodElement methodElement = new MethodElement(); methodElement.Name = "DoSomething"; methodElement.Access = CodeAccess.Public; methodElement.Type = "bool"; methodElement.BodyText = "\treturn false;"; classElement.AddChild(methodElement); List<ICodeElement> codeElements = new List<ICodeElement>(); StringWriter writer; codeElements.Add(classElement); CodeConfiguration configuration = new CodeConfiguration(); CSharpWriter csharpWriter = new CSharpWriter(); csharpWriter.Configuration = configuration; // // Tabs // configuration.Formatting.Tabs.SpacesPerTab = 4; configuration.Formatting.Tabs.TabStyle = TabStyle.Tabs; writer = new StringWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "public class TestClass\r\n" + "{\r\n" + "\tpublic bool DoSomething()\r\n" + "\t{\r\n" + "\t\treturn false;\r\n" + "\t}\r\n" + "}", text, "Unexpected element text."); // // Spaces(4) // configuration.Formatting.Tabs.SpacesPerTab = 4; configuration.Formatting.Tabs.TabStyle = TabStyle.Spaces; writer = new StringWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); text = writer.ToString(); Assert.AreEqual( "public class TestClass\r\n" + "{\r\n" + " public bool DoSomething()\r\n" + " {\r\n" + " return false;\r\n" + " }\r\n" + "}", text, "Unexpected element text."); // // Spaces(8) // configuration.Formatting.Tabs.SpacesPerTab = 8; configuration.Formatting.Tabs.TabStyle = TabStyle.Spaces; writer = new StringWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); text = writer.ToString(); Assert.AreEqual( "public class TestClass\r\n" + "{\r\n" + " public bool DoSomething()\r\n" + " {\r\n" + " return false;\r\n" + " }\r\n" + "}", text, "Unexpected element text."); // // Parse spaces // configuration.Formatting.Tabs.SpacesPerTab = 4; configuration.Formatting.Tabs.TabStyle = TabStyle.Tabs; methodElement.BodyText = " return false;"; writer = new StringWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); text = writer.ToString(); Assert.AreEqual( "public class TestClass\r\n" + "{\r\n" + "\tpublic bool DoSomething()\r\n" + "\t{\r\n" + "\t\treturn false;\r\n" + "\t}\r\n" + "}", text, "Unexpected element text."); } /// <summary> /// Tests writing an attribute element with a list of children. /// </summary> [Test] public void WriteAttributeElementListTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); AttributeElement attributeElement = new AttributeElement(); attributeElement.Name = "Obsolete"; attributeElement.Target = "property"; attributeElement.BodyText = "\"This is obsolete\""; attributeElement.AddHeaderCommentLine( "<summary>We no longer need this...</summary>", true); AttributeElement childAttributeElement = new AttributeElement(); childAttributeElement.Name = "Description"; childAttributeElement.BodyText = "\"This is a description.\""; attributeElement.AddChild(childAttributeElement); StringWriter writer = new StringWriter(); codeElements.Add(attributeElement); CSharpWriter codeWriter = new CSharpWriter(); codeWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "///<summary>We no longer need this...</summary>\r\n" + "[property: Obsolete(\"This is obsolete\"),\r\nDescription(\"This is a description.\")]", text, "Attribute element was not written correctly."); } /// <summary> /// Tests writing an attribute element. /// </summary> [Test] public void WriteAttributeElementTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); AttributeElement attributeElement = new AttributeElement(); attributeElement.Name = "Obsolete"; attributeElement.BodyText = "\"This is obsolete\""; attributeElement.AddHeaderCommentLine( "<summary>We no longer need this...</summary>", true); StringWriter writer = new StringWriter(); codeElements.Add(attributeElement); CSharpWriter csharpWriter = new CSharpWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "///<summary>We no longer need this...</summary>\r\n" + "[Obsolete(\"This is obsolete\")]", text, "Attribute element was not written correctly."); } /// <summary> /// Tests writing a generic class. /// </summary> [Test] public void WriteClassDefinitionGenericTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); TypeElement classElement = new TypeElement(); classElement.Access = CodeAccess.Public; classElement.TypeModifiers = TypeModifiers.Static; classElement.Type = TypeElementType.Class; classElement.Name = "TestClass"; classElement.AddInterface( new InterfaceReference("IDisposable", InterfaceReferenceType.Interface)); classElement.AddTypeParameter(new TypeParameter("T")); codeElements.Add(classElement); StringWriter writer = new StringWriter(); CSharpWriter csharpWriter = new CSharpWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "public static class TestClass<T> : IDisposable\r\n" + "{\r\n}", text, "Class element was not written correctly."); classElement = new TypeElement(); classElement.Access = CodeAccess.Public; classElement.TypeModifiers = TypeModifiers.Static; classElement.Type = TypeElementType.Class; classElement.Name = "TestClass"; classElement.AddInterface( new InterfaceReference("IDisposable", InterfaceReferenceType.Interface)); classElement.AddTypeParameter( new TypeParameter("T", "class", "IDisposable", "new()")); codeElements[0] = classElement; writer = new StringWriter(); csharpWriter = new CSharpWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); text = writer.ToString(); Assert.AreEqual( "public static class TestClass<T> : IDisposable\r\n" + " where T : class, IDisposable, new()\r\n" + "{\r\n}", text, "Class element was not written correctly."); } /// <summary> /// Tests writing a partial class. /// </summary> [Test] public void WriteClassDefinitionPartialTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); TypeElement classElement = new TypeElement(); classElement.Access = CodeAccess.Public; classElement.TypeModifiers = TypeModifiers.Static | TypeModifiers.Partial; classElement.Type = TypeElementType.Class; classElement.Name = "TestClass"; classElement.AddTypeParameter( new TypeParameter("T", "class", "IDisposable", "new()")); classElement.AddInterface( new InterfaceReference("IDisposable", InterfaceReferenceType.Interface)); StringWriter writer = new StringWriter(); codeElements.Add(classElement); CSharpWriter csharpWriter = new CSharpWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "public static partial class TestClass<T> : IDisposable\r\n" + " where T : class, IDisposable, new()\r\n" + "{\r\n}", text, "Class element was not written correctly."); } /// <summary> /// Tests writing a class. /// </summary> [Test] public void WriteClassDefinitionTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); TypeElement classElement = new TypeElement(); classElement.Access = CodeAccess.Public; classElement.TypeModifiers = TypeModifiers.Sealed; classElement.Type = TypeElementType.Class; classElement.Name = "TestClass"; classElement.AddInterface( new InterfaceReference("IDisposable", InterfaceReferenceType.Interface)); classElement.AddInterface( new InterfaceReference("IEnumerable", InterfaceReferenceType.Interface)); StringWriter writer; codeElements.Add(classElement); CSharpWriter csharpWriter = new CSharpWriter(); writer = new StringWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "public sealed class TestClass : IDisposable, IEnumerable\r\n{\r\n}", text, "Class element was not written correctly."); classElement.TypeModifiers = TypeModifiers.Abstract; csharpWriter = new CSharpWriter(); writer = new StringWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); text = writer.ToString(); Assert.AreEqual( "public abstract class TestClass : IDisposable, IEnumerable\r\n{\r\n}", text, "Class element was not written correctly."); classElement.TypeModifiers = TypeModifiers.Static; csharpWriter = new CSharpWriter(); writer = new StringWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); text = writer.ToString(); Assert.AreEqual( "public static class TestClass : IDisposable, IEnumerable\r\n{\r\n}", text, "Class element was not written correctly."); classElement.TypeModifiers = TypeModifiers.Unsafe; csharpWriter = new CSharpWriter(); writer = new StringWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); text = writer.ToString(); Assert.AreEqual( "public unsafe class TestClass : IDisposable, IEnumerable\r\n{\r\n}", text, "Class element was not written correctly."); classElement.TypeModifiers = TypeModifiers.New; classElement.Access = CodeAccess.Private; csharpWriter = new CSharpWriter(); writer = new StringWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); text = writer.ToString(); Assert.AreEqual( "private new class TestClass : IDisposable, IEnumerable\r\n{\r\n}", text, "Class element was not written correctly."); } /// <summary> /// Tests writing a class with regions. /// </summary> [Test] public void WriteClassDefinitionWithRegionsTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); TypeElement classElement = new TypeElement(); classElement.Access = CodeAccess.Public; classElement.Type = TypeElementType.Class; classElement.Name = "TestClass"; RegionElement fieldsRegion = new RegionElement(); fieldsRegion.Name = "Fields"; FieldElement field1 = new FieldElement(); field1.Name = "_val1"; field1.Access = CodeAccess.Private; field1.Type = "int"; FieldElement field2 = new FieldElement(); field2.Name = "_val2"; field2.Access = CodeAccess.Private; field2.Type = "int"; fieldsRegion.AddChild(field1); fieldsRegion.AddChild(field2); classElement.AddChild(fieldsRegion); RegionElement methodsRegion = new RegionElement(); methodsRegion.Name = "Methods"; MethodElement method = new MethodElement(); method.Name = "DoSomething"; method.Access = CodeAccess.Public; method.Type = "void"; method.BodyText = string.Empty; methodsRegion.AddChild(method); classElement.AddChild(methodsRegion); StringWriter writer; codeElements.Add(classElement); CSharpWriter csharpWriter = new CSharpWriter(); writer = new StringWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "public class TestClass\r\n" + "{\r\n" + " #region Fields\r\n\r\n" + " private int _val1;\r\n" + " private int _val2;\r\n\r\n" + " #endregion Fields\r\n\r\n" + " #region Methods\r\n\r\n" + " public void DoSomething()\r\n" + " {\r\n" + " }\r\n\r\n" + " #endregion Methods\r\n" + "}", text, "Class element was not written correctly."); } /// <summary> /// Tests writing a class with unspecified access. /// </summary> [Test] public void WriteClassUnspecifiedAccessTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); TypeElement classElement = new TypeElement(); classElement.Access = CodeAccess.None; classElement.TypeModifiers = TypeModifiers.Partial; classElement.Type = TypeElementType.Class; classElement.Name = "TestClass"; classElement.AddInterface( new InterfaceReference("IDisposable", InterfaceReferenceType.Interface)); StringWriter writer = new StringWriter(); codeElements.Add(classElement); CSharpWriter csharpWriter = new CSharpWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "partial class TestClass : IDisposable\r\n" + "{\r\n}", text, "Class element was not written correctly."); } /// <summary> /// Tests writing a condition directive. /// </summary> [Test] public void WriteConditionDirectiveTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); ConditionDirectiveElement conditionDirectiveElement = new ConditionDirectiveElement(); conditionDirectiveElement.ConditionExpression = "DEBUG"; conditionDirectiveElement.ElseCondition = new ConditionDirectiveElement(); conditionDirectiveElement.ElseCondition.ConditionExpression = "TEST"; conditionDirectiveElement.ElseCondition.ElseCondition = new ConditionDirectiveElement(); StringWriter writer = new StringWriter(); codeElements.Add(conditionDirectiveElement); CSharpWriter codeWriter = new CSharpWriter(); codeWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "#if DEBUG\r\n" + "#elif TEST\r\n" + "#else\r\n" + "#endif", text, "Condition directive element was not written correctly."); } /// <summary> /// Tests writing a condition directive. /// </summary> [Test] public void WriteConditionDirectiveWithChildrenTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); ConditionDirectiveElement conditionDirectiveElement = new ConditionDirectiveElement(); conditionDirectiveElement.ConditionExpression = "DEBUG"; conditionDirectiveElement.AddChild(new CommentElement("Debug")); conditionDirectiveElement.ElseCondition = new ConditionDirectiveElement(); conditionDirectiveElement.ElseCondition.ConditionExpression = "TEST"; conditionDirectiveElement.ElseCondition.AddChild(new CommentElement("Test")); conditionDirectiveElement.ElseCondition.ElseCondition = new ConditionDirectiveElement(); conditionDirectiveElement.ElseCondition.ElseCondition.AddChild(new CommentElement("Else")); StringWriter writer = new StringWriter(); codeElements.Add(conditionDirectiveElement); CSharpWriter codeWriter = new CSharpWriter(); codeWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "#if DEBUG\r\n\r\n" + "//Debug\r\n\r\n" + "#elif TEST\r\n\r\n" + "//Test\r\n\r\n" + "#else\r\n\r\n" + "//Else\r\n\r\n" + "#endif", text, "Condition directive element was not written correctly."); } /// <summary> /// Tests writing a constructor with a constructor reference. /// </summary> [Test] public void WriteConstructorReferenceTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); ConstructorElement constructorElement = new ConstructorElement(); constructorElement.Access = CodeAccess.Public; constructorElement.Name = "TestClass"; constructorElement.Parameters = "int value"; constructorElement.Reference = "base(value)"; StringWriter writer = new StringWriter(); codeElements.Add(constructorElement); CSharpWriter csharpWriter = new CSharpWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "public TestClass(int value)\r\n : base(value)\r\n{\r\n}", text, "Constructor element was not written correctly."); } /// <summary> /// Tests writing a constructor. /// </summary> [Test] public void WriteConstructorTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); ConstructorElement constructorElement = new ConstructorElement(); constructorElement.Access = CodeAccess.Public; constructorElement.Name = "TestClass"; constructorElement.Parameters = "int value"; StringWriter writer = new StringWriter(); codeElements.Add(constructorElement); CSharpWriter csharpWriter = new CSharpWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "public TestClass(int value)\r\n{\r\n}", text, "Constructor element was not written correctly."); } /// <summary> /// Tests writing a generic delegate. /// </summary> [Test] public void WriteDelegateGenericTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); DelegateElement delegateElement = new DelegateElement(); delegateElement.Access = CodeAccess.Public; delegateElement.Type = "int"; delegateElement.Name = "Compare"; delegateElement.Parameters = "T t1, T t2"; delegateElement.AddTypeParameter( new TypeParameter("T", "class")); StringWriter writer = new StringWriter(); codeElements.Add(delegateElement); CSharpWriter csharpWriter = new CSharpWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "public delegate int Compare<T>(T t1, T t2)\r\n" + " where T : class;", text, "Delegate element was not written correctly."); } /// <summary> /// Tests writing a delegate. /// </summary> [Test] public void WriteDelegateTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); DelegateElement delegateElement = new DelegateElement(); delegateElement.Access = CodeAccess.Public; delegateElement.Type = "int"; delegateElement.Name = "DoSomething"; delegateElement.Parameters = "bool flag"; StringWriter writer = new StringWriter(); codeElements.Add(delegateElement); CSharpWriter csharpWriter = new CSharpWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "public delegate int DoSomething(bool flag);", text, "Delegate element was not written correctly."); } /// <summary> /// Tests writing an event. /// </summary> [Test] public void WriteEventTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); EventElement eventElement = new EventElement(); eventElement.Access = CodeAccess.Public; eventElement.Type = "EventHandler"; eventElement.Name = "TestEvent"; StringWriter writer = new StringWriter(); codeElements.Add(eventElement); CSharpWriter csharpWriter = new CSharpWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "public event EventHandler TestEvent;", text, "Event element was not written correctly."); } /// <summary> /// Tests writing a fixed field. /// </summary> [Test] public void WriteFieldFixedTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); FieldElement fieldElement = new FieldElement(); fieldElement.Access = CodeAccess.Public; fieldElement.Type = "char"; fieldElement.Name = "pathName[128]"; fieldElement[CSharpExtendedProperties.Fixed] = true; StringWriter writer = new StringWriter(); codeElements.Add(fieldElement); CSharpWriter csharpWriter = new CSharpWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "public fixed char pathName[128];", text, "FieldElement element was not written correctly."); } /// <summary> /// Tests writing a generic field. /// </summary> [Test] public void WriteFieldGenericTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); FieldElement fieldElement = new FieldElement(); fieldElement.Access = CodeAccess.Private; fieldElement.MemberModifiers = MemberModifiers.Static; fieldElement.Type = "Dictionary<string, int>"; fieldElement.Name = "_test"; fieldElement.InitialValue = "new Dictionary<string, int>()"; StringWriter writer = new StringWriter(); codeElements.Add(fieldElement); CSharpWriter csharpWriter = new CSharpWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "private static Dictionary<string, int> _test = new Dictionary<string, int>();", text, "FieldElement element was not written correctly."); } /// <summary> /// Tests writing a field that's whose intial value has multiple lines. /// </summary> [Test] public void WriteFieldMultilineInitialValueNewLineTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); TypeElement typeElement = new TypeElement(); typeElement.Name = "TestClass"; FieldElement fieldElement = new FieldElement(); fieldElement.Access = CodeAccess.Private; fieldElement.MemberModifiers = MemberModifiers.Static; fieldElement.Type = "string"; fieldElement.Name = "_test"; fieldElement.InitialValue = "\r\n\t\t\"This is a string on a single line.\""; typeElement.AddChild(fieldElement); StringWriter writer = new StringWriter(); codeElements.Add(typeElement); CSharpWriter csharpWriter = new CSharpWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "public class TestClass\r\n" + "{\r\n" + " private static string _test = \r\n" + " \"This is a string on a single line.\";\r\n" + "}", text, "Field element was not written correctly."); } /// <summary> /// Tests writing a field that's whose intial value has multiple lines. /// </summary> [Test] public void WriteFieldMultilineInitialValueSameLineTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); TypeElement typeElement = new TypeElement(); typeElement.Name = "TestClass"; FieldElement fieldElement = new FieldElement(); fieldElement.Access = CodeAccess.Private; fieldElement.MemberModifiers = MemberModifiers.Static; fieldElement.Type = "string"; fieldElement.Name = "_test"; fieldElement.InitialValue = "\"This is\" +\r\n\t\t\"string spanning multiple lines.\""; typeElement.AddChild(fieldElement); StringWriter writer = new StringWriter(); codeElements.Add(typeElement); CSharpWriter csharpWriter = new CSharpWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "public class TestClass\r\n" + "{\r\n" + " private static string _test = \"This is\" +\r\n" + " \"string spanning multiple lines.\";\r\n" + "}", text, "Field element was not written correctly."); } /// <summary> /// Tests writing a new constant field. /// </summary> [Test] public void WriteFieldNewConstantTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); FieldElement fieldElement = new FieldElement(); fieldElement.Access = CodeAccess.Public; fieldElement.MemberModifiers = MemberModifiers.Constant | MemberModifiers.New; fieldElement.Type = "string"; fieldElement.Name = "Test"; fieldElement.InitialValue = "\"Test\""; StringWriter writer = new StringWriter(); codeElements.Add(fieldElement); CSharpWriter codeWriter = new CSharpWriter(); codeWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "public new const string Test = \"Test\";", text, "FieldElement element was not written correctly."); } /// <summary> /// Tests writing a field. /// </summary> [Test] public void WriteFieldTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); FieldElement fieldElement = new FieldElement(); fieldElement.Access = CodeAccess.Private; fieldElement.MemberModifiers = MemberModifiers.Static; fieldElement.Type = "int"; fieldElement.Name = "_test"; fieldElement.InitialValue = "1"; StringWriter writer = new StringWriter(); codeElements.Add(fieldElement); CSharpWriter csharpWriter = new CSharpWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "private static int _test = 1;", text, "FieldElement element was not written correctly."); } /// <summary> /// Tests writing a field with a trailing block comment. /// </summary> [Test] public void WriteFieldTrailingBlockCommentTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); FieldElement fieldElement = new FieldElement(); fieldElement.Access = CodeAccess.Private; fieldElement.MemberModifiers = MemberModifiers.Static; fieldElement.Type = "int"; fieldElement.Name = "_test"; fieldElement.InitialValue = "1"; fieldElement.TrailingComment = new CommentElement( "Comment line 1\r\n\tComment line 2", CommentType.Block); StringWriter writer = new StringWriter(); codeElements.Add(fieldElement); CSharpWriter csharpWriter = new CSharpWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "private static int _test = 1; /*Comment line 1\r\n Comment line 2*/", text, "FieldElement element was not written correctly."); } /// <summary> /// Tests writing a field with a trailing comment. /// </summary> [Test] public void WriteFieldTrailingCommentTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); FieldElement fieldElement = new FieldElement(); fieldElement.Access = CodeAccess.Private; fieldElement.MemberModifiers = MemberModifiers.Static; fieldElement.Type = "int"; fieldElement.Name = "_test"; fieldElement.InitialValue = "1"; fieldElement.TrailingComment = new CommentElement("This is a comment"); StringWriter writer = new StringWriter(); codeElements.Add(fieldElement); CSharpWriter csharpWriter = new CSharpWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "private static int _test = 1; //This is a comment", text, "FieldElement element was not written correctly."); } /// <summary> /// Tests writing a volatile field. /// </summary> [Test] public void WriteFieldVolatileTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); FieldElement fieldElement = new FieldElement(); fieldElement.Access = CodeAccess.Private; fieldElement.MemberModifiers = MemberModifiers.Static; fieldElement.IsVolatile = true; fieldElement.Type = "int"; fieldElement.Name = "_test"; fieldElement.InitialValue = "1"; StringWriter writer = new StringWriter(); codeElements.Add(fieldElement); CSharpWriter csharpWriter = new CSharpWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "private static volatile int _test = 1;", text, "FieldElement element was not written correctly."); } /// <summary> /// Tests writing a group of elements. /// </summary> [Test] public void WriteGroupNestedTest() { GroupElement group = new GroupElement(); GroupElement group1 = new GroupElement(); GroupElement group1a = new GroupElement(); group1a.AddChild(new UsingElement("System")); group1a.AddChild(new UsingElement("System.IO")); group1a.AddChild(new UsingElement("System.Text")); group1.AddChild(group1a); GroupElement group1b = new GroupElement(); group1b.AddChild(new UsingElement("NArrange.Core")); group1.AddChild(group1b); group.AddChild(group1); GroupElement group2 = new GroupElement(); GroupElement group2a = new GroupElement(); group2a.AddChild(new UsingElement("MyClass", "System.String")); group2.AddChild(group2a); group.AddChild(group2); List<ICodeElement> codeElements = new List<ICodeElement>(); codeElements.Add(group); StringWriter writer; CSharpWriter csharpWriter = new CSharpWriter(); writer = new StringWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "using System;\r\n" + "using System.IO;\r\n" + "using System.Text;\r\n\r\n" + "using NArrange.Core;\r\n\r\n" + "using MyClass = System.String;", text, "Group was not written correctly."); group.SeparatorType = GroupSeparatorType.Custom; group.CustomSeparator = "\r\n"; group1.SeparatorType = GroupSeparatorType.Custom; group1.CustomSeparator = "\r\n"; group2.SeparatorType = GroupSeparatorType.Custom; group2.CustomSeparator = "\r\n"; writer = new StringWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); text = writer.ToString(); Assert.AreEqual( "using System;\r\n" + "using System.IO;\r\n" + "using System.Text;\r\n\r\n\r\n" + "using NArrange.Core;\r\n\r\n\r\n" + "using MyClass = System.String;", text, "Group was not written correctly."); } /// <summary> /// Tests writing a group of elements. /// </summary> [Test] public void WriteGroupTest() { string[] nameSpaces = new string[] { "System", "System.IO", "System.Text" }; GroupElement group = new GroupElement(); foreach (string nameSpace in nameSpaces) { UsingElement usingElement = new UsingElement(); usingElement.Name = nameSpace; group.AddChild(usingElement); } List<ICodeElement> codeElements = new List<ICodeElement>(); codeElements.Add(group); StringWriter writer; CSharpWriter csharpWriter = new CSharpWriter(); writer = new StringWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "using System;\r\n" + "using System.IO;\r\n" + "using System.Text;", text, "Group was not written correctly."); group.SeparatorType = GroupSeparatorType.Custom; group.CustomSeparator = "\r\n"; writer = new StringWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); text = writer.ToString(); Assert.AreEqual( "using System;\r\n\r\n" + "using System.IO;\r\n\r\n" + "using System.Text;", text, "Group was not written correctly."); } /// <summary> /// Tests writing an interface definition. /// </summary> [Test] public void WriteInterfaceDefinitionTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); TypeElement classElement = new TypeElement(); classElement.Access = CodeAccess.Public; classElement.Type = TypeElementType.Interface; classElement.Name = "TestInterface"; classElement.AddInterface( new InterfaceReference("IDisposable", InterfaceReferenceType.Interface)); StringWriter writer = new StringWriter(); codeElements.Add(classElement); CSharpWriter csharpWriter = new CSharpWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "public interface TestInterface : IDisposable\r\n" + "{\r\n}", text, "Interface element was not written correctly."); } /// <summary> /// Tests writing an abstract method. /// </summary> [Test] public void WriteMethodAbstractTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); MethodElement methodElement = new MethodElement(); methodElement.Access = CodeAccess.Protected; methodElement.MemberModifiers = MemberModifiers.Abstract; methodElement.Type = "void"; methodElement.Name = "DoSomething"; StringWriter writer = new StringWriter(); codeElements.Add(methodElement); CSharpWriter csharpWriter = new CSharpWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "protected abstract void DoSomething();", text, "Method element was not written correctly."); } /// <summary> /// Tests writing a method with a generic return type. /// </summary> [Test] public void WriteMethodGenericReturnTypeTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); MethodElement methodElement = new MethodElement(); methodElement.Access = CodeAccess.None; methodElement.Type = "IEnumerator<T>"; methodElement.Name = "IEnumerable<T>.GetEnumerator"; methodElement.BodyText = "\treturn null;"; StringWriter writer = new StringWriter(); codeElements.Add(methodElement); CSharpWriter csharpWriter = new CSharpWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "IEnumerator<T> IEnumerable<T>.GetEnumerator()\r\n" + "{\r\n" + " return null;\r\n" + "}", text, "Method element was not written correctly."); } /// <summary> /// Tests writing a partial method declaration. /// </summary> [Test] public void WriteMethodPartialDeclarationTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); MethodElement methodElement = new MethodElement(); methodElement.Access = CodeAccess.Private; methodElement.MemberModifiers = MemberModifiers.Partial; methodElement.Type = "void"; methodElement.Name = "DoSomething"; methodElement.Parameters = "bool flag"; methodElement.BodyText = null; StringWriter writer = new StringWriter(); codeElements.Add(methodElement); CSharpWriter csharpWriter = new CSharpWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "partial private void DoSomething(bool flag);", text, "Method element was not written correctly."); } /// <summary> /// Tests writing a partial method implementation. /// </summary> [Test] public void WriteMethodPartialImplementationTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); MethodElement methodElement = new MethodElement(); methodElement.Access = CodeAccess.Private; methodElement.MemberModifiers = MemberModifiers.Partial; methodElement.Type = "void"; methodElement.Name = "DoSomething"; methodElement.Parameters = "bool flag"; methodElement.BodyText = "\treturn;"; StringWriter writer = new StringWriter(); codeElements.Add(methodElement); CSharpWriter csharpWriter = new CSharpWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "partial private void DoSomething(bool flag)\r\n" + "{\r\n" + " return;\r\n" + "}", text, "Method element was not written correctly."); } /// <summary> /// Tests writing a sealed method. /// </summary> [Test] public void WriteMethodSealedTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); MethodElement methodElement = new MethodElement(); methodElement.Access = CodeAccess.Public; methodElement.MemberModifiers = MemberModifiers.Sealed | MemberModifiers.Override; methodElement.Type = "void"; methodElement.Name = "DoSomething"; StringWriter writer = new StringWriter(); codeElements.Add(methodElement); CSharpWriter csharpWriter = new CSharpWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "public override sealed void DoSomething();", text, "Method element was not written correctly."); } /// <summary> /// Tests writing a method. /// </summary> [Test] public void WriteMethodTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); MethodElement methodElement = new MethodElement(); methodElement.Access = CodeAccess.Public; methodElement.MemberModifiers = MemberModifiers.Static; methodElement.Type = "int"; methodElement.Name = "DoSomething"; methodElement.Parameters = "bool flag"; methodElement.BodyText = "\treturn 0;"; StringWriter writer = new StringWriter(); codeElements.Add(methodElement); CSharpWriter csharpWriter = new CSharpWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "public static int DoSomething(bool flag)\r\n" + "{\r\n" + " return 0;\r\n" + "}", text, "Method element was not written correctly."); } /// <summary> /// Tests writing an explicit operator. /// </summary> [Test] public void WriteOperatorExplicitTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); MethodElement operatorElement = new MethodElement(); operatorElement.IsOperator = true; operatorElement.OperatorType = OperatorType.Explicit; operatorElement.Name = null; operatorElement.Access = CodeAccess.Public; operatorElement.MemberModifiers = MemberModifiers.Static; operatorElement.Type = "decimal"; operatorElement.Parameters = "Fraction f"; operatorElement.BodyText = "return (decimal)f.num / f.den;"; StringWriter writer = new StringWriter(); codeElements.Add(operatorElement); CSharpWriter csharpWriter = new CSharpWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "public static explicit operator decimal(Fraction f)\r\n" + "{\r\n" + " return (decimal)f.num / f.den;\r\n" + "}", text, "Operator element was not written correctly."); } /// <summary> /// Tests writing an implicit operator. /// </summary> [Test] public void WriteOperatorImplicitTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); MethodElement operatorElement = new MethodElement(); operatorElement.IsOperator = true; operatorElement.OperatorType = OperatorType.Implicit; operatorElement.Name = null; operatorElement.Access = CodeAccess.Public; operatorElement.MemberModifiers = MemberModifiers.Static; operatorElement.Type = "double"; operatorElement.Parameters = "Fraction f"; operatorElement.BodyText = "return (double)f.num / f.den;"; StringWriter writer = new StringWriter(); codeElements.Add(operatorElement); CSharpWriter csharpWriter = new CSharpWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "public static implicit operator double(Fraction f)\r\n" + "{\r\n" + " return (double)f.num / f.den;\r\n" + "}", text, "Operator element was not written correctly."); } /// <summary> /// Tests writing an operator. /// </summary> [Test] public void WriteOperatorTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); MethodElement operatorElement = new MethodElement(); operatorElement.IsOperator = true; operatorElement.Name = "+"; operatorElement.Access = CodeAccess.Public; operatorElement.MemberModifiers = MemberModifiers.Static; operatorElement.Type = "Fraction"; operatorElement.Parameters = "Fraction a, Fraction b"; operatorElement.BodyText = "return new Fraction(a.num * b.den + b.num * a.den, a.den * b.den);"; StringWriter writer = new StringWriter(); codeElements.Add(operatorElement); CSharpWriter csharpWriter = new CSharpWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "public static Fraction operator +(Fraction a, Fraction b)\r\n" + "{\r\n" + " return new Fraction(a.num * b.den + b.num * a.den, a.den * b.den);\r\n" + "}", text, "Operator element was not written correctly."); } /// <summary> /// Tests writing a region with comment directives. /// </summary> [Test] public void WriteRegionCommentDirectiveTest() { TypeElement classElement = new TypeElement(); classElement.Name = "Test"; RegionElement regionElement = new RegionElement(); regionElement.Name = "TestRegion"; classElement.AddChild(regionElement); FieldElement fieldElement = new FieldElement(); fieldElement.Name = "val"; fieldElement.Type = "int"; regionElement.AddChild(fieldElement); List<ICodeElement> codeElements = new List<ICodeElement>(); StringWriter writer; codeElements.Add(classElement); CodeConfiguration configuration = new CodeConfiguration(); CSharpWriter codeWriter = new CSharpWriter(); codeWriter.Configuration = configuration; configuration.Formatting.Regions.EndRegionNameEnabled = true; configuration.Formatting.Regions.Style = RegionStyle.CommentDirective; writer = new StringWriter(); codeWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "public class Test\r\n" + "{\r\n" + " // $(Begin) TestRegion\r\n\r\n" + " public int val;\r\n\r\n" + " // $(End) TestRegion\r\n" + "}", text, "Unexpected element text."); } /// <summary> /// Tests writing a region with and without end region names enabled. /// </summary> [Test] public void WriteRegionEndRegionNameTest() { RegionElement regionElement = new RegionElement(); regionElement.Name = "TestRegion"; List<ICodeElement> codeElements = new List<ICodeElement>(); StringWriter writer; codeElements.Add(regionElement); CodeConfiguration configuration = new CodeConfiguration(); CSharpWriter codeWriter = new CSharpWriter(); codeWriter.Configuration = configuration; configuration.Formatting.Regions.EndRegionNameEnabled = true; writer = new StringWriter(); codeWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "#region TestRegion\r\n" + "#endregion TestRegion", text, "Unexpected element text."); configuration.Formatting.Regions.EndRegionNameEnabled = false; writer = new StringWriter(); codeWriter.Write(codeElements.AsReadOnly(), writer); text = writer.ToString(); Assert.AreEqual( "#region TestRegion\r\n" + "#endregion", text, "Unexpected element text."); } /// <summary> /// Tests writing a region with no directives. /// </summary> [Test] public void WriteRegionNoDirectiveTest() { TypeElement classElement = new TypeElement(); classElement.Name = "Test"; RegionElement regionElement = new RegionElement(); regionElement.Name = "TestRegion"; classElement.AddChild(regionElement); FieldElement fieldElement1 = new FieldElement(); fieldElement1.Name = "val1"; fieldElement1.Type = "int"; regionElement.AddChild(fieldElement1); FieldElement fieldElement2 = new FieldElement(); fieldElement2.Name = "val2"; fieldElement2.Type = "int"; regionElement.AddChild(fieldElement2); List<ICodeElement> codeElements = new List<ICodeElement>(); StringWriter writer; codeElements.Add(classElement); CodeConfiguration configuration = new CodeConfiguration(); CSharpWriter codeWriter = new CSharpWriter(); codeWriter.Configuration = configuration; string expectedText = "public class Test\r\n" + "{\r\n" + " public int val1;\r\n" + " public int val2;\r\n" + "}"; // // Turned off at the region level // regionElement.DirectivesEnabled = false; configuration.Formatting.Regions.EndRegionNameEnabled = true; configuration.Formatting.Regions.Style = RegionStyle.Directive; writer = new StringWriter(); codeWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual(expectedText, text, "Unexpected element text."); // // Turned off at the configuration level // regionElement.DirectivesEnabled = true; configuration.Formatting.Regions.EndRegionNameEnabled = true; configuration.Formatting.Regions.Style = RegionStyle.NoDirective; writer = new StringWriter(); codeWriter.Write(codeElements.AsReadOnly(), writer); text = writer.ToString(); Assert.AreEqual(expectedText, text, "Unexpected element text."); } /// <summary> /// Tests writing a using element with a redefine. /// </summary> [Test] public void WriteUsingElementRedefineTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); UsingElement usingElement = new UsingElement(); usingElement.Name = "SysText"; usingElement.Redefine = "System.Text"; StringWriter writer = new StringWriter(); codeElements.Add(usingElement); CSharpWriter csharpWriter = new CSharpWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "using SysText = System.Text;", text, "Using element was not written correctly."); } /// <summary> /// Tests writing a using element. /// </summary> [Test] public void WriteUsingElementTest() { List<ICodeElement> codeElements = new List<ICodeElement>(); UsingElement usingElement = new UsingElement(); usingElement.Name = "System.Text"; usingElement.AddHeaderCommentLine("We'll be doing several text operations."); StringWriter writer = new StringWriter(); codeElements.Add(usingElement); CSharpWriter csharpWriter = new CSharpWriter(); csharpWriter.Write(codeElements.AsReadOnly(), writer); string text = writer.ToString(); Assert.AreEqual( "//We'll be doing several text operations.\r\n" + "using System.Text;", text, "Using element was not written correctly."); } #endregion 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. #if XMLSERIALIZERGENERATOR namespace Microsoft.XmlSerializer.Generator #else namespace System.Xml.Serialization #endif { using System.Reflection; using System.Collections; using System.Xml.Schema; using System; using System.Text; using System.ComponentModel; using System.Xml; // These classes represent a mapping between classes and a particular XML format. // There are two class of mapping information: accessors (such as elements and // attributes), and mappings (which specify the type of an accessor). internal abstract class Accessor { private string _name; private object _defaultValue = null; private string _ns; private TypeMapping _mapping; private bool _any; private string _anyNs; private bool _topLevelInSchema; private bool _isFixed; private bool _isOptional; private XmlSchemaForm _form = XmlSchemaForm.None; internal Accessor() { } internal TypeMapping Mapping { get { return _mapping; } set { _mapping = value; } } internal object Default { get { return _defaultValue; } set { _defaultValue = value; } } internal bool HasDefault { get { return _defaultValue != null && _defaultValue != DBNull.Value; } } internal virtual string Name { get { return _name == null ? string.Empty : _name; } set { _name = value; } } internal bool Any { get { return _any; } set { _any = value; } } internal string AnyNamespaces { get { return _anyNs; } set { _anyNs = value; } } internal string Namespace { get { return _ns; } set { _ns = value; } } internal XmlSchemaForm Form { get { return _form; } set { _form = value; } } internal bool IsFixed { get { return _isFixed; } set { _isFixed = value; } } internal bool IsOptional { get { return _isOptional; } set { _isOptional = value; } } internal bool IsTopLevelInSchema { get { return _topLevelInSchema; } set { _topLevelInSchema = value; } } internal static string EscapeName(string name) { if (name == null || name.Length == 0) return name; return XmlConvert.EncodeLocalName(name); } internal static string EscapeQName(string name) { if (name == null || name.Length == 0) return name; int colon = name.LastIndexOf(':'); if (colon < 0) return XmlConvert.EncodeLocalName(name); else { if (colon == 0 || colon == name.Length - 1) throw new ArgumentException(SR.Format(SR.Xml_InvalidNameChars, name), nameof(name)); return new XmlQualifiedName(XmlConvert.EncodeLocalName(name.Substring(colon + 1)), XmlConvert.EncodeLocalName(name.Substring(0, colon))).ToString(); } } internal static string UnescapeName(string name) { return XmlConvert.DecodeName(name); } internal string ToString(string defaultNs) { if (Any) { return (Namespace == null ? "##any" : Namespace) + ":" + Name; } else { return Namespace == defaultNs ? Name : Namespace + ":" + Name; } } } internal class ElementAccessor : Accessor { private bool _nullable; private bool _isSoap; private bool _unbounded = false; internal bool IsSoap { get { return _isSoap; } set { _isSoap = value; } } internal bool IsNullable { get { return _nullable; } set { _nullable = value; } } internal bool IsUnbounded { get { return _unbounded; } set { _unbounded = value; } } internal ElementAccessor Clone() { ElementAccessor newAccessor = new ElementAccessor(); newAccessor._nullable = _nullable; newAccessor.IsTopLevelInSchema = this.IsTopLevelInSchema; newAccessor.Form = this.Form; newAccessor._isSoap = _isSoap; newAccessor.Name = this.Name; newAccessor.Default = this.Default; newAccessor.Namespace = this.Namespace; newAccessor.Mapping = this.Mapping; newAccessor.Any = this.Any; return newAccessor; } } internal class ChoiceIdentifierAccessor : Accessor { private string _memberName; private string[] _memberIds; private MemberInfo _memberInfo; internal string MemberName { get { return _memberName; } set { _memberName = value; } } internal string[] MemberIds { get { return _memberIds; } set { _memberIds = value; } } internal MemberInfo MemberInfo { get { return _memberInfo; } set { _memberInfo = value; } } } internal class TextAccessor : Accessor { } internal class XmlnsAccessor : Accessor { } internal class AttributeAccessor : Accessor { private bool _isSpecial; private bool _isList; internal bool IsSpecialXmlNamespace { get { return _isSpecial; } } internal bool IsList { get { return _isList; } set { _isList = value; } } internal void CheckSpecial() { int colon = Name.LastIndexOf(':'); if (colon >= 0) { if (!Name.StartsWith("xml:", StringComparison.Ordinal)) { throw new InvalidOperationException(SR.Format(SR.Xml_InvalidNameChars, Name)); } Name = Name.Substring("xml:".Length); Namespace = XmlReservedNs.NsXml; _isSpecial = true; } else { if (Namespace == XmlReservedNs.NsXml) { _isSpecial = true; } else { _isSpecial = false; } } if (_isSpecial) { Form = XmlSchemaForm.Qualified; } } } internal abstract class Mapping { private bool _isSoap; internal Mapping() { } protected Mapping(Mapping mapping) { _isSoap = mapping._isSoap; } internal bool IsSoap { get { return _isSoap; } set { _isSoap = value; } } } internal abstract class TypeMapping : Mapping { private TypeDesc _typeDesc; private string _typeNs; private string _typeName; private bool _referencedByElement; private bool _referencedByTopLevelElement; private bool _includeInSchema = true; private bool _reference = false; internal bool ReferencedByTopLevelElement { get { return _referencedByTopLevelElement; } set { _referencedByTopLevelElement = value; } } internal bool ReferencedByElement { get { return _referencedByElement || _referencedByTopLevelElement; } set { _referencedByElement = value; } } internal string Namespace { get { return _typeNs; } set { _typeNs = value; } } internal string TypeName { get { return _typeName; } set { _typeName = value; } } internal TypeDesc TypeDesc { get { return _typeDesc; } set { _typeDesc = value; } } internal bool IncludeInSchema { get { return _includeInSchema; } set { _includeInSchema = value; } } internal virtual bool IsList { get { return false; } set { } } internal bool IsReference { get { return _reference; } set { _reference = value; } } internal bool IsAnonymousType { get { return _typeName == null || _typeName.Length == 0; } } internal virtual string DefaultElementName { get { return IsAnonymousType ? XmlConvert.EncodeLocalName(_typeDesc.Name) : _typeName; } } } internal class PrimitiveMapping : TypeMapping { private bool _isList; internal override bool IsList { get { return _isList; } set { _isList = value; } } } internal class NullableMapping : TypeMapping { private TypeMapping _baseMapping; internal TypeMapping BaseMapping { get { return _baseMapping; } set { _baseMapping = value; } } internal override string DefaultElementName { get { return BaseMapping.DefaultElementName; } } } internal class ArrayMapping : TypeMapping { private ElementAccessor[] _elements; private ElementAccessor[] _sortedElements; private ArrayMapping _next; private StructMapping _topLevelMapping; internal ElementAccessor[] Elements { get { return _elements; } set { _elements = value; _sortedElements = null; } } internal ElementAccessor[] ElementsSortedByDerivation { get { if (_sortedElements != null) return _sortedElements; if (_elements == null) return null; _sortedElements = new ElementAccessor[_elements.Length]; Array.Copy(_elements, 0, _sortedElements, 0, _elements.Length); AccessorMapping.SortMostToLeastDerived(_sortedElements); return _sortedElements; } } internal ArrayMapping Next { get { return _next; } set { _next = value; } } internal StructMapping TopLevelMapping { get { return _topLevelMapping; } set { _topLevelMapping = value; } } } internal class EnumMapping : PrimitiveMapping { private ConstantMapping[] _constants; private bool _isFlags; internal bool IsFlags { get { return _isFlags; } set { _isFlags = value; } } internal ConstantMapping[] Constants { get { return _constants; } set { _constants = value; } } } internal class ConstantMapping : Mapping { private string _xmlName; private string _name; private long _value; internal string XmlName { get { return _xmlName == null ? string.Empty : _xmlName; } set { _xmlName = value; } } internal string Name { get { return _name == null ? string.Empty : _name; } set { _name = value; } } internal long Value { get { return _value; } set { _value = value; } } } internal class StructMapping : TypeMapping, INameScope { private MemberMapping[] _members; private StructMapping _baseMapping; private StructMapping _derivedMappings; private StructMapping _nextDerivedMapping; private MemberMapping _xmlnsMember = null; private bool _hasSimpleContent; private bool _openModel; private bool _isSequence; private NameTable _elements; private NameTable _attributes; private CodeIdentifiers _scope; internal StructMapping BaseMapping { get { return _baseMapping; } set { _baseMapping = value; if (!IsAnonymousType && _baseMapping != null) { _nextDerivedMapping = _baseMapping._derivedMappings; _baseMapping._derivedMappings = this; } if (value._isSequence && !_isSequence) { _isSequence = true; if (_baseMapping.IsSequence) { for (StructMapping derived = _derivedMappings; derived != null; derived = derived.NextDerivedMapping) { derived.SetSequence(); } } } } } internal StructMapping DerivedMappings { get { return _derivedMappings; } } internal bool IsFullyInitialized { get { return _baseMapping != null && Members != null; } } internal NameTable LocalElements { get { if (_elements == null) _elements = new NameTable(); return _elements; } } internal NameTable LocalAttributes { get { if (_attributes == null) _attributes = new NameTable(); return _attributes; } } object INameScope.this[string name, string ns] { get { object named = LocalElements[name, ns]; if (named != null) return named; if (_baseMapping != null) return ((INameScope)_baseMapping)[name, ns]; return null; } set { LocalElements[name, ns] = value; } } internal StructMapping NextDerivedMapping { get { return _nextDerivedMapping; } } internal bool HasSimpleContent { get { return _hasSimpleContent; } } internal bool HasXmlnsMember { get { StructMapping mapping = this; while (mapping != null) { if (mapping.XmlnsMember != null) return true; mapping = mapping.BaseMapping; } return false; } } internal MemberMapping[] Members { get { return _members; } set { _members = value; } } internal MemberMapping XmlnsMember { get { return _xmlnsMember; } set { _xmlnsMember = value; } } internal bool IsOpenModel { get { return _openModel; } set { _openModel = value; } } internal CodeIdentifiers Scope { get { if (_scope == null) _scope = new CodeIdentifiers(); return _scope; } set { _scope = value; } } internal MemberMapping FindDeclaringMapping(MemberMapping member, out StructMapping declaringMapping, string parent) { declaringMapping = null; if (BaseMapping != null) { MemberMapping baseMember = BaseMapping.FindDeclaringMapping(member, out declaringMapping, parent); if (baseMember != null) return baseMember; } if (_members == null) return null; for (int i = 0; i < _members.Length; i++) { if (_members[i].Name == member.Name) { if (_members[i].TypeDesc != member.TypeDesc) throw new InvalidOperationException(SR.Format(SR.XmlHiddenMember, parent, member.Name, member.TypeDesc.FullName, this.TypeName, _members[i].Name, _members[i].TypeDesc.FullName)); else if (!_members[i].Match(member)) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidXmlOverride, parent, member.Name, this.TypeName, _members[i].Name)); } declaringMapping = this; return _members[i]; } } return null; } internal bool Declares(MemberMapping member, string parent) { StructMapping m; return (FindDeclaringMapping(member, out m, parent) != null); } internal void SetContentModel(TextAccessor text, bool hasElements) { if (BaseMapping == null || BaseMapping.TypeDesc.IsRoot) { _hasSimpleContent = !hasElements && text != null && !text.Mapping.IsList; } else if (BaseMapping.HasSimpleContent) { if (text != null || hasElements) { // we can only extent a simleContent type with attributes throw new InvalidOperationException(SR.Format(SR.XmlIllegalSimpleContentExtension, TypeDesc.FullName, BaseMapping.TypeDesc.FullName)); } else { _hasSimpleContent = true; } } else { _hasSimpleContent = false; } if (!_hasSimpleContent && text != null && !text.Mapping.TypeDesc.CanBeTextValue) { throw new InvalidOperationException(SR.Format(SR.XmlIllegalTypedTextAttribute, TypeDesc.FullName, text.Name, text.Mapping.TypeDesc.FullName)); } } internal bool HasExplicitSequence() { if (_members != null) { for (int i = 0; i < _members.Length; i++) { if (_members[i].IsParticle && _members[i].IsSequence) { return true; } } } return (_baseMapping != null && _baseMapping.HasExplicitSequence()); } internal void SetSequence() { if (TypeDesc.IsRoot) return; StructMapping start = this; // find first mapping that does not have the sequence set while (start.BaseMapping != null && !start.BaseMapping.IsSequence && !start.BaseMapping.TypeDesc.IsRoot) start = start.BaseMapping; start.IsSequence = true; for (StructMapping derived = start.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) { derived.SetSequence(); } } internal bool IsSequence { get { return _isSequence && !TypeDesc.IsRoot; } set { _isSequence = value; } } } internal abstract class AccessorMapping : Mapping { private TypeDesc _typeDesc; private AttributeAccessor _attribute; private ElementAccessor[] _elements; private ElementAccessor[] _sortedElements; private TextAccessor _text; private ChoiceIdentifierAccessor _choiceIdentifier; private XmlnsAccessor _xmlns; private bool _ignore; internal AccessorMapping() { } protected AccessorMapping(AccessorMapping mapping) : base(mapping) { _typeDesc = mapping._typeDesc; _attribute = mapping._attribute; _elements = mapping._elements; _sortedElements = mapping._sortedElements; _text = mapping._text; _choiceIdentifier = mapping._choiceIdentifier; _xmlns = mapping._xmlns; _ignore = mapping._ignore; } internal bool IsAttribute { get { return _attribute != null; } } internal bool IsText { get { return _text != null && (_elements == null || _elements.Length == 0); } } internal bool IsParticle { get { return (_elements != null && _elements.Length > 0); } } internal TypeDesc TypeDesc { get { return _typeDesc; } set { _typeDesc = value; } } internal AttributeAccessor Attribute { get { return _attribute; } set { _attribute = value; } } internal ElementAccessor[] Elements { get { return _elements; } set { _elements = value; _sortedElements = null; } } internal static void SortMostToLeastDerived(ElementAccessor[] elements) { Array.Sort(elements, new AccessorComparer()); } internal class AccessorComparer : IComparer { public int Compare(object o1, object o2) { if (o1 == o2) return 0; Accessor a1 = (Accessor)o1; Accessor a2 = (Accessor)o2; int w1 = a1.Mapping.TypeDesc.Weight; int w2 = a2.Mapping.TypeDesc.Weight; if (w1 == w2) return 0; if (w1 < w2) return 1; return -1; } } internal ElementAccessor[] ElementsSortedByDerivation { get { if (_sortedElements != null) return _sortedElements; if (_elements == null) return null; _sortedElements = new ElementAccessor[_elements.Length]; Array.Copy(_elements, 0, _sortedElements, 0, _elements.Length); SortMostToLeastDerived(_sortedElements); return _sortedElements; } } internal TextAccessor Text { get { return _text; } set { _text = value; } } internal ChoiceIdentifierAccessor ChoiceIdentifier { get { return _choiceIdentifier; } set { _choiceIdentifier = value; } } internal XmlnsAccessor Xmlns { get { return _xmlns; } set { _xmlns = value; } } internal bool Ignore { get { return _ignore; } set { _ignore = value; } } internal Accessor Accessor { get { if (_xmlns != null) return _xmlns; if (_attribute != null) return _attribute; if (_elements != null && _elements.Length > 0) return _elements[0]; return _text; } } internal static bool ElementsMatch(ElementAccessor[] a, ElementAccessor[] b) { if (a == null) { if (b == null) return true; return false; } if (b == null) return false; if (a.Length != b.Length) return false; for (int i = 0; i < a.Length; i++) { if (a[i].Name != b[i].Name || a[i].Namespace != b[i].Namespace || a[i].Form != b[i].Form || a[i].IsNullable != b[i].IsNullable) return false; } return true; } internal bool Match(AccessorMapping mapping) { if (Elements != null && Elements.Length > 0) { if (!ElementsMatch(Elements, mapping.Elements)) { return false; } if (Text == null) { return (mapping.Text == null); } } if (Attribute != null) { if (mapping.Attribute == null) return false; return (Attribute.Name == mapping.Attribute.Name && Attribute.Namespace == mapping.Attribute.Namespace && Attribute.Form == mapping.Attribute.Form); } if (Text != null) { return (mapping.Text != null); } return (mapping.Accessor == null); } } internal class MemberMappingComparer : IComparer { public int Compare(object o1, object o2) { MemberMapping m1 = (MemberMapping)o1; MemberMapping m2 = (MemberMapping)o2; bool m1Text = m1.IsText; if (m1Text) { if (m2.IsText) return 0; return 1; } else if (m2.IsText) return -1; if (m1.SequenceId < 0 && m2.SequenceId < 0) return 0; if (m1.SequenceId < 0) return 1; if (m2.SequenceId < 0) return -1; if (m1.SequenceId < m2.SequenceId) return -1; if (m1.SequenceId > m2.SequenceId) return 1; return 0; } } internal class MemberMapping : AccessorMapping { private string _name; private bool _checkShouldPersist; private SpecifiedAccessor _checkSpecified; private bool _isReturnValue; private bool _readOnly = false; private int _sequenceId = -1; private MemberInfo _memberInfo; private MemberInfo _checkSpecifiedMemberInfo; private MethodInfo _checkShouldPersistMethodInfo; internal MemberMapping() { } private MemberMapping(MemberMapping mapping) : base(mapping) { _name = mapping._name; _checkShouldPersist = mapping._checkShouldPersist; _checkSpecified = mapping._checkSpecified; _isReturnValue = mapping._isReturnValue; _readOnly = mapping._readOnly; _sequenceId = mapping._sequenceId; _memberInfo = mapping._memberInfo; _checkSpecifiedMemberInfo = mapping._checkSpecifiedMemberInfo; _checkShouldPersistMethodInfo = mapping._checkShouldPersistMethodInfo; } internal bool CheckShouldPersist { get { return _checkShouldPersist; } set { _checkShouldPersist = value; } } internal SpecifiedAccessor CheckSpecified { get { return _checkSpecified; } set { _checkSpecified = value; } } internal string Name { get { return _name == null ? string.Empty : _name; } set { _name = value; } } internal MemberInfo MemberInfo { get { return _memberInfo; } set { _memberInfo = value; } } internal MemberInfo CheckSpecifiedMemberInfo { get { return _checkSpecifiedMemberInfo; } set { _checkSpecifiedMemberInfo = value; } } internal MethodInfo CheckShouldPersistMethodInfo { get { return _checkShouldPersistMethodInfo; } set { _checkShouldPersistMethodInfo = value; } } internal bool IsReturnValue { get { return _isReturnValue; } set { _isReturnValue = value; } } internal bool ReadOnly { get { return _readOnly; } set { _readOnly = value; } } internal bool IsSequence { get { return _sequenceId >= 0; } } internal int SequenceId { get { return _sequenceId; } set { _sequenceId = value; } } private string GetNullableType(TypeDesc td) { // SOAP encoded arrays not mapped to Nullable<T> since they always derive from soapenc:Array if (td.IsMappedType || (!td.IsValueType && (Elements[0].IsSoap || td.ArrayElementTypeDesc == null))) return td.FullName; if (td.ArrayElementTypeDesc != null) { return GetNullableType(td.ArrayElementTypeDesc) + "[]"; } return "System.Nullable`1[" + td.FullName + "]"; } internal MemberMapping Clone() { return new MemberMapping(this); } } internal class MembersMapping : TypeMapping { private MemberMapping[] _members; private bool _hasWrapperElement = true; private bool _validateRpcWrapperElement; private bool _writeAccessors = true; private MemberMapping _xmlnsMember = null; internal MemberMapping[] Members { get { return _members; } set { _members = value; } } internal MemberMapping XmlnsMember { get { return _xmlnsMember; } set { _xmlnsMember = value; } } internal bool HasWrapperElement { get { return _hasWrapperElement; } set { _hasWrapperElement = value; } } internal bool ValidateRpcWrapperElement { get { return _validateRpcWrapperElement; } set { _validateRpcWrapperElement = value; } } internal bool WriteAccessors { get { return _writeAccessors; } set { _writeAccessors = value; } } } internal class SpecialMapping : TypeMapping { private bool _namedAny; internal bool NamedAny { get { return _namedAny; } set { _namedAny = value; } } } internal class SerializableMapping : SpecialMapping { private XmlSchema _schema; private Type _type; private bool _needSchema = true; // new implementation of the IXmlSerializable private MethodInfo _getSchemaMethod; private XmlQualifiedName _xsiType; private XmlSchemaType _xsdType; private XmlSchemaSet _schemas; private bool _any; private string _namespaces; private SerializableMapping _baseMapping; private SerializableMapping _derivedMappings; private SerializableMapping _nextDerivedMapping; private SerializableMapping _next; // all mappings with the same qname internal SerializableMapping() { } internal SerializableMapping(MethodInfo getSchemaMethod, bool any, string ns) { _getSchemaMethod = getSchemaMethod; _any = any; this.Namespace = ns; _needSchema = getSchemaMethod != null; } internal SerializableMapping(XmlQualifiedName xsiType, XmlSchemaSet schemas) { _xsiType = xsiType; _schemas = schemas; this.TypeName = xsiType.Name; this.Namespace = xsiType.Namespace; _needSchema = false; } internal void SetBaseMapping(SerializableMapping mapping) { _baseMapping = mapping; if (_baseMapping != null) { _nextDerivedMapping = _baseMapping._derivedMappings; _baseMapping._derivedMappings = this; if (this == _nextDerivedMapping) { throw new InvalidOperationException(SR.Format(SR.XmlCircularDerivation, TypeDesc.FullName)); } } } internal bool IsAny { get { if (_any) return true; if (_getSchemaMethod == null) return false; if (_needSchema && typeof(XmlSchemaType).IsAssignableFrom(_getSchemaMethod.ReturnType)) return false; RetrieveSerializableSchema(); return _any; } } internal string NamespaceList { get { RetrieveSerializableSchema(); if (_namespaces == null) { if (_schemas != null) { StringBuilder anyNamespaces = new StringBuilder(); foreach (XmlSchema s in _schemas.Schemas()) { if (s.TargetNamespace != null && s.TargetNamespace.Length > 0) { if (anyNamespaces.Length > 0) anyNamespaces.Append(" "); anyNamespaces.Append(s.TargetNamespace); } } _namespaces = anyNamespaces.ToString(); } else { _namespaces = string.Empty; } } return _namespaces; } } internal SerializableMapping DerivedMappings { get { return _derivedMappings; } } internal SerializableMapping NextDerivedMapping { get { return _nextDerivedMapping; } } internal SerializableMapping Next { get { return _next; } set { _next = value; } } internal Type Type { get { return _type; } set { _type = value; } } internal XmlSchemaSet Schemas { get { RetrieveSerializableSchema(); return _schemas; } } internal XmlSchema Schema { get { RetrieveSerializableSchema(); return _schema; } } internal XmlQualifiedName XsiType { get { if (!_needSchema) return _xsiType; if (_getSchemaMethod == null) return null; if (typeof(XmlSchemaType).IsAssignableFrom(_getSchemaMethod.ReturnType)) return null; RetrieveSerializableSchema(); return _xsiType; } } internal XmlSchemaType XsdType { get { RetrieveSerializableSchema(); return _xsdType; } } internal static void ValidationCallbackWithErrorCode(object sender, ValidationEventArgs args) { // CONSIDER: need the real type name if (args.Severity == XmlSeverityType.Error) throw new InvalidOperationException(SR.Format(SR.XmlSerializableSchemaError, typeof(IXmlSerializable).Name, args.Message)); } internal void CheckDuplicateElement(XmlSchemaElement element, string elementNs) { if (element == null) return; // only check duplicate definitions for top-level element if (element.Parent == null || !(element.Parent is XmlSchema)) return; XmlSchemaObjectTable elements = null; if (Schema != null && Schema.TargetNamespace == elementNs) { #if !XMLSERIALIZERGENERATOR XmlSchemas.Preprocess(Schema); elements = Schema.Elements; #endif } else if (Schemas != null) { elements = Schemas.GlobalElements; } else { return; } foreach (XmlSchemaElement e in elements.Values) { if (e.Name == element.Name && e.QualifiedName.Namespace == elementNs) { if (Match(e, element)) return; // XmlSerializableRootDupName=Cannot reconcile schema for '{0}'. Please use [XmlRoot] attribute to change name or namepace of the top-level element to avoid duplicate element declarations: element name='{1} namespace='{2}'. throw new InvalidOperationException(SR.Format(SR.XmlSerializableRootDupName, _getSchemaMethod.DeclaringType.FullName, e.Name, elementNs)); } } } private bool Match(XmlSchemaElement e1, XmlSchemaElement e2) { if (e1.IsNillable != e2.IsNillable) return false; if (e1.RefName != e2.RefName) return false; if (e1.SchemaType != e2.SchemaType) return false; if (e1.SchemaTypeName != e2.SchemaTypeName) return false; if (e1.MinOccurs != e2.MinOccurs) return false; if (e1.MaxOccurs != e2.MaxOccurs) return false; if (e1.IsAbstract != e2.IsAbstract) return false; if (e1.DefaultValue != e2.DefaultValue) return false; if (e1.SubstitutionGroup != e2.SubstitutionGroup) return false; return true; } private void RetrieveSerializableSchema() { if (_needSchema) { _needSchema = false; if (_getSchemaMethod != null) { // get the type info if (_schemas == null) _schemas = new XmlSchemaSet(); object typeInfo = _getSchemaMethod.Invoke(null, new object[] { _schemas }); _xsiType = XmlQualifiedName.Empty; if (typeInfo != null) { if (typeof(XmlSchemaType).IsAssignableFrom(_getSchemaMethod.ReturnType)) { _xsdType = (XmlSchemaType)typeInfo; // check if type is named _xsiType = _xsdType.QualifiedName; } else if (typeof(XmlQualifiedName).IsAssignableFrom(_getSchemaMethod.ReturnType)) { _xsiType = (XmlQualifiedName)typeInfo; if (_xsiType.IsEmpty) { throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaEmptyTypeName, _type.FullName, _getSchemaMethod.Name)); } } else { throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaMethodReturnType, _type.Name, _getSchemaMethod.Name, typeof(XmlSchemaProviderAttribute).Name, typeof(XmlQualifiedName).FullName)); } } else { _any = true; } // make sure that user-specified schemas are valid _schemas.ValidationEventHandler += new ValidationEventHandler(ValidationCallbackWithErrorCode); _schemas.Compile(); #if !XMLSERIALIZERGENERATOR // at this point we verified that the information returned by the IXmlSerializable is valid // Now check to see if the type was referenced before: // UNDONE check for the duplcate types if (!_xsiType.IsEmpty) { // try to find the type in the schemas collection if (_xsiType.Namespace != XmlSchema.Namespace) { ArrayList srcSchemas = (ArrayList)_schemas.Schemas(_xsiType.Namespace); if (srcSchemas.Count == 0) { throw new InvalidOperationException(SR.Format(SR.XmlMissingSchema, _xsiType.Namespace)); } if (srcSchemas.Count > 1) { throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaInclude, _xsiType.Namespace, _getSchemaMethod.DeclaringType.FullName, _getSchemaMethod.Name)); } XmlSchema s = (XmlSchema)srcSchemas[0]; if (s == null) { throw new InvalidOperationException(SR.Format(SR.XmlMissingSchema, _xsiType.Namespace)); } _xsdType = (XmlSchemaType)s.SchemaTypes[_xsiType]; if (_xsdType == null) { throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaTypeMissing, _getSchemaMethod.DeclaringType.FullName, _getSchemaMethod.Name, _xsiType.Name, _xsiType.Namespace)); } _xsdType = _xsdType.Redefined != null ? _xsdType.Redefined : _xsdType; } } #endif } else { IXmlSerializable serializable = (IXmlSerializable)Activator.CreateInstance(_type); _schema = serializable.GetSchema(); if (_schema != null) { if (_schema.Id == null || _schema.Id.Length == 0) throw new InvalidOperationException(SR.Format(SR.XmlSerializableNameMissing1, _type.FullName)); } } } } } }
namespace Incoding.UnitTest.ExtensionsGroup { #region << Using >> using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Management.Instrumentation; using Incoding.Block; using Incoding.Block.Logging; using Incoding.CQRS; using Incoding.Extensions; using Incoding.MSpecContrib; using Incoding.UnitTest.Block; using Machine.Specifications; using Machine.Specifications.Annotations; #endregion [Subject(typeof(ReflectionExtensions))] public class When_reflection_extensions { #region Fake classes class FakeQuery : QueryBase<string> { protected override string ExecuteResult() { throw new NotImplementedException(); } } interface IGenericType { } class GenericType1 : IGenericType { } class GenericType2 : IGenericType { } class GenericType3 : IGenericType { } // ReSharper disable UnusedTypeParameter interface IGenericHandler<TGenericType> where TGenericType : IGenericType { } // ReSharper restore UnusedTypeParameter class GenericSubscriber : IGenericHandler<GenericType1>, IGenericHandler<GenericType2> { } class FakeSetValueClass { #region Static Fields static string staticValue = "staticValue"; #endregion #region Fields readonly string readOnlyPrivateField; string privateField; int privateIntField; int? privateIntNullableField; private object classField; #endregion internal class FakeInnerClass { public string Val { get; set; } } #region Properties [UsedImplicitly] public string PrivateField { get; set; } // ReSharper disable MemberCanBePrivate.Local protected string ProtectedProperty { get; set; } #endregion // ReSharper restore MemberCanBePrivate.Local #region Api Methods public string GetProtected() { return ProtectedProperty; } public string GetPrivateFiled() { return this.privateField; } public string GetReadOnlyPrivateFiled() { return this.readOnlyPrivateField; } public FakeSetValueClass SetPrivateField(string value) { this.privateField = value; return this; } public FakeSetValueClass SetPrivateIntField(int value) { this.privateIntField = value; return this; } public FakeSetValueClass SetPrivateIntNullableField(int? value) { this.privateIntNullableField = value; return this; } public FakeSetValueClass SetPrivateClassNullableField(FakeInnerClass value) { this.classField = value; return this; } #endregion } #endregion It should_be_primitive_int = () => typeof(int).IsPrimitive().ShouldBeTrue(); It should_be_primitive_nullable_int = () => typeof(int?).IsPrimitive().ShouldBeTrue(); It should_be_primitive_string = () => typeof(string).IsPrimitive().ShouldBeTrue(); It should_be_not_primitive = () => typeof(IGenericType).IsPrimitive().ShouldBeFalse(); It should_be_not_primitive_generic = () => typeof(IGenericHandler<GenericType2>).IsPrimitive().ShouldBeFalse(); It should_be_implement_class = () => typeof(ArgumentException).IsImplement<Exception>().ShouldBeTrue(); It should_be_implement_with_generic = () => typeof(List<int>).IsImplement<IList<int>>(); It should_be_implement_interface = () => typeof(ClipboardLogger).IsImplement<ILogger>().ShouldBeTrue(); It should_not_be_implement_interface = () => typeof(ClipboardLogger).IsImplement<ICloneable>().ShouldBeFalse(); It should_be_implement_query = () => typeof(FakeQuery).IsImplement(typeof(QueryBase<string>)).ShouldBeTrue(); It should_be_implement_deep = () => typeof(ArgumentException).IsImplement<object>().ShouldBeTrue(); It should_be_implement_generic_1 = () => typeof(GenericSubscriber).IsImplement(typeof(IGenericHandler<GenericType1>)).ShouldBeTrue(); It should_be_implement_generic_2 = () => typeof(GenericSubscriber).IsImplement(typeof(IGenericHandler<GenericType2>)).ShouldBeTrue(); It should_not_be_implement_generic_3 = () => typeof(GenericSubscriber).IsImplement(typeof(IGenericHandler<GenericType3>)).ShouldBeFalse(); It should_be_implement_same_type = () => typeof(ArgumentException).IsImplement<ArgumentException>().ShouldBeTrue(); It should_be_first_attribute = () => typeof(FakeCacheKey).FirstOrDefaultAttribute<FakeAttribute>().ShouldNotBeNull(); It should_be_has_attribute = () => typeof(FakeCacheKey).HasAttribute<FakeAttribute>().ShouldBeTrue(); It should_be_first_attributes_with_default = () => typeof(FakeCacheKey).FirstOrDefaultAttribute<CLSCompliantAttribute>().ShouldBeNull(); It should_be_get_member_name = () => { Expression<Func<ArgumentException, object>> expression = exception => exception.Message; expression.GetMemberName().ShouldEqual("Message"); }; It should_be_get_member_name_from_convert = () => { Expression<Func<ArgumentException, object>> expression = exception => exception.Data; expression.GetMemberName().ShouldEqual("Data"); }; It should_be_get_member_name_complex_object = () => { Expression<Func<ArgumentException, object>> expression = exception => exception.InnerException.Data; expression.GetMemberName().ShouldEqual("InnerException.Data"); }; It should_be_get_member_name_complex_object_one_char = () => { Expression<Func<ArgumentException, object>> expression = r => r.InnerException.Data; expression.GetMemberName().ShouldEqual("InnerException.Data"); }; It should_be_get_member_name_with_complex_field = () => { Expression<Func<ArgumentException, object>> expression = exception => exception.InnerException.Message; expression.GetMemberName().ShouldEqual("InnerException.Message"); }; It should_be_set_value_to_field_with_camelcase = () => new FakeSetValueClass() .SetValue("privateField", Pleasure.Generator.TheSameString()) .GetPrivateFiled() .ShouldEqual(Pleasure.Generator.TheSameString()); It should_be_set_value_to_readonly_field = () => new FakeSetValueClass() .SetValue("readOnlyPrivateField", Pleasure.Generator.TheSameString()) .GetReadOnlyPrivateFiled() .ShouldEqual(Pleasure.Generator.TheSameString()); It should_be_set_value_to_property = () => new FakeSetValueClass() .SetValue("ProtectedProperty", Pleasure.Generator.TheSameString()) .GetProtected().ShouldEqual(Pleasure.Generator.TheSameString()); It should_be_set_field_with_wrong_name = () => Catch.Exception(() => new FakeSetValueClass().SetValue("NotFoundProperty", "Value")) .ShouldBeAssignableTo<InstanceNotFoundException>(); It should_be_try_get_value_with_wrong_name = () => new FakeSetValueClass() .TryGetValue("NotFoundField") .ShouldBeNull(); It should_be_try_get_value = () => new FakeSetValueClass() .SetPrivateField(Pleasure.Generator.TheSameString()) .TryGetValue("privateField") .ShouldEqual(Pleasure.Generator.TheSameString()); It should_be_try_get_value_static = () => new FakeSetValueClass() .TryGetValue("staticValue") .ShouldEqual("staticValue"); It should_be_try_get_value_int_private = () => new FakeSetValueClass().SetPrivateIntField(5) .TryGetValue<int>("privateIntField") .ShouldEqual(5); It should_be_try_get_value_int_nullable_private = () => new FakeSetValueClass().SetPrivateIntNullableField(null) .TryGetValue<int?>("privateIntNullableField") .ShouldBeNull(); It should_be_try_get_value_int_nullable_val_private = () => new FakeSetValueClass().SetPrivateIntNullableField(6) .TryGetValue<int?>("privateIntNullableField") .ShouldEqual(6); It should_be_try_get_value_class_nullable_private = () => new FakeSetValueClass().SetPrivateClassNullableField(null) .TryGetValue<FakeSetValueClass.FakeInnerClass>("classField") .ShouldBeNull(); It should_be_try_get_value_class_nullable_val_private = () => new FakeSetValueClass().SetPrivateClassNullableField(new FakeSetValueClass.FakeInnerClass() { Val = "asd"}) .TryGetValue<FakeSetValueClass>("classField") .ShouldEqualWeak(new FakeSetValueClass.FakeInnerClass() { Val = "asd" }); It should_be_is_typical_type = () => { DateTime.Now.GetType().IsTypicalType().ShouldBeTrue(); 5.GetType().IsTypicalType().ShouldBeTrue(); "5".GetType().IsTypicalType().ShouldBeTrue(); typeof(DayOfWeek).IsTypicalType().ShouldBeTrue(); new FakeSetValueClass().GetType().IsTypicalType().ShouldBeFalse(); }; } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using IxMilia.Dxf.Entities; using IxMilia.Dxf.Sections; using Xunit; namespace IxMilia.Dxf.Test { public abstract class AbstractDxfTests { protected static DxfFile Parse(string data) { using (var ms = new MemoryStream()) using (var writer = new StreamWriter(ms, new UTF8Encoding(false))) { writer.WriteLine(data.Trim()); writer.Flush(); ms.Seek(0, SeekOrigin.Begin); return DxfFile.Load(ms); } } protected static DxfFile Parse(params (int code, object value)[] codePairs) { var testBuffer = new TestCodePairBufferReader(codePairs); var file = DxfFile.LoadFromReader(testBuffer); return file; } protected static DxfFile Section(string sectionName, string data) { return Parse(string.Format(@" 0 SECTION 2 {0}{1} 0 ENDSEC 0 EOF ", sectionName, string.IsNullOrWhiteSpace(data) ? null : "\r\n" + data.Trim())); } protected static DxfFile Section(string sectionName, params (int code, object value)[] codePairs) { return Section(sectionName, (IEnumerable<(int code, object value)>)codePairs); } protected static DxfFile Section(string sectionName, IEnumerable<(int code, object value)> codePairs) { var preCodePairs = new[] { (0, (object)"SECTION"), (2, sectionName), }; var postCodePairs = new[] { (0, (object)"ENDSEC"), (0, "EOF"), }; var testBuffer = new TestCodePairBufferReader(preCodePairs.Concat(codePairs).Concat(postCodePairs)); var file = DxfFile.LoadFromReader(testBuffer); return file; } internal static DxfFile RoundTrip(DxfFile file) { var pairs = file.GetCodePairs(); var roundTrippedFile = DxfFile.LoadFromReader(new TestCodePairBufferReader(pairs)); return roundTrippedFile; } internal static DxfTextReader TextReaderFromLines(Encoding defaultTextEncoding, params string[] lines) { var ms = new MemoryStream(); var writer = new StreamWriter(ms); for (int i = 1; i < lines.Length; i++) { writer.WriteLine(lines[i]); } writer.Flush(); ms.Seek(0, SeekOrigin.Begin); var firstLine = lines[0]; return new DxfTextReader(ms, defaultTextEncoding, firstLine); } internal static DxfTextReader TextReaderFromLines(params string[] lines) { return TextReaderFromLines(Encoding.UTF8, lines); } internal static byte[] WriteToBinaryWriter(params (int code, object value)[] pairs) { using (var ms = new MemoryStream()) { var writer = new DxfWriter(ms, asText: false, version: DxfAcadVersion.R2004); writer.CreateInternalWriters(); foreach (var pair in pairs) { var properPair = new DxfCodePair(pair.code, pair.value); writer.WriteCodeValuePair(properPair); } ms.Seek(0, SeekOrigin.Begin); return ms.ToArray(); } } internal static string WriteToTextWriter(params (int code, object value)[] pairs) { using (var ms = new MemoryStream()) { var writer = new DxfWriter(ms, asText: true, version: DxfAcadVersion.R2004); writer.CreateInternalWriters(); foreach (var pair in pairs) { var properPair = new DxfCodePair(pair.code, pair.value); writer.WriteCodeValuePair(properPair); } writer.Flush(); ms.Seek(0, SeekOrigin.Begin); using (var reader = new StreamReader(ms)) { return reader.ReadToEnd(); } } } internal static bool AreCodePairsEquivalent(DxfCodePair a, DxfCodePair b) { if (a.Code == b.Code && DxfCodePair.ExpectedType(a.Code) == typeof(string) && (a.StringValue == "#" || b.StringValue == "#")) { // fake handle placeholder return true; } return a == b; } internal static int IndexOf(IEnumerable<DxfCodePair> superset, params (int code, object value)[] subset) { return IndexOf(superset.ToList(), subset.Select(cp => new DxfCodePair(cp.code, cp.value)).ToList()); } internal static int IndexOf(List<DxfCodePair> superset, List<DxfCodePair> subset) { var upperBound = superset.Count - subset.Count; for (int supersetIndex = 0; supersetIndex <= upperBound; supersetIndex++) { bool isMatch = true; for (int subsetIndex = 0; subsetIndex < subset.Count && isMatch; subsetIndex++) { var expected = subset[subsetIndex]; var actual = superset[supersetIndex + subsetIndex]; isMatch &= AreCodePairsEquivalent(expected, actual); } if (isMatch) { // found it return supersetIndex; } } return -1; } internal static void VerifyFileContains(DxfFile file, params (int code, object value)[] codePairs) { var expectedPairs = codePairs.Select(cp => new DxfCodePair(cp.code, cp.value)).ToList(); var actualPairs = file.GetCodePairs().ToList(); var index = IndexOf(actualPairs, expectedPairs); if (index < 0) { var expectedString = string.Join("\n", expectedPairs); var actualString = string.Join("\n", actualPairs); throw new Exception($"Unable to find expected pairs\n{expectedString}\n\nin\n\n{actualString}."); } } internal static void VerifyFileContains(DxfFile file, DxfSectionType sectionType, params (int code, object value)[] codePairs) { var expectedPairs = codePairs.Select(cp => new DxfCodePair(cp.code, cp.value)).ToList(); var sections = file.Sections.Where(s => s.Type == sectionType); var actualPairs = file.GetCodePairs(sections).ToList(); var index = IndexOf(actualPairs, expectedPairs); if (index < 0) { var expectedString = string.Join("\n", expectedPairs); var actualString = string.Join("\n", actualPairs); throw new Exception($"Unable to find expected pairs\n{expectedString}\n\nin\n\n{actualString}."); } } internal static void VerifyFileDoesNotContain(DxfFile file, params (int code, object value)[] codePairs) { var expectedPairs = codePairs.Select(cp => new DxfCodePair(cp.code, cp.value)).ToList(); var actualPairs = file.GetCodePairs().ToList(); var index = IndexOf(actualPairs, expectedPairs); if (index >= 0) { var expectedString = string.Join("\n", expectedPairs); var actualString = string.Join("\n", actualPairs); throw new Exception($"Expected not to find\n{expectedString}\n\nin\n\n{actualString}.\n\nItem was found at index {index}."); } } internal static void VerifyFileDoesNotContain(DxfFile file, DxfSectionType sectionType, params (int code, object value)[] codePairs) { var expectedPairs = codePairs.Select(cp => new DxfCodePair(cp.code, cp.value)).ToList(); var sections = file.Sections.Where(s => s.Type == sectionType); var actualPairs = file.GetCodePairs(sections).ToList(); var index = IndexOf(actualPairs, expectedPairs); if (index >= 0) { var expectedString = string.Join("\n", expectedPairs); var actualString = string.Join("\n", actualPairs); throw new Exception($"Expected not to find\n{expectedString}\n\nin\n\n{actualString}.\n\nItem was found at index {index}."); } } protected static void AssertArrayEqual<T>(T[] expected, T[] actual) { if (expected == null) { Assert.Null(actual); } Assert.NotNull(actual); Assert.Equal(expected.Length, actual.Length); for (int i = 0; i < expected.Length; i++) { Assert.Equal(expected[i], actual[i]); } } protected static bool IsListOfT(Type type) { return type.GetTypeInfo().IsGenericTypeDefinition && type.GenericTypeArguments.Length == 1 && type.Name == "List`1"; } protected static T SetAllPropertiesToDefault<T>(T item) { foreach (var property in item.GetType().GetTypeInfo().GetProperties().Where(p => p.GetSetMethod() != null && p.GetIndexParameters().Length == 0)) { var propertyType = property.PropertyType; var defaultValue = propertyType.GetTypeInfo().IsValueType ? Activator.CreateInstance(propertyType) : null; property.SetValue(item, defaultValue); } return item; } protected static void AssertEquivalent<T>(T expected, T actual) { foreach (var field in typeof(T).GetFields()) { var expectedField = field.GetValue(expected); var actualField = field.GetValue(actual); Assert.Equal(expectedField, actualField); } foreach (var property in typeof(T).GetProperties()) { var expectedProperty = property.GetValue(expected); var actualProperty = property.GetValue(actual); Assert.Equal(expectedProperty, actualProperty); } } protected static void AssertContains(IEnumerable<DxfCodePair> actualPairs, params (int code, object value)[] expectedPairs) { var index = IndexOf(actualPairs, expectedPairs); if (index < 0) { var expectedString = string.Join("\n", expectedPairs); var actualString = string.Join("\n", actualPairs); throw new Exception($"Unable to find expected pairs\n{expectedString}\n\nin\n\n{actualString}."); } } public static IEnumerable<Type> GetAllEntityTypes() { var assembly = typeof(DxfFile).Assembly; foreach (var type in assembly.GetTypes()) { if (ReaderWriterTests.IsEntityOrDerived(type) && !type.IsAbstract && type != typeof(DxfDimensionBase)) { yield return type; } } } public static IEnumerable<Type> GetAllObjectTypes() { var assembly = typeof(DxfFile).Assembly; foreach (var type in assembly.GetTypes()) { if (ReaderWriterTests.IsObjectOrDerived(type) && !type.IsAbstract) { yield return type; } } } } }
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 WebAPIConnectWithChrist.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; } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // 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 Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using Windows.UI.Input; using Windows.Storage.Streams; using System; using System.Linq; using System.Collections.Generic; using System.Windows.Input; namespace SDKTemplate { public sealed partial class Scenario1_EventAndMenuHookup : Page { private MainPage rootPage; private RadialController Controller; private int activeItemIndex; private List<RadialControllerMenuItem> menuItems = new List<RadialControllerMenuItem>(); private List<Slider> sliders = new List<Slider>(); private List<ToggleSwitch> toggles = new List<ToggleSwitch>(); public Scenario1_EventAndMenuHookup() { this.InitializeComponent(); InitializeController(); CreateMenuItems(); } protected override void OnNavigatedTo(NavigationEventArgs e) { rootPage = MainPage.Current; } protected override void OnNavigatedFrom(NavigationEventArgs e) { if (Controller != null) { Controller.Menu.Items.Clear(); } } private void InitializeController() { Controller = RadialController.CreateForCurrentView(); Controller.RotationResolutionInDegrees = 1; // Wire events Controller.RotationChanged += Controller_RotationChanged; Controller.ButtonClicked += Controller_ButtonClicked; Controller.ScreenContactStarted += Controller_ScreenContactStarted; Controller.ScreenContactContinued += Controller_ScreenContactContinued; Controller.ScreenContactEnded += Controller_ScreenContactEnded; Controller.ControlAcquired += Controller_ControlAcquired; Controller.ControlLost += Controller_ControlLost; } private void CreateMenuItems() { AddKnownIconItems(); AddCustomIconItems(); AddFontGlyphItems(); // Set the invoked callbacks for each menu item for (int i = 0; i < menuItems.Count; ++i) { RadialControllerMenuItem radialControllerItem = menuItems[i]; int index = i; radialControllerItem.Invoked += (sender, args) => { OnItemInvoked(index); }; } } private void AddKnownIconItems() { menuItems.Add(RadialControllerMenuItem.CreateFromKnownIcon("Item0", RadialControllerMenuKnownIcon.InkColor)); sliders.Add(slider0); toggles.Add(toggle0); menuItems.Add(RadialControllerMenuItem.CreateFromKnownIcon("Item1", RadialControllerMenuKnownIcon.NextPreviousTrack)); sliders.Add(slider1); toggles.Add(toggle1); } private void AddCustomIconItems() { menuItems.Add(RadialControllerMenuItem.CreateFromIcon("Item2", RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/Item2.png")))); sliders.Add(slider2); toggles.Add(toggle2); menuItems.Add(RadialControllerMenuItem.CreateFromIcon("Item3", RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/Item3.png")))); sliders.Add(slider3); toggles.Add(toggle3); } private void AddFontGlyphItems() { // Using system font menuItems.Add(RadialControllerMenuItem.CreateFromFontGlyph("Item4", "\x2764", "Segoe UI Emoji")); sliders.Add(slider4); toggles.Add(toggle4); // Using custom font menuItems.Add(RadialControllerMenuItem.CreateFromFontGlyph("Item5", "\ue102", "Symbols", new Uri("ms-appx:///Assets/Symbols.ttf"))); sliders.Add(slider5); toggles.Add(toggle5); } private void OnItemInvoked(int selectedItemIndex) { if (activeItemIndex != selectedItemIndex) { activeItemIndex = selectedItemIndex; PrintSelectedItem(); } } private void AddItem(object sender, RoutedEventArgs e) { RadialControllerMenuItem radialControllerMenuItem = GetRadialControllerMenuItemFromSender(sender); if (!Controller.Menu.Items.Contains(radialControllerMenuItem)) { Controller.Menu.Items.Add(radialControllerMenuItem); log.Text += "\n Added : " + radialControllerMenuItem.DisplayText; } } private void RemoveItem(object sender, RoutedEventArgs e) { RadialControllerMenuItem radialControllerMenuItem = GetRadialControllerMenuItemFromSender(sender); if (Controller.Menu.Items.Contains(radialControllerMenuItem)) { Controller.Menu.Items.Remove(radialControllerMenuItem); log.Text += "\n Removed : " + radialControllerMenuItem.DisplayText; } } private void SelectItem(object sender, RoutedEventArgs e) { RadialControllerMenuItem radialControllerMenuItem = GetRadialControllerMenuItemFromSender(sender); if (Controller.Menu.Items.Contains(radialControllerMenuItem)) { Controller.Menu.SelectMenuItem(radialControllerMenuItem); PrintSelectedItem(); } } private void SelectPreviouslySelectedItem(object sender, RoutedEventArgs e) { Controller.Menu.TrySelectPreviouslySelectedMenuItem(); PrintSelectedItem(); } private RadialControllerMenuItem GetRadialControllerMenuItemFromSender(object sender) { Button button = sender as Button; int index = Convert.ToInt32(button.CommandParameter); return menuItems[index]; } private void PrintSelectedItem(object sender, RoutedEventArgs e) { PrintSelectedItem(); } private void PrintSelectedItem() { RadialControllerMenuItem selectedMenuItem = Controller.Menu.GetSelectedMenuItem(); string itemName = string.Empty; if (selectedMenuItem == menuItems[activeItemIndex]) { itemName = selectedMenuItem.DisplayText; } else if (selectedMenuItem == null) { itemName = "System Item"; } if (itemName != string.Empty) { log.Text += "\n Selected : " + itemName; } } private void OnLogSizeChanged(object sender, object e) { logViewer.ChangeView(null, logViewer.ExtentHeight, null); } private void Controller_ControlAcquired(RadialController sender, RadialControllerControlAcquiredEventArgs args) { log.Text += "\n Control Acquired"; LogContactInfo(args.Contact); } private void Controller_ControlLost(RadialController sender, object args) { log.Text += "\n Control Lost"; } private void Controller_ScreenContactStarted(RadialController sender, RadialControllerScreenContactStartedEventArgs args) { log.Text += "\n Contact Started "; LogContactInfo(args.Contact); } private void Controller_ScreenContactContinued(RadialController sender, RadialControllerScreenContactContinuedEventArgs args) { log.Text += "\n Contact Continued "; LogContactInfo(args.Contact); } private void Controller_ScreenContactEnded(RadialController sender, object args) { log.Text += "\n Contact Ended"; } private void ToggleMenuSuppression(Object sender, RoutedEventArgs args) { RadialControllerConfiguration radialControllerConfig = RadialControllerConfiguration.GetForCurrentView(); if (MenuSuppressionToggleSwitch.IsOn) { radialControllerConfig.ActiveControllerWhenMenuIsSuppressed = Controller; } radialControllerConfig.IsMenuSuppressed = MenuSuppressionToggleSwitch.IsOn; } private void Controller_ButtonClicked(RadialController sender, RadialControllerButtonClickedEventArgs args) { log.Text += "\n Button Clicked "; LogContactInfo(args.Contact); ToggleSwitch toggle = toggles[activeItemIndex]; toggle.IsOn = !toggle.IsOn; } private void Controller_RotationChanged(RadialController sender, RadialControllerRotationChangedEventArgs args) { log.Text += "\n Rotation Changed Delta = " + args.RotationDeltaInDegrees; LogContactInfo(args.Contact); sliders[activeItemIndex].Value += args.RotationDeltaInDegrees; } private void LogContactInfo(RadialControllerScreenContact contact) { if (contact != null) { log.Text += "\n Bounds = " + contact.Bounds.ToString(); log.Text += "\n Position = " + contact.Position.ToString(); } } } }
// // FSpotTabbloExport.TabbloExport // // Authors: // Wojciech Dzierzanowski ([email protected]) // // (C) Copyright 2009 Wojciech Dzierzanowski // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Diagnostics; using System.Net; using System.Threading; using Mono.Tabblo; using Mono.Unix; using Hyena; using FSpot; using FSpot.Core; using FSpot.UI.Dialog; namespace FSpot.Exporters.Tabblo { public class TabbloExport : FSpot.Extensions.IExporter { private readonly TabbloExportModel model; private TabbloExportView main_dialog; private ThreadProgressDialog progress_dialog; private readonly Uploader uploader; private TraceListener debug_listener; private TotalUploadProgress upload_progress; // // Initialization // public TabbloExport () { model = new TabbloExportModel (); uploader = new Uploader (model); } public void Run (IBrowsableCollection photos) { if (null == photos || null == photos.Items) { throw new ArgumentNullException ("photos"); } main_dialog = new TabbloExportView (photos); InitBindings (); model.Deserialize (); model.PhotoCollection = photos; // Model deserialization triggers the various event // handlers, which can cause the default widget to lose // focus (it can be invalid, and hence disabled, for a // moment). main_dialog.ResetFocus (); main_dialog.Show (); } private void InitBindings () { Debug.Assert (null != model); Debug.Assert (null != main_dialog); main_dialog.Response += HandleResponse; // Account data model.UsernameChanged += HandleUsernameChanged; main_dialog.username_entry.Changed += HandleUsernameChanged; model.PasswordChanged += HandlePasswordChanged; main_dialog.password_entry.Changed += HandlePasswordChanged; // Tags model.AttachTagsChanged += HandleAttachTagsToggled; main_dialog.attach_tags_button.Toggled += HandleAttachTagsToggled; model.AttachedTagsChanged += HandleAttachedTagsChanged; main_dialog.attached_tags_select_button.Clicked += HandleSelectAttachedTagsClicked; model.RemoveTagsChanged += HandleRemoveTagsToggled; main_dialog.remove_tags_button.Toggled += HandleRemoveTagsToggled; model.RemovedTagsChanged += HandleRemovedTagsChanged; main_dialog.removed_tags_select_button.Clicked += HandleSelectRemovedTagsClicked; } // // Event handlers // private void HandleUsernameChanged (object sender, EventArgs args) { if (model == sender) { main_dialog.username_entry.Text = model.Username; OnAccountDataChanged (); } else { model.Username = main_dialog.username_entry.Text; } } private void HandlePasswordChanged (object sender, EventArgs args) { if (model == sender) { main_dialog.password_entry.Text = model.Password; OnAccountDataChanged (); } else { model.Password = main_dialog.password_entry.Text; } } private void OnAccountDataChanged () { main_dialog.Validated = model.Username.Length > 0 && model.Password.Length > 0; } private void HandleAttachTagsToggled (object sender, EventArgs args) { if (model == sender) { if (model.AttachTags && 0 == model .AttachedTags.Length) { model.AttachedTags = SelectTags (); model.AttachTags = 0 < model.AttachedTags.Length; } main_dialog.attach_tags_button.Active = model.AttachTags; main_dialog.attached_tags_select_button .Sensitive = model.AttachTags; } else { model.AttachTags = main_dialog.attach_tags_button.Active; } } private void HandleRemoveTagsToggled (object sender, EventArgs args) { if (model == sender) { if (model.RemoveTags && 0 == model .RemovedTags.Length) { model.RemovedTags = SelectTags (); model.RemoveTags = 0 < model.RemovedTags.Length; } main_dialog.remove_tags_button.Active = model.RemoveTags; main_dialog.removed_tags_select_button .Sensitive = model.RemoveTags; } else { model.RemoveTags = main_dialog.remove_tags_button.Active; } } private void HandleSelectAttachedTagsClicked (object sender, EventArgs args) { Debug.Assert (model != sender); FSpot.Core.Tag [] tags = SelectTags (); if (null != tags) { model.AttachedTags = tags; } } private void HandleSelectRemovedTagsClicked (object sender, EventArgs args) { Debug.Assert (model != sender); FSpot.Core.Tag [] tags = SelectTags (); if (null != tags) { model.RemovedTags = tags; } } private void HandleAttachedTagsChanged (object sender, EventArgs args) { Debug.Assert (model == sender); main_dialog.attached_tags_view.Tags = model.AttachedTags; main_dialog.attach_tags_button.Active = model.AttachTags && model.AttachedTags.Length > 0; } private void HandleRemovedTagsChanged (object sender, EventArgs args) { Debug.Assert (model == sender); main_dialog.removed_tags_view.Tags = model.RemovedTags; main_dialog.remove_tags_button.Active = model.RemoveTags && model.RemovedTags.Length > 0; } private FSpot.Core.Tag [] SelectTags () { TagStore tag_store = FSpot.App.Instance.Database.Tags; TagSelectionDialog tagDialog = new TagSelectionDialog (tag_store); FSpot.Core.Tag [] tags = tagDialog.Run (); tagDialog.Hide (); return tags; } private void HandleResponse (object sender, Gtk.ResponseArgs args) { main_dialog.Destroy (); if (Gtk.ResponseType.Ok != args.ResponseId) { Log.Information ("Tabblo export was canceled."); return; } model.Serialize (); Log.Information ("Starting Tabblo export"); Thread upload_thread = new Thread (new ThreadStart (Upload)); progress_dialog = new ThreadProgressDialog ( upload_thread, model.Photos.Length); progress_dialog.Start (); } // // Upload logic // private void Upload () { Debug.Assert (null != uploader); Picture [] pictures = GetPicturesForUpload (); Debug.Assert (pictures.Length == model.Photos.Length); OnUploadStarted (pictures); try { for (int i = 0; i < pictures.Length; ++i) { uploader.Upload (pictures [i]); OnPhotoUploaded (model.Photos [i]); } progress_dialog.Message = Catalog.GetString ( "Done sending photos"); progress_dialog.ProgressText = Catalog .GetString ("Upload complete"); progress_dialog.Fraction = 1; progress_dialog.ButtonLabel = Gtk.Stock.Ok; } catch (TabbloException e) { progress_dialog.Message = Catalog.GetString ( "Error uploading to Tabblo: ") + e.Message; progress_dialog.ProgressText = Catalog.GetString ("Error"); // FIXME: Retry logic? // progressDialog.PerformRetrySkip (); Log.Exception (e); } finally { OnUploadFinished (); } } private void OnUploadStarted (Picture [] pictures) { Debug.Assert (null != pictures); Debug.Assert (null != uploader); Debug.Assert (null != progress_dialog); // Initialize the debug output listener. // `Mono.Tabblo' uses the standard // `System.Diagnostics.Debug' facilities for debug // output only. debug_listener = new FSpotTraceListener (); Debug.Listeners.Add (debug_listener); // Initialize the progress handler. upload_progress = new FSpotUploadProgress ( pictures, progress_dialog); uploader.ProgressChanged += upload_progress.HandleProgress; // Set up the certificate policy. ServicePointManager.CertificatePolicy = new UserDecisionCertificatePolicy (); } private void OnUploadFinished () { Debug.Assert (null != uploader); Debug.Assert (null != debug_listener); Debug.Assert (null != upload_progress); uploader.ProgressChanged -= upload_progress.HandleProgress; Debug.Listeners.Remove (debug_listener); } private void OnPhotoUploaded (IPhoto item) { Debug.Assert (null != item); if (!model.AttachTags && !model.RemoveTags) { return; } PhotoStore photo_store = FSpot.App.Instance.Database.Photos; FSpot.Photo photo = photo_store.GetByUri ( item.DefaultVersion.Uri); Debug.Assert (null != photo); if (null == photo) { return; } if (model.AttachTags) { photo.AddTag (model.AttachedTags); } if (model.RemoveTags) { photo.RemoveTag (model.RemovedTags); } photo_store.Commit (photo); } private Picture [] GetPicturesForUpload () { Picture [] pictures = new Picture [model.Photos.Length]; IPhoto [] items = model.Photos; for (int i = 0; i < pictures.Length; ++i) { string mime_type = GLib.FileFactory.NewForUri (items [i].DefaultVersion.Uri). QueryInfo ("standard::content-type", GLib.FileQueryInfoFlags.None, null).ContentType; pictures [i] = new Picture (items [i].Name, new Uri (items [i].DefaultVersion.Uri.AbsoluteUri), mime_type, model.Privacy); } return pictures; } } }
/********************************************************************++ * Copyright (c) Microsoft Corporation. All rights reserved. * --********************************************************************/ using System.IO; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading; using System.Runtime.Serialization; using System.Management.Automation.Host; using System.Management.Automation.Remoting; using Microsoft.PowerShell.Commands; using System.Management.Automation.Internal; using System.Diagnostics.CodeAnalysis; // for fxcop using Dbg = System.Management.Automation.Diagnostics; using System.Diagnostics; using System.Linq; using Microsoft.PowerShell.Telemetry.Internal; #if CORECLR // Use stubs for SerializableAttribute and ISerializable related types using Microsoft.PowerShell.CoreClr.Stubs; #endif #pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings namespace System.Management.Automation.Runspaces { /// <summary> /// Runspace class for local runspace /// </summary> internal sealed partial class LocalRunspace : RunspaceBase { #region constructors /// <summary> /// Construct an instance of an Runspace using a custom implementation /// of PSHost. /// </summary> /// <param name="host"> /// The explicit PSHost implementation /// </param> /// <param name="runspaceConfig"> /// configuration information for this minshell. /// </param> [SuppressMessage("Microsoft.Maintainability", "CA1505:AvoidUnmaintainableCode")] internal LocalRunspace(PSHost host, RunspaceConfiguration runspaceConfig) : base(host, runspaceConfig) { } /// <summary> /// Construct an instance of an Runspace using a custom implementation /// of PSHost. /// </summary> /// <param name="host"> /// The explicit PSHost implementation /// </param> /// <param name="initialSessionState"> /// configuration information for this minshell. /// </param> /// <param name="suppressClone"> /// If true, don't make a copy of the initial session state object /// </param> [SuppressMessage("Microsoft.Maintainability", "CA1505:AvoidUnmaintainableCode")] internal LocalRunspace(PSHost host, InitialSessionState initialSessionState, bool suppressClone) : base(host, initialSessionState, suppressClone) { } /// <summary> /// Construct an instance of an Runspace using a custom implementation /// of PSHost. /// </summary> /// <param name="host"> /// The explicit PSHost implementation /// </param> /// <param name="initialSessionState"> /// configuration information for this minshell. /// </param> [SuppressMessage("Microsoft.Maintainability", "CA1505:AvoidUnmaintainableCode")] internal LocalRunspace(PSHost host, InitialSessionState initialSessionState) : base(host, initialSessionState) { } #endregion constructors /// <summary> /// Private data to be used by applications built on top of PowerShell. /// /// Local runspace pool is created with application private data set to an empty <see cref="PSPrimitiveDictionary"/>. /// /// Runspaces that are part of a <see cref="RunspacePool"/> inherit application private data from the pool. /// </summary> public override PSPrimitiveDictionary GetApplicationPrivateData() { // if we didn't get applicationPrivateData from a runspace pool, // then we create a new one if (_applicationPrivateData == null) { lock (this.SyncRoot) { if (_applicationPrivateData == null) { _applicationPrivateData = new PSPrimitiveDictionary(); } } } return _applicationPrivateData; } /// <summary> /// A method that runspace pools can use to propagate application private data into runspaces /// </summary> /// <param name="applicationPrivateData"></param> internal override void SetApplicationPrivateData(PSPrimitiveDictionary applicationPrivateData) { _applicationPrivateData = applicationPrivateData; } private PSPrimitiveDictionary _applicationPrivateData; /// <summary> /// Gets the event manager /// </summary> public override PSEventManager Events { get { System.Management.Automation.ExecutionContext context = this.GetExecutionContext; if (context == null) { return null; } return context.Events; } } /// <summary> /// This property determines whether a new thread is create for each invocation /// </summary> /// <remarks> /// Any updates to the value of this property must be done before the Runspace is opened /// </remarks> /// <exception cref="InvalidRunspaceStateException"> /// An attempt to change this property was made after opening the Runspace /// </exception> /// <exception cref="InvalidOperationException"> /// The thread options cannot be changed to the requested value /// </exception> public override PSThreadOptions ThreadOptions { get { return _createThreadOptions; } set { lock (this.SyncRoot) { if (value != _createThreadOptions) { if (this.RunspaceStateInfo.State != RunspaceState.BeforeOpen) { #if CORECLR // No ApartmentState.STA Support In CoreCLR bool allowed = value == PSThreadOptions.ReuseThread; #else // if the runspace is already opened we only allow changing the options if // the apartment state is MTA and the new value is ReuseThread bool allowed = (this.ApartmentState == ApartmentState.MTA || this.ApartmentState == ApartmentState.Unknown) // Unknown is the same as MTA && value == PSThreadOptions.ReuseThread; #endif if (!allowed) { throw new InvalidOperationException(StringUtil.Format(RunspaceStrings.InvalidThreadOptionsChange)); } } _createThreadOptions = value; } } } } private PSThreadOptions _createThreadOptions = PSThreadOptions.Default; /// <summary> /// Resets the runspace state to allow for fast reuse. Not all of the runspace /// elements are reset. The goal is to minimize the chance of the user taking /// accidental dependencies on prior runspace state. /// </summary> public override void ResetRunspaceState() { PSInvalidOperationException invalidOperation = null; if (this.InitialSessionState == null) { invalidOperation = PSTraceSource.NewInvalidOperationException(); } else if (this.RunspaceState != Runspaces.RunspaceState.Opened) { invalidOperation = PSTraceSource.NewInvalidOperationException( RunspaceStrings.RunspaceNotInOpenedState, this.RunspaceState); } else if (this.RunspaceAvailability != Runspaces.RunspaceAvailability.Available) { invalidOperation = PSTraceSource.NewInvalidOperationException( RunspaceStrings.ConcurrentInvokeNotAllowed); } if (invalidOperation != null) { invalidOperation.Source = "ResetRunspaceState"; throw invalidOperation; } this.InitialSessionState.ResetRunspaceState(this.ExecutionContext); // Finally, reset history for this runspace. This needs to be done // last to so that changes to the default MaximumHistorySize will be picked up. _history = new History(this.ExecutionContext); } #region protected_methods /// <summary> /// Create a pipeline from a command string /// </summary> /// <param name="command">A valid command string. Can be null</param> /// <param name="addToHistory">if true command is added to history</param> /// <param name="isNested">True for nested pipeline</param> /// <returns> /// A pipeline pre-filled with Commands specified in commandString. /// </returns> protected override Pipeline CoreCreatePipeline(string command, bool addToHistory, bool isNested) { // NTRAID#Windows Out Of Band Releases-915851-2005/09/13 if (_disposed) { throw PSTraceSource.NewObjectDisposedException("runspace"); } return (Pipeline)new LocalPipeline(this, command, addToHistory, isNested); } #endregion protected_methods #region protected_properties /// <summary> /// Gets the execution context /// </summary> internal override System.Management.Automation.ExecutionContext GetExecutionContext { get { if (_engine == null) return null; else return _engine.Context; } } /// <summary> /// Returns true if the internal host is in a nested prompt /// </summary> internal override bool InNestedPrompt { get { System.Management.Automation.ExecutionContext context = this.GetExecutionContext; if (context == null) { return false; } return context.InternalHost.HostInNestedPrompt(); } } #endregion protected_properties #region internal_properties /// <summary> /// CommandFactory object for this runspace. /// </summary> internal CommandFactory CommandFactory { get { return _commandFactory; } } /// <summary> /// Gets history manager for this runspace /// </summary> /// <value></value> internal History History { get { return _history; } } /// <summary> /// Gets transcription data for this runspace /// </summary> /// <value></value> internal TranscriptionData TranscriptionData { get { return _transcriptionData; } } private TranscriptionData _transcriptionData = null; private JobRepository _jobRepository; /// <summary> /// List of jobs in this runspace /// </summary> internal JobRepository JobRepository { get { return _jobRepository; } } private JobManager _jobManager; /// <summary> /// Manager for JobSourceAdapters registered in this runspace. /// </summary> public override JobManager JobManager { get { return _jobManager; } } private RunspaceRepository _runspaceRepository; /// <summary> /// List of remote runspaces in this runspace /// </summary> internal RunspaceRepository RunspaceRepository { get { return _runspaceRepository; } } #endregion internal_properties #region Debugger /// <summary> /// Debugger /// </summary> public override Debugger Debugger { get { return InternalDebugger ?? base.Debugger; } } private static string s_debugPreferenceCachePath = Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "WindowsPowerShell"), "DebugPreference.clixml"); private static object s_debugPreferenceLockObject = new object(); /// <summary> /// DebugPreference serves as a property bag to keep /// track of all process specific debug preferences. /// </summary> public class DebugPreference { public string[] AppDomainNames; } /// <summary> /// CreateDebugPerfStruct is a helper method to populate DebugPreference /// </summary> /// <param name="AppDomainNames">App Domain Names</param> /// <returns>DebugPreference</returns> private static DebugPreference CreateDebugPreference(string[] AppDomainNames) { DebugPreference DebugPreference = new DebugPreference(); DebugPreference.AppDomainNames = AppDomainNames; return DebugPreference; } /// <summary> /// SetDebugPreference is a helper method used to enable and disable debug preference. /// </summary> /// <param name="processName">Process Name</param> /// <param name="appDomainName">App Domain Name</param> /// <param name="enable">Indicates if the debug preference has to be enabled or disabled.</param> internal static void SetDebugPreference(string processName, List<string> appDomainName, bool enable) { lock (s_debugPreferenceLockObject) { bool iscacheUpdated = false; Hashtable debugPreferenceCache = null; string[] appDomainNames = null; if (appDomainName != null) { appDomainNames = appDomainName.ToArray(); } if (!File.Exists(LocalRunspace.s_debugPreferenceCachePath)) { if (enable) { DebugPreference DebugPreference = CreateDebugPreference(appDomainNames); debugPreferenceCache = new Hashtable(); debugPreferenceCache.Add(processName, DebugPreference); iscacheUpdated = true; } } else { debugPreferenceCache = GetDebugPreferenceCache(null); if (debugPreferenceCache != null) { if (enable) { // Debug preference is set to enable. // If the cache does not contain the process name, then we just update the cache. if (!debugPreferenceCache.ContainsKey(processName)) { DebugPreference DebugPreference = CreateDebugPreference(appDomainNames); debugPreferenceCache.Add(processName, DebugPreference); iscacheUpdated = true; } else { // In this case, the cache contains the process name, hence we check the list of // app domains for which the debug preference is set to enable. DebugPreference processDebugPreference = GetProcessSpecificDebugPreference(debugPreferenceCache[processName]); // processDebugPreference would point to null if debug preference is enabled for all app domains. // If processDebugPreference is not null then it means that user has selected specific // appdomins for which the debug preference has to be enabled. if (processDebugPreference != null) { List<string> cachedAppDomainNames = null; if (processDebugPreference.AppDomainNames != null && processDebugPreference.AppDomainNames.Length > 0) { cachedAppDomainNames = new List<string>(processDebugPreference.AppDomainNames); foreach (string currentAppDomainName in appDomainName) { if (!cachedAppDomainNames.Contains(currentAppDomainName, StringComparer.OrdinalIgnoreCase)) { cachedAppDomainNames.Add(currentAppDomainName); iscacheUpdated = true; } } } if (iscacheUpdated) { DebugPreference DebugPreference = CreateDebugPreference(cachedAppDomainNames.ToArray()); debugPreferenceCache[processName] = DebugPreference; } } } } else { // Debug preference is set to disable. if (debugPreferenceCache.ContainsKey(processName)) { if (appDomainName == null) { debugPreferenceCache.Remove(processName); iscacheUpdated = true; } else { DebugPreference processDebugPreference = GetProcessSpecificDebugPreference(debugPreferenceCache[processName]); // processDebugPreference would point to null if debug preference is enabled for all app domains. // If processDebugPreference is not null then it means that user has selected specific // appdomins for which the debug preference has to be enabled. if (processDebugPreference != null) { List<string> cachedAppDomainNames = null; if (processDebugPreference.AppDomainNames != null && processDebugPreference.AppDomainNames.Length > 0) { cachedAppDomainNames = new List<string>(processDebugPreference.AppDomainNames); foreach (string currentAppDomainName in appDomainName) { if (cachedAppDomainNames.Contains(currentAppDomainName, StringComparer.OrdinalIgnoreCase)) { // remove requested appdomains debug preference details. cachedAppDomainNames.Remove(currentAppDomainName); iscacheUpdated = true; } } } if (iscacheUpdated) { DebugPreference DebugPreference = CreateDebugPreference(cachedAppDomainNames.ToArray()); debugPreferenceCache[processName] = DebugPreference; } } } } } } else { // For whatever reason, cache is corrupted. Hence override the cache content. if (enable) { debugPreferenceCache = new Hashtable(); DebugPreference DebugPreference = CreateDebugPreference(appDomainNames); debugPreferenceCache.Add(processName, DebugPreference); iscacheUpdated = true; } } } if (iscacheUpdated) { using (PowerShell ps = PowerShell.Create()) { ps.AddCommand("Export-Clixml").AddParameter("Path", LocalRunspace.s_debugPreferenceCachePath).AddParameter("InputObject", debugPreferenceCache); ps.Invoke(); } } } } /// <summary> /// GetDebugPreferenceCache is a helper method used to fetch /// the debug preference cache contents as a Hashtable. /// </summary> /// <param name="runspace">Runspace</param> /// <returns>If the Debug preference is persisted then a hashtable containing /// the debug preference is returned or else Null is returned.</returns> private static Hashtable GetDebugPreferenceCache(Runspace runspace) { Hashtable debugPreferenceCache = null; using (PowerShell ps = PowerShell.Create()) { if (runspace != null) { ps.Runspace = runspace; } ps.AddCommand("Import-Clixml").AddParameter("Path", LocalRunspace.s_debugPreferenceCachePath); Collection<PSObject> psObjects = ps.Invoke(); if (psObjects != null && psObjects.Count == 1) { debugPreferenceCache = psObjects[0].BaseObject as Hashtable; } } return debugPreferenceCache; } /// <summary> /// GetProcessSpecificDebugPreference is a helper method used to fetch persisted process specific debug preference. /// </summary> /// <param name="debugPreference"></param> /// <returns></returns> private static DebugPreference GetProcessSpecificDebugPreference(object debugPreference) { DebugPreference processDebugPreference = null; if (debugPreference != null) { PSObject debugPreferencePsObject = debugPreference as PSObject; if (debugPreferencePsObject != null) { processDebugPreference = LanguagePrimitives.ConvertTo<DebugPreference>(debugPreferencePsObject); } } return processDebugPreference; } #endregion /// <summary> /// Open the runspace /// </summary> /// <param name="syncCall"> /// parameter which control if Open is done synchronously or asynchronously /// </param> protected override void OpenHelper(bool syncCall) { if (syncCall) { //Open runspace synchronously DoOpenHelper(); } else { //Open runspace in another thread Thread asyncThread = new Thread(new ThreadStart(this.OpenThreadProc)); asyncThread.Start(); } } /// <summary> /// Start method for asynchronous open /// </summary> private void OpenThreadProc() { #pragma warning disable 56500 try { DoOpenHelper(); } catch (Exception exception) // ignore non-severe exceptions { CommandProcessorBase.CheckForSevereException(exception); //This exception is reported by raising RunspaceState //change event. } #pragma warning restore 56500 } /// <summary> /// Helper function used for opening a runspace /// </summary> private void DoOpenHelper() { // NTRAID#Windows Out Of Band Releases-915851-2005/09/13 if (_disposed) { throw PSTraceSource.NewObjectDisposedException("runspace"); } bool startLifeCycleEventWritten = false; s_runspaceInitTracer.WriteLine("begin open runspace"); try { _transcriptionData = new TranscriptionData(); if (InitialSessionState != null) { // All ISS-based configuration of the engine itself is done by AutomationEngine, // which calls InitialSessionState.Bind(). Anything that doesn't // require an active and open runspace should be done in ISS.Bind() _engine = new AutomationEngine(Host, null, InitialSessionState); } else { _engine = new AutomationEngine(Host, RunspaceConfiguration, null); } _engine.Context.CurrentRunspace = this; //Log engine for start of engine life MshLog.LogEngineLifecycleEvent(_engine.Context, EngineState.Available); startLifeCycleEventWritten = true; _commandFactory = new CommandFactory(_engine.Context); _history = new History(_engine.Context); _jobRepository = new JobRepository(); _jobManager = new JobManager(); _runspaceRepository = new RunspaceRepository(); s_runspaceInitTracer.WriteLine("initializing built-in aliases and variable information"); InitializeDefaults(); } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); s_runspaceInitTracer.WriteLine("Runspace open failed"); //Log engine health event LogEngineHealthEvent(exception); //Log engine for end of engine life if (startLifeCycleEventWritten) { Dbg.Assert(_engine.Context != null, "if startLifeCycleEventWritten is true, ExecutionContext must be present"); MshLog.LogEngineLifecycleEvent(_engine.Context, EngineState.Stopped); } //Open failed. Set the RunspaceState to Broken. SetRunspaceState(RunspaceState.Broken, exception); //Raise the event RaiseRunspaceStateEvents(); //Rethrow the exception. For asynchronous execution, //OpenThreadProc will catch it. For synchronous execution //caller of open will catch it. throw; } SetRunspaceState(RunspaceState.Opened); RunspaceOpening.Set(); //Raise the event RaiseRunspaceStateEvents(); s_runspaceInitTracer.WriteLine("runspace opened successfully"); // Now do initial state configuration that requires an active runspace if (InitialSessionState != null) { Exception initError = InitialSessionState.BindRunspace(this, s_runspaceInitTracer); if (initError != null) { // Log engine health event LogEngineHealthEvent(initError); // Log engine for end of engine life Debug.Assert(_engine.Context != null, "if startLifeCycleEventWritten is true, ExecutionContext must be present"); MshLog.LogEngineLifecycleEvent(_engine.Context, EngineState.Stopped); // Open failed. Set the RunspaceState to Broken. SetRunspaceState(RunspaceState.Broken, initError); // Raise the event RaiseRunspaceStateEvents(); // Throw the exception. For asynchronous execution, // OpenThreadProc will catch it. For synchronous execution // caller of open will catch it. throw initError; } } TelemetryAPI.ReportLocalSessionCreated(InitialSessionState, TranscriptionData); } /// <summary> /// Logs engine health event /// </summary> internal void LogEngineHealthEvent(Exception exception) { LogEngineHealthEvent( exception, Severity.Error, MshLog.EVENT_ID_CONFIGURATION_FAILURE, null); } /// <summary> /// Logs engine health event /// </summary> internal void LogEngineHealthEvent(Exception exception, Severity severity, int id, Dictionary<String, String> additionalInfo) { Dbg.Assert(exception != null, "Caller should validate the parameter"); LogContext logContext = new LogContext(); logContext.EngineVersion = Version.ToString(); logContext.HostId = Host.InstanceId.ToString(); logContext.HostName = Host.Name; logContext.HostVersion = Host.Version.ToString(); logContext.RunspaceId = InstanceId.ToString(); logContext.Severity = severity.ToString(); if (this.RunspaceConfiguration == null) { logContext.ShellId = Utils.DefaultPowerShellShellID; } else { logContext.ShellId = this.RunspaceConfiguration.ShellId; } MshLog.LogEngineHealthEvent( logContext, id, exception, additionalInfo); } /// <summary> /// Returns the thread that must be used to execute pipelines when CreateThreadOptions is ReuseThread /// </summary> /// <remarks> /// The pipeline calls this function after ensuring there is a single thread in the pipeline, so no locking is necessary /// </remarks> internal PipelineThread GetPipelineThread() { if (_pipelineThread == null) { #if CORECLR // No ApartmentState In CoreCLR _pipelineThread = new PipelineThread(); #else _pipelineThread = new PipelineThread(this.ApartmentState); #endif } return _pipelineThread; } private PipelineThread _pipelineThread = null; protected override void CloseHelper(bool syncCall) { if (syncCall) { //Do close synchronously DoCloseHelper(); } else { //Do close asynchronously Thread asyncThread = new Thread(new ThreadStart(this.CloseThreadProc)); asyncThread.Start(); } } /// <summary> /// Start method for asynchronous close /// </summary> private void CloseThreadProc() { #pragma warning disable 56500 try { DoCloseHelper(); } catch (Exception exception) // ignore non-severe exceptions { CommandProcessorBase.CheckForSevereException(exception); } #pragma warning restore 56500 } /// <summary> /// Close the runspace. /// </summary> /// <remarks> /// Attempts to create/execute pipelines after a call to /// close will fail. /// </remarks> private void DoCloseHelper() { // Stop any transcription if we're the last runspace to exit ExecutionContext executionContext = this.GetExecutionContext; if (executionContext != null) { Runspace hostRunspace = null; try { hostRunspace = executionContext.EngineHostInterface.Runspace; } catch (PSNotImplementedException) { // EngineHostInterface.Runspace throws PSNotImplementedException if there // is no interactive host. } if ((hostRunspace == null) || (this == hostRunspace)) { PSHostUserInterface host = executionContext.EngineHostInterface.UI; if (host != null) { host.StopAllTranscribing(); } } } // Generate the shutdown event if (Events != null) Events.GenerateEvent(PSEngineEvent.Exiting, null, new object[] { }, null, true, false); //Stop all running pipelines //Note:Do not perform the Cancel in lock. Reason is //Pipeline executes in separate thread, say threadP. //When pipeline is canceled/failed/completed in //Pipeline.ExecuteThreadProc it removes the pipeline //from the list of running pipelines. threadP will need //lock to remove the pipelines from the list of running pipelines //And we will deadlock. //Note:It is possible that one or more pipelines in the list //of active pipelines have completed before we call cancel. //That is fine since Pipeline.Cancel handles that( It ignores //the cancel request if pipeline execution has already //completed/failed/canceled. StopPipelines(); // Disconnect all disconnectable jobs in the job repository. StopOrDisconnectAllJobs(); // Close or disconnect all the remote runspaces available in the // runspace repository. CloseOrDisconnectAllRemoteRunspaces(() => { List<RemoteRunspace> runspaces = new List<RemoteRunspace>(); foreach (PSSession psSession in this.RunspaceRepository.Runspaces) { runspaces.Add(psSession.Runspace as RemoteRunspace); } return runspaces; }); //Notify Engine components that that runspace is closing. _engine.Context.RunspaceClosingNotification(); //Log engine lifecycle event. MshLog.LogEngineLifecycleEvent(_engine.Context, EngineState.Stopped); // Uninitialize the AMSI scan interface AmsiUtils.Uninitialize(); //All pipelines have been canceled. Close the runspace. _engine = null; _commandFactory = null; SetRunspaceState(RunspaceState.Closed); //Raise Event RaiseRunspaceStateEvents(); // Report telemetry if we have no more open runspaces. bool allRunspacesClosed = true; bool hostProvidesExitTelemetry = false; foreach (var r in Runspace.RunspaceList) { if (r.RunspaceStateInfo.State != RunspaceState.Closed) { allRunspacesClosed = false; break; } var localRunspace = r as LocalRunspace; if (localRunspace != null && localRunspace.Host is IHostProvidesTelemetryData) { hostProvidesExitTelemetry = true; break; } } if (allRunspacesClosed && !hostProvidesExitTelemetry) { TelemetryAPI.ReportExitTelemetry(null); } } /// <summary> /// Closes or disconnects all the remote runspaces passed in by the getRunspace /// function. If a remote runspace supports disconnect then it will be disconnected /// rather than closed. /// </summary> private void CloseOrDisconnectAllRemoteRunspaces(Func<List<RemoteRunspace>> getRunspaces) { List<RemoteRunspace> runspaces = getRunspaces(); if (runspaces.Count == 0) { return; } // whether the close of all remoterunspaces completed using (ManualResetEvent remoteRunspaceCloseCompleted = new ManualResetEvent(false)) { ThrottleManager throttleManager = new ThrottleManager(); throttleManager.ThrottleComplete += delegate (object sender, EventArgs e) { remoteRunspaceCloseCompleted.Set(); }; foreach (RemoteRunspace remoteRunspace in runspaces) { IThrottleOperation operation = new CloseOrDisconnectRunspaceOperationHelper(remoteRunspace); throttleManager.AddOperation(operation); } throttleManager.EndSubmitOperations(); remoteRunspaceCloseCompleted.WaitOne(); } } /// <summary> /// Disconnects all disconnectable jobs listed in the JobRepository. /// </summary> private void StopOrDisconnectAllJobs() { if (JobRepository.Jobs.Count == 0) { return; } List<RemoteRunspace> disconnectRunspaces = new List<RemoteRunspace>(); using (ManualResetEvent jobsStopCompleted = new ManualResetEvent(false)) { ThrottleManager throttleManager = new ThrottleManager(); throttleManager.ThrottleComplete += delegate (object sender, EventArgs e) { jobsStopCompleted.Set(); }; foreach (Job job in this.JobRepository.Jobs) { // Only stop or disconnect PowerShell jobs. if (job is PSRemotingJob == false) { continue; } if (!job.CanDisconnect) { // If the job cannot be disconnected then add it to // the stop list. throttleManager.AddOperation(new StopJobOperationHelper(job)); } else if (job.JobStateInfo.State == JobState.Running) { // Otherwise add disconnectable runspaces to list so that // they can be disconnected. IEnumerable<RemoteRunspace> jobRunspaces = job.GetRunspaces(); if (jobRunspaces != null) { disconnectRunspaces.AddRange(jobRunspaces); } } } // foreach job // Stop jobs. throttleManager.EndSubmitOperations(); jobsStopCompleted.WaitOne(); } // using jobsStopCompleted // Disconnect all disconnectable job runspaces found. CloseOrDisconnectAllRemoteRunspaces(() => { return disconnectRunspaces; }); } internal void ReleaseDebugger() { Debugger debugger = Debugger; if (debugger != null) { try { if (debugger.UnhandledBreakpointMode == UnhandledBreakpointProcessingMode.Wait) { // Sets the mode and also releases a held debug stop. debugger.UnhandledBreakpointMode = UnhandledBreakpointProcessingMode.Ignore; } } catch (PSNotImplementedException) { } } } #region SessionStateProxy protected override void DoSetVariable(string name, object value) { // NTRAID#Windows Out Of Band Releases-915851-2005/09/13 if (_disposed) { throw PSTraceSource.NewObjectDisposedException("runspace"); } _engine.Context.EngineSessionState.SetVariableValue(name, value, CommandOrigin.Internal); } protected override object DoGetVariable(string name) { // NTRAID#Windows Out Of Band Releases-915851-2005/09/13 if (_disposed) { throw PSTraceSource.NewObjectDisposedException("runspace"); } return _engine.Context.EngineSessionState.GetVariableValue(name); } protected override List<string> DoApplications { get { if (_disposed) { throw PSTraceSource.NewObjectDisposedException("runspace"); } return _engine.Context.EngineSessionState.Applications; } } protected override List<string> DoScripts { get { if (_disposed) { throw PSTraceSource.NewObjectDisposedException("runspace"); } return _engine.Context.EngineSessionState.Scripts; } } protected override DriveManagementIntrinsics DoDrive { get { if (_disposed) { throw PSTraceSource.NewObjectDisposedException("runspace"); } return _engine.Context.SessionState.Drive; } } protected override PSLanguageMode DoLanguageMode { get { if (_disposed) { throw PSTraceSource.NewObjectDisposedException("runspace"); } return _engine.Context.SessionState.LanguageMode; } set { if (_disposed) { throw PSTraceSource.NewObjectDisposedException("runspace"); } _engine.Context.SessionState.LanguageMode = value; } } protected override PSModuleInfo DoModule { get { if (_disposed) { throw PSTraceSource.NewObjectDisposedException("runspace"); } return _engine.Context.EngineSessionState.Module; } } protected override PathIntrinsics DoPath { get { if (_disposed) { throw PSTraceSource.NewObjectDisposedException("runspace"); } return _engine.Context.SessionState.Path; } } protected override CmdletProviderManagementIntrinsics DoProvider { get { if (_disposed) { throw PSTraceSource.NewObjectDisposedException("runspace"); } return _engine.Context.SessionState.Provider; } } protected override PSVariableIntrinsics DoPSVariable { get { if (_disposed) { throw PSTraceSource.NewObjectDisposedException("runspace"); } return _engine.Context.SessionState.PSVariable; } } protected override CommandInvocationIntrinsics DoInvokeCommand { get { if (_disposed) { throw PSTraceSource.NewObjectDisposedException("runspace"); } return _engine.Context.EngineIntrinsics.InvokeCommand; } } protected override ProviderIntrinsics DoInvokeProvider { get { if (_disposed) { throw PSTraceSource.NewObjectDisposedException("runspace"); } return _engine.Context.EngineIntrinsics.InvokeProvider; } } #endregion SessionStateProxy #region IDisposable Members /// <summary> /// Set to true when object is disposed /// </summary> private bool _disposed; /// <summary> /// Protected dispose which can be overridden by derived classes. /// </summary> /// <param name="disposing"></param> [SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "pipelineThread", Justification = "pipelineThread is disposed in Close()")] protected override void Dispose(bool disposing) { try { if (_disposed) { return; } lock (SyncRoot) { if (_disposed) { return; } _disposed = true; } if (disposing) { Close(); _engine = null; _history = null; _transcriptionData = null; _jobManager = null; _jobRepository = null; _runspaceRepository = null; if (RunspaceOpening != null) { RunspaceOpening.Dispose(); RunspaceOpening = null; } // Dispose the event manager if (this.ExecutionContext != null && this.ExecutionContext.Events != null) { try { this.ExecutionContext.Events.Dispose(); } catch (ObjectDisposedException) { ; } } } } finally { base.Dispose(disposing); } } /// <summary> /// Close the runspace /// </summary> public override void Close() { // Do not put cleanup activities in here, as they aren't // captured in CloseAsync() case. Instead, put them in // DoCloseHelper() base.Close(); // call base.Close() first to make it stop the pipeline if (_pipelineThread != null) { _pipelineThread.Close(); } } #endregion IDisposable Members #region private fields /// <summary> /// CommandFactory for creating Command objects /// </summary> private CommandFactory _commandFactory; /// <summary> /// AutomationEngine instance for this runspace /// </summary> private AutomationEngine _engine; internal AutomationEngine Engine { get { return _engine; } } /// <summary> /// Manages history for this runspace /// </summary> private History _history; [TraceSource("RunspaceInit", "Initialization code for Runspace")] private static PSTraceSource s_runspaceInitTracer = PSTraceSource.GetTracer("RunspaceInit", "Initialization code for Runspace", false); /// <summary> /// This ensures all processes have a server/listener. /// </summary> private static RemoteSessionNamedPipeServer s_IPCNamedPipeServer = RemoteSessionNamedPipeServer.IPCNamedPipeServer; #endregion private fields } #region Helper Class /// <summary> /// Helper class to stop a running job. /// </summary> internal sealed class StopJobOperationHelper : IThrottleOperation { private Job _job; /// <summary> /// Internal constructor /// </summary> /// <param name="job">Job object to stop.</param> internal StopJobOperationHelper(Job job) { _job = job; _job.StateChanged += new EventHandler<JobStateEventArgs>(HandleJobStateChanged); } /// <summary> /// Handles the Job state change event. /// </summary> /// <param name="sender">Originator of event, unused</param> /// <param name="eventArgs">Event arguments containing Job state.</param> private void HandleJobStateChanged(object sender, JobStateEventArgs eventArgs) { if (_job.IsFinishedState(_job.JobStateInfo.State)) { // We are done when the job is in the finished state. RaiseOperationCompleteEvent(); } } /// <summary> /// Override method to start the operation. /// </summary> internal override void StartOperation() { if (_job.IsFinishedState(_job.JobStateInfo.State)) { // The job is already in the finished state and so cannot be stopped. RaiseOperationCompleteEvent(); } else { // Otherwise stop the job. _job.StopJob(); } } /// <summary> /// Override method to stop the operation. Not used, stop operation must /// run to completion. /// </summary> internal override void StopOperation() { } /// <summary> /// Event to signal ThrottleManager when the operation is complete. /// </summary> internal override event EventHandler<OperationStateEventArgs> OperationComplete; /// <summary> /// Raise the OperationComplete event. /// </summary> private void RaiseOperationCompleteEvent() { _job.StateChanged -= new EventHandler<JobStateEventArgs>(HandleJobStateChanged); OperationStateEventArgs operationStateArgs = new OperationStateEventArgs(); operationStateArgs.OperationState = OperationState.StartComplete; operationStateArgs.BaseEvent = EventArgs.Empty; OperationComplete.SafeInvoke(this, operationStateArgs); } } /// <summary> /// Helper class to disconnect a runspace if the runspace supports disconnect /// semantics or otherwise close the runspace. /// </summary> internal sealed class CloseOrDisconnectRunspaceOperationHelper : IThrottleOperation { private RemoteRunspace _remoteRunspace; /// <summary> /// Internal constructor /// </summary> /// <param name="remoteRunspace"></param> internal CloseOrDisconnectRunspaceOperationHelper(RemoteRunspace remoteRunspace) { _remoteRunspace = remoteRunspace; _remoteRunspace.StateChanged += new EventHandler<RunspaceStateEventArgs>(HandleRunspaceStateChanged); } /// <summary> /// Handle the runspace state changed event /// </summary> /// <param name="sender">sender of this information, unused</param> /// <param name="eventArgs">runspace event args</param> private void HandleRunspaceStateChanged(object sender, RunspaceStateEventArgs eventArgs) { switch (eventArgs.RunspaceStateInfo.State) { case RunspaceState.BeforeOpen: case RunspaceState.Closing: case RunspaceState.Opened: case RunspaceState.Opening: case RunspaceState.Disconnecting: return; } //remoteRunspace.Dispose(); //remoteRunspace = null; RaiseOperationCompleteEvent(); } /// <summary> /// Start the operation of closing the runspace /// </summary> internal override void StartOperation() { if (_remoteRunspace.RunspaceStateInfo.State == RunspaceState.Closed || _remoteRunspace.RunspaceStateInfo.State == RunspaceState.Broken || _remoteRunspace.RunspaceStateInfo.State == RunspaceState.Disconnected) { // If the runspace is currently in a disconnected state then leave it // as is. // in this case, calling a close won't raise any events. Simply raise // the OperationCompleted event. After the if check, but before we // get to this point if the state was changed, then the StateChanged // event handler will anyway raise the event and so we are fine RaiseOperationCompleteEvent(); } else { // If the runspace supports disconnect semantics and is running a command, // then disconnect it rather than closing it. if (_remoteRunspace.CanDisconnect && _remoteRunspace.GetCurrentlyRunningPipeline() != null) { _remoteRunspace.DisconnectAsync(); } else { _remoteRunspace.CloseAsync(); } } } /// <summary> /// There is no scenario where we are going to cancel this close /// Hence this method is intentionally empty /// </summary> internal override void StopOperation() { } /// <summary> /// Event raised when the required operation is complete /// </summary> internal override event EventHandler<OperationStateEventArgs> OperationComplete; /// <summary> /// Raise the operation completed event /// </summary> private void RaiseOperationCompleteEvent() { _remoteRunspace.StateChanged -= new EventHandler<RunspaceStateEventArgs>(HandleRunspaceStateChanged); OperationStateEventArgs operationStateEventArgs = new OperationStateEventArgs(); operationStateEventArgs.OperationState = OperationState.StartComplete; operationStateEventArgs.BaseEvent = EventArgs.Empty; OperationComplete.SafeInvoke(this, operationStateEventArgs); } } /// <summary> /// Defines the exception thrown an error loading modules occurs while opening the runspace. It /// contains a list of all of the module errors that have occurred /// </summary> [Serializable] public class RunspaceOpenModuleLoadException : RuntimeException { #region ctor /// <summary> /// Initializes a new instance of ScriptBlockToPowerShellNotSupportedException /// with the message set to typeof(ScriptBlockToPowerShellNotSupportedException).FullName /// </summary> public RunspaceOpenModuleLoadException() : base(typeof(ScriptBlockToPowerShellNotSupportedException).FullName) { } /// <summary> /// Initializes a new instance of ScriptBlockToPowerShellNotSupportedException setting the message /// </summary> /// <param name="message">the exception's message</param> public RunspaceOpenModuleLoadException(string message) : base(message) { } /// <summary> /// Initializes a new instance of ScriptBlockToPowerShellNotSupportedException setting the message and innerException /// </summary> /// <param name="message">the exception's message</param> /// <param name="innerException">the exceptions's inner exception</param> public RunspaceOpenModuleLoadException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Recommended constructor for the class /// </summary> /// <param name="moduleName">The name of the module that cause the error</param> /// <param name="errors">The collection of errors that occurred during module processing</param> internal RunspaceOpenModuleLoadException( string moduleName, PSDataCollection<ErrorRecord> errors) : base(StringUtil.Format(RunspaceStrings.ErrorLoadingModulesOnRunspaceOpen, moduleName, (errors != null && errors.Count > 0 && errors[0] != null) ? errors[0].ToString() : String.Empty), null) { _errors = errors; this.SetErrorId("ErrorLoadingModulesOnRunspaceOpen"); this.SetErrorCategory(ErrorCategory.OpenError); } #endregion ctor /// <summary> /// The collection of error records generated while loading the modules. /// </summary> public PSDataCollection<ErrorRecord> ErrorRecords { get { return _errors; } } private PSDataCollection<ErrorRecord> _errors; #region Serialization /// <summary> /// Initializes a new instance of RunspaceOpenModuleLoadException with serialization parameters /// </summary> /// <param name="info"> serialization information </param> /// <param name="context"> streaming context </param> protected RunspaceOpenModuleLoadException(SerializationInfo info, StreamingContext context) : base(info, context) { } /// <summary> /// Populates a <see cref="SerializationInfo"/> with the /// data needed to serialize the RunspaceOpenModuleLoadException object. /// </summary> /// <param name="info">The <see cref="SerializationInfo"/> to populate with data.</param> /// <param name="context">The destination for this serialization.</param> public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new PSArgumentNullException("info"); } base.GetObjectData(info, context); } #endregion Serialization } // RunspaceOpenException #endregion Helper Class }
//----------------------------------------------------------------------- // <copyright> // Copyright (C) Ruslan Yakushev for the PHP Manager for IIS project. // // This file is subject to the terms and conditions of the Microsoft Public License (MS-PL). // See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL for more details. // </copyright> //----------------------------------------------------------------------- //#define VSDesigner using System; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using Microsoft.Web.Management.Client.Win32; using Web.Management.PHP.Config; namespace Web.Management.PHP.Setup { internal sealed class RecommendedConfigDialog : #if VSDesigner Form #else TaskForm #endif { private const int TagIssueDescription = 0; private const int TagIssueRecommendation = 1; private const int TagIssueIndex = 2; private const int TagSize = 3; private PHPModule _module; private ManagementPanel _contentPanel; private ListView _configIssuesListView; private ColumnHeader _nameHeader; private Label _configIssueLabel; private ColumnHeader _currentValueHeader; private ColumnHeader _recommendedValueHeader; private Label _recommendationLabel; private TextBox _recommendationTextBox; private Label _issueDescriptionLabel; private TextBox _issueDescriptionTextBox; private Label _formDescriptionLabel; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; public RecommendedConfigDialog(PHPModule module): base(module) { _module = module; InitializeComponent(); InitializeUI(); } protected override bool CanAccept { get { return (_configIssuesListView.CheckedItems.Count > 0); } } protected override bool CanShowHelp { get { return true; } } /// <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); } private static string GetResourceStringByName(string name) { string result = Resources.ResourceManager.GetString(name); if (result == null) { result = name; } return result; } private void InitializeComponent() { this._configIssuesListView = new System.Windows.Forms.ListView(); this._nameHeader = new System.Windows.Forms.ColumnHeader(); this._currentValueHeader = new System.Windows.Forms.ColumnHeader(); this._recommendedValueHeader = new System.Windows.Forms.ColumnHeader(); this._configIssueLabel = new System.Windows.Forms.Label(); this._recommendationLabel = new System.Windows.Forms.Label(); this._recommendationTextBox = new System.Windows.Forms.TextBox(); this._issueDescriptionLabel = new System.Windows.Forms.Label(); this._issueDescriptionTextBox = new System.Windows.Forms.TextBox(); this._formDescriptionLabel = new System.Windows.Forms.Label(); this.SuspendLayout(); // // _configIssuesListView // this._configIssuesListView.CheckBoxes = true; this._configIssuesListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this._nameHeader, this._currentValueHeader, this._recommendedValueHeader}); this._configIssuesListView.FullRowSelect = true; this._configIssuesListView.Location = new System.Drawing.Point(0, 74); this._configIssuesListView.MultiSelect = false; this._configIssuesListView.Name = "_configIssuesListView"; this._configIssuesListView.Size = new System.Drawing.Size(480, 130); this._configIssuesListView.TabIndex = 2; this._configIssuesListView.UseCompatibleStateImageBehavior = false; this._configIssuesListView.View = System.Windows.Forms.View.Details; this._configIssuesListView.ItemChecked += new System.Windows.Forms.ItemCheckedEventHandler(this.OnConfigIssuesListViewItemChecked); this._configIssuesListView.SelectedIndexChanged += new System.EventHandler(this.OnConfigIssuesListViewSelectedIndexChanged); // // _nameHeader // this._nameHeader.Text = Resources.RecommendConfigDialogSettingName; this._nameHeader.Width = 170; // // _currentValueHeader // this._currentValueHeader.Text = Resources.RecommendConfigDialogCurrentValue; this._currentValueHeader.Width = 150; // // _recommendedValueHeader // this._recommendedValueHeader.Text = Resources.RecommendConfigDialogRecommendedValue; this._recommendedValueHeader.Width = 150; // // _configIssueLabel // this._configIssueLabel.AutoSize = true; this._configIssueLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this._configIssueLabel.Location = new System.Drawing.Point(0, 58); this._configIssueLabel.Name = "_configIssueLabel"; this._configIssueLabel.Size = new System.Drawing.Size(180, 13); this._configIssueLabel.TabIndex = 1; this._configIssueLabel.Text = Resources.RecommendConfigDialogDetectedIssues; // // _recommendationLabel // this._recommendationLabel.AutoSize = true; this._recommendationLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this._recommendationLabel.Location = new System.Drawing.Point(0, 298); this._recommendationLabel.Name = "_recommendationLabel"; this._recommendationLabel.Size = new System.Drawing.Size(108, 13); this._recommendationLabel.TabIndex = 5; this._recommendationLabel.Text = Resources.RecommendConfigDialogRecommendation; // // _recommendationTextBox // this._recommendationTextBox.Location = new System.Drawing.Point(0, 314); this._recommendationTextBox.Multiline = true; this._recommendationTextBox.Name = "_recommendationTextBox"; this._recommendationTextBox.ReadOnly = true; this._recommendationTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this._recommendationTextBox.Size = new System.Drawing.Size(480, 60); this._recommendationTextBox.TabIndex = 6; // // _issueDescriptionLabel // this._issueDescriptionLabel.AutoSize = true; this._issueDescriptionLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this._issueDescriptionLabel.Location = new System.Drawing.Point(0, 225); this._issueDescriptionLabel.Name = "_issueDescriptionLabel"; this._issueDescriptionLabel.Size = new System.Drawing.Size(107, 13); this._issueDescriptionLabel.TabIndex = 3; this._issueDescriptionLabel.Text = Resources.RecommendConfigDialogIssueDescription; // // _issueDescriptionTextBox // this._issueDescriptionTextBox.Location = new System.Drawing.Point(0, 242); this._issueDescriptionTextBox.Multiline = true; this._issueDescriptionTextBox.Name = "_issueDescriptionTextBox"; this._issueDescriptionTextBox.ReadOnly = true; this._issueDescriptionTextBox.Size = new System.Drawing.Size(480, 41); this._issueDescriptionTextBox.TabIndex = 4; // // _formDescriptionLabel // this._formDescriptionLabel.Dock = System.Windows.Forms.DockStyle.Top; this._formDescriptionLabel.Location = new System.Drawing.Point(0, 0); this._formDescriptionLabel.Name = "_formDescriptionLabel"; this._formDescriptionLabel.Size = new System.Drawing.Size(504, 38); this._formDescriptionLabel.TabIndex = 0; this._formDescriptionLabel.Text = Resources.RecommendConfigDialogDescription; // // RecommendedConfigDialog // this.ClientSize = new System.Drawing.Size(504, 452); this.Controls.Add(this._formDescriptionLabel); this.Controls.Add(this._issueDescriptionTextBox); this.Controls.Add(this._issueDescriptionLabel); this.Controls.Add(this._recommendationTextBox); this.Controls.Add(this._recommendationLabel); this.Controls.Add(this._configIssueLabel); this.Controls.Add(this._configIssuesListView); this.Name = "RecommendedConfigDialog"; this.ResumeLayout(false); #if VSDesigner this.PerformLayout(); #endif } private void InitializeUI() { _contentPanel = new ManagementPanel(); _contentPanel.SuspendLayout(); this._contentPanel.Location = new System.Drawing.Point(0, 0); this._contentPanel.Dock = DockStyle.Fill; this._contentPanel.Controls.Add(_formDescriptionLabel); this._contentPanel.Controls.Add(_configIssueLabel); this._contentPanel.Controls.Add(_configIssuesListView); this._contentPanel.Controls.Add(_issueDescriptionLabel); this._contentPanel.Controls.Add(_issueDescriptionTextBox); this._contentPanel.Controls.Add(_recommendationLabel); this._contentPanel.Controls.Add(_recommendationTextBox); this._contentPanel.ResumeLayout(false); this._contentPanel.PerformLayout(); this.Text = Resources.RecommendConfigDialogTitle; SetContent(_contentPanel); UpdateTaskForm(); } protected override void OnAccept() { try { ArrayList selectedIssues = new ArrayList(); foreach (ListViewItem item in _configIssuesListView.CheckedItems) { object[] tag = item.Tag as object[]; selectedIssues.Add(tag[TagIssueIndex]); } _module.Proxy.ApplyRecommendedSettings(selectedIssues); DialogResult = DialogResult.OK; Close(); } catch (Exception ex) { DisplayErrorMessage(ex, Resources.ResourceManager); } } private void OnConfigIssuesDoWork(object sender, DoWorkEventArgs e) { e.Result = _module.Proxy.GetConfigIssues(); } private void OnConfigIssuesDoWorkCompleted(object sender, RunWorkerCompletedEventArgs e) { _configIssuesListView.BeginUpdate(); _configIssuesListView.SuspendLayout(); try { RemoteObjectCollection<PHPConfigIssue> configIssues = e.Result as RemoteObjectCollection<PHPConfigIssue>; if (configIssues != null) { foreach (PHPConfigIssue configIssue in configIssues) { ListViewItem listViewItem = new ListViewItem(configIssue.SettingName); if (String.IsNullOrEmpty(configIssue.CurrentValue)) { listViewItem.SubItems.Add(Resources.ConfigIssueNone); } else { listViewItem.SubItems.Add(configIssue.CurrentValue); } listViewItem.SubItems.Add(configIssue.RecommendedValue); listViewItem.Tag = new object[TagSize] { GetResourceStringByName(configIssue.IssueDescription), GetResourceStringByName(configIssue.Recommendation), configIssue.IssueIndex }; _configIssuesListView.Items.Add(listViewItem); } } } catch (Exception ex) { DisplayErrorMessage(ex, Resources.ResourceManager); } finally { _configIssuesListView.ResumeLayout(); _configIssuesListView.EndUpdate(); } if (_configIssuesListView.Items.Count > 0) { _configIssuesListView.Focus(); _configIssuesListView.Items[0].Selected = true; UpdateTaskForm(); } } private void OnConfigIssuesListViewItemChecked(object sender, ItemCheckedEventArgs e) { UpdateTaskForm(); } private void OnConfigIssuesListViewSelectedIndexChanged(object sender, EventArgs e) { if (_configIssuesListView.SelectedItems.Count > 0) { object[] tag = _configIssuesListView.SelectedItems[0].Tag as object[]; _issueDescriptionTextBox.Text = (string)tag[TagIssueDescription]; _recommendationTextBox.Text = (string)tag[TagIssueRecommendation]; } } protected override void OnLoad(EventArgs e) { base.OnLoad(e); StartAsyncTask(OnConfigIssuesDoWork, OnConfigIssuesDoWorkCompleted); } protected override void ShowHelp() { Helper.Browse(Globals.RecommendedConfigOnlineHelp); } } }
// ZlibStream.cs // ------------------------------------------------------------------ // // Copyright (c) 2009 Dino Chiesa and Microsoft Corporation. // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // // last saved (in emacs): // Time-stamp: <2011-July-31 14:53:33> // // ------------------------------------------------------------------ // // This module defines the ZlibStream class, which is similar in idea to // the System.IO.Compression.DeflateStream and // System.IO.Compression.GZipStream classes in the .NET BCL. // // ------------------------------------------------------------------ using System; using System.IO; namespace Ionic.Zlib { /// <summary> /// Represents a Zlib stream for compression or decompression. /// </summary> /// <remarks> /// /// <para> /// The ZlibStream is a <see /// href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator</see> on a <see /// cref="System.IO.Stream"/>. It adds ZLIB compression or decompression to any /// stream. /// </para> /// /// <para> Using this stream, applications can compress or decompress data via /// stream <c>Read()</c> and <c>Write()</c> operations. Either compresssion or /// decompression can occur through either reading or writing. The compression /// format used is ZLIB, which is documented in <see /// href="http://www.ietf.org/rfc/rfc1950.txt">IETF RFC 1950</see>, "ZLIB Compressed /// Data Format Specification version 3.3". This implementation of ZLIB always uses /// DEFLATE as the compression method. (see <see /// href="http://www.ietf.org/rfc/rfc1951.txt">IETF RFC 1951</see>, "DEFLATE /// Compressed Data Format Specification version 1.3.") </para> /// /// <para> /// The ZLIB format allows for varying compression methods, window sizes, and dictionaries. /// This implementation always uses the DEFLATE compression method, a preset dictionary, /// and 15 window bits by default. /// </para> /// /// <para> /// This class is similar to <see cref="DeflateStream"/>, except that it adds the /// RFC1950 header and trailer bytes to a compressed stream when compressing, or expects /// the RFC1950 header and trailer bytes when decompressing. It is also similar to the /// <see cref="GZipStream"/>. /// </para> /// </remarks> /// <seealso cref="DeflateStream" /> /// <seealso cref="GZipStream" /> public class ZlibStream : System.IO.Stream { internal ZlibBaseStream _baseStream; bool _disposed; /// <summary> /// Create a <c>ZlibStream</c> using the specified <c>CompressionMode</c>. /// </summary> /// <remarks> /// /// <para> /// When mode is <c>CompressionMode.Compress</c>, the <c>ZlibStream</c> /// will use the default compression level. The "captive" stream will be /// closed when the <c>ZlibStream</c> is closed. /// </para> /// /// </remarks> /// /// <example> /// This example uses a <c>ZlibStream</c> to compress a file, and writes the /// compressed data to another file. /// <code> /// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress)) /// { /// using (var raw = System.IO.File.Create(fileToCompress + ".zlib")) /// { /// using (Stream compressor = new ZlibStream(raw, CompressionMode.Compress)) /// { /// byte[] buffer = new byte[WORKING_BUFFER_SIZE]; /// int n; /// while ((n= input.Read(buffer, 0, buffer.Length)) != 0) /// { /// compressor.Write(buffer, 0, n); /// } /// } /// } /// } /// </code> /// <code lang="VB"> /// Using input As Stream = File.OpenRead(fileToCompress) /// Using raw As FileStream = File.Create(fileToCompress &amp; ".zlib") /// Using compressor As Stream = New ZlibStream(raw, CompressionMode.Compress) /// Dim buffer As Byte() = New Byte(4096) {} /// Dim n As Integer = -1 /// Do While (n &lt;&gt; 0) /// If (n &gt; 0) Then /// compressor.Write(buffer, 0, n) /// End If /// n = input.Read(buffer, 0, buffer.Length) /// Loop /// End Using /// End Using /// End Using /// </code> /// </example> /// /// <param name="stream">The stream which will be read or written.</param> /// <param name="mode">Indicates whether the ZlibStream will compress or decompress.</param> public ZlibStream(System.IO.Stream stream, CompressionMode mode) : this(stream, mode, CompressionLevel.Default, false) { } /// <summary> /// Create a <c>ZlibStream</c> using the specified <c>CompressionMode</c> and /// the specified <c>CompressionLevel</c>. /// </summary> /// /// <remarks> /// /// <para> /// When mode is <c>CompressionMode.Decompress</c>, the level parameter is ignored. /// The "captive" stream will be closed when the <c>ZlibStream</c> is closed. /// </para> /// /// </remarks> /// /// <example> /// This example uses a <c>ZlibStream</c> to compress data from a file, and writes the /// compressed data to another file. /// /// <code> /// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress)) /// { /// using (var raw = System.IO.File.Create(fileToCompress + ".zlib")) /// { /// using (Stream compressor = new ZlibStream(raw, /// CompressionMode.Compress, /// CompressionLevel.BestCompression)) /// { /// byte[] buffer = new byte[WORKING_BUFFER_SIZE]; /// int n; /// while ((n= input.Read(buffer, 0, buffer.Length)) != 0) /// { /// compressor.Write(buffer, 0, n); /// } /// } /// } /// } /// </code> /// /// <code lang="VB"> /// Using input As Stream = File.OpenRead(fileToCompress) /// Using raw As FileStream = File.Create(fileToCompress &amp; ".zlib") /// Using compressor As Stream = New ZlibStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression) /// Dim buffer As Byte() = New Byte(4096) {} /// Dim n As Integer = -1 /// Do While (n &lt;&gt; 0) /// If (n &gt; 0) Then /// compressor.Write(buffer, 0, n) /// End If /// n = input.Read(buffer, 0, buffer.Length) /// Loop /// End Using /// End Using /// End Using /// </code> /// </example> /// /// <param name="stream">The stream to be read or written while deflating or inflating.</param> /// <param name="mode">Indicates whether the ZlibStream will compress or decompress.</param> /// <param name="level">A tuning knob to trade speed for effectiveness.</param> public ZlibStream(System.IO.Stream stream, CompressionMode mode, CompressionLevel level) : this(stream, mode, level, false) { } /// <summary> /// Create a <c>ZlibStream</c> using the specified <c>CompressionMode</c>, and /// explicitly specify whether the captive stream should be left open after /// Deflation or Inflation. /// </summary> /// /// <remarks> /// /// <para> /// When mode is <c>CompressionMode.Compress</c>, the <c>ZlibStream</c> will use /// the default compression level. /// </para> /// /// <para> /// This constructor allows the application to request that the captive stream /// remain open after the deflation or inflation occurs. By default, after /// <c>Close()</c> is called on the stream, the captive stream is also /// closed. In some cases this is not desired, for example if the stream is a /// <see cref="System.IO.MemoryStream"/> that will be re-read after /// compression. Specify true for the <paramref name="leaveOpen"/> parameter to leave the stream /// open. /// </para> /// /// <para> /// See the other overloads of this constructor for example code. /// </para> /// /// </remarks> /// /// <param name="stream">The stream which will be read or written. This is called the /// "captive" stream in other places in this documentation.</param> /// <param name="mode">Indicates whether the ZlibStream will compress or decompress.</param> /// <param name="leaveOpen">true if the application would like the stream to remain /// open after inflation/deflation.</param> public ZlibStream(System.IO.Stream stream, CompressionMode mode, bool leaveOpen) : this(stream, mode, CompressionLevel.Default, leaveOpen) { } /// <summary> /// Create a <c>ZlibStream</c> using the specified <c>CompressionMode</c> /// and the specified <c>CompressionLevel</c>, and explicitly specify /// whether the stream should be left open after Deflation or Inflation. /// </summary> /// /// <remarks> /// /// <para> /// This constructor allows the application to request that the captive /// stream remain open after the deflation or inflation occurs. By /// default, after <c>Close()</c> is called on the stream, the captive /// stream is also closed. In some cases this is not desired, for example /// if the stream is a <see cref="System.IO.MemoryStream"/> that will be /// re-read after compression. Specify true for the <paramref /// name="leaveOpen"/> parameter to leave the stream open. /// </para> /// /// <para> /// When mode is <c>CompressionMode.Decompress</c>, the level parameter is /// ignored. /// </para> /// /// </remarks> /// /// <example> /// /// This example shows how to use a ZlibStream to compress the data from a file, /// and store the result into another file. The filestream remains open to allow /// additional data to be written to it. /// /// <code> /// using (var output = System.IO.File.Create(fileToCompress + ".zlib")) /// { /// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress)) /// { /// using (Stream compressor = new ZlibStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, true)) /// { /// byte[] buffer = new byte[WORKING_BUFFER_SIZE]; /// int n; /// while ((n= input.Read(buffer, 0, buffer.Length)) != 0) /// { /// compressor.Write(buffer, 0, n); /// } /// } /// } /// // can write additional data to the output stream here /// } /// </code> /// <code lang="VB"> /// Using output As FileStream = File.Create(fileToCompress &amp; ".zlib") /// Using input As Stream = File.OpenRead(fileToCompress) /// Using compressor As Stream = New ZlibStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, True) /// Dim buffer As Byte() = New Byte(4096) {} /// Dim n As Integer = -1 /// Do While (n &lt;&gt; 0) /// If (n &gt; 0) Then /// compressor.Write(buffer, 0, n) /// End If /// n = input.Read(buffer, 0, buffer.Length) /// Loop /// End Using /// End Using /// ' can write additional data to the output stream here. /// End Using /// </code> /// </example> /// /// <param name="stream">The stream which will be read or written.</param> /// /// <param name="mode">Indicates whether the ZlibStream will compress or decompress.</param> /// /// <param name="leaveOpen"> /// true if the application would like the stream to remain open after /// inflation/deflation. /// </param> /// /// <param name="level"> /// A tuning knob to trade speed for effectiveness. This parameter is /// effective only when mode is <c>CompressionMode.Compress</c>. /// </param> public ZlibStream(System.IO.Stream stream, CompressionMode mode, CompressionLevel level, bool leaveOpen) { _baseStream = new ZlibBaseStream(stream, mode, level, ZlibStreamFlavor.ZLIB, leaveOpen); } #region Zlib properties /// <summary> /// This property sets the flush behavior on the stream. /// Sorry, though, not sure exactly how to describe all the various settings. /// </summary> virtual public FlushType FlushMode { get { return (this._baseStream._flushMode); } set { if (_disposed) throw new ObjectDisposedException("ZlibStream"); this._baseStream._flushMode = value; } } /// <summary> /// The size of the working buffer for the compression codec. /// </summary> /// /// <remarks> /// <para> /// The working buffer is used for all stream operations. The default size is /// 1024 bytes. The minimum size is 128 bytes. You may get better performance /// with a larger buffer. Then again, you might not. You would have to test /// it. /// </para> /// /// <para> /// Set this before the first call to <c>Read()</c> or <c>Write()</c> on the /// stream. If you try to set it afterwards, it will throw. /// </para> /// </remarks> public int BufferSize { get { return this._baseStream._bufferSize; } set { if (_disposed) throw new ObjectDisposedException("ZlibStream"); if (this._baseStream._workingBuffer != null) throw new ZlibException("The working buffer is already set."); if (value < ZlibConstants.WorkingBufferSizeMin) throw new ZlibException(String.Format("Don't be silly. {0} bytes?? Use a bigger buffer, at least {1}.", value, ZlibConstants.WorkingBufferSizeMin)); this._baseStream._bufferSize = value; } } /// <summary> Returns the total number of bytes input so far.</summary> virtual public long TotalIn { get { return this._baseStream._z.TotalBytesIn; } } /// <summary> Returns the total number of bytes output so far.</summary> virtual public long TotalOut { get { return this._baseStream._z.TotalBytesOut; } } #endregion #region System.IO.Stream methods /// <summary> /// Dispose the stream. /// </summary> /// <remarks> /// <para> /// This may or may not result in a <c>Close()</c> call on the captive /// stream. See the constructors that have a <c>leaveOpen</c> parameter /// for more information. /// </para> /// <para> /// This method may be invoked in two distinct scenarios. If disposing /// == true, the method has been called directly or indirectly by a /// user's code, for example via the public Dispose() method. In this /// case, both managed and unmanaged resources can be referenced and /// disposed. If disposing == false, the method has been called by the /// runtime from inside the object finalizer and this method should not /// reference other objects; in that case only unmanaged resources must /// be referenced or disposed. /// </para> /// </remarks> /// <param name="disposing"> /// indicates whether the Dispose method was invoked by user code. /// </param> protected override void Dispose(bool disposing) { try { if (!_disposed) { if (disposing && (this._baseStream != null)) this._baseStream.Close(); _disposed = true; } } finally { base.Dispose(disposing); } } /// <summary> /// Indicates whether the stream can be read. /// </summary> /// <remarks> /// The return value depends on whether the captive stream supports reading. /// </remarks> public override bool CanRead { get { if (_disposed) throw new ObjectDisposedException("ZlibStream"); return _baseStream._stream.CanRead; } } /// <summary> /// Indicates whether the stream supports Seek operations. /// </summary> /// <remarks> /// Always returns false. /// </remarks> public override bool CanSeek { get { return false; } } /// <summary> /// Indicates whether the stream can be written. /// </summary> /// <remarks> /// The return value depends on whether the captive stream supports writing. /// </remarks> public override bool CanWrite { get { if (_disposed) throw new ObjectDisposedException("ZlibStream"); return _baseStream._stream.CanWrite; } } /// <summary> /// Flush the stream. /// </summary> public override void Flush() { if (_disposed) throw new ObjectDisposedException("ZlibStream"); _baseStream.Flush(); } /// <summary> /// Reading this property always throws a <see cref="NotSupportedException"/>. /// </summary> public override long Length { get { throw new NotSupportedException(); } } /// <summary> /// The position of the stream pointer. /// </summary> /// /// <remarks> /// Setting this property always throws a <see /// cref="NotSupportedException"/>. Reading will return the total bytes /// written out, if used in writing, or the total bytes read in, if used in /// reading. The count may refer to compressed bytes or uncompressed bytes, /// depending on how you've used the stream. /// </remarks> public override long Position { get { if (this._baseStream._streamMode == Ionic.Zlib.ZlibBaseStream.StreamMode.Writer) return this._baseStream._z.TotalBytesOut; if (this._baseStream._streamMode == Ionic.Zlib.ZlibBaseStream.StreamMode.Reader) return this._baseStream._z.TotalBytesIn; return 0; } set { throw new NotSupportedException(); } } /// <summary> /// Read data from the stream. /// </summary> /// /// <remarks> /// /// <para> /// If you wish to use the <c>ZlibStream</c> to compress data while reading, /// you can create a <c>ZlibStream</c> with <c>CompressionMode.Compress</c>, /// providing an uncompressed data stream. Then call <c>Read()</c> on that /// <c>ZlibStream</c>, and the data read will be compressed. If you wish to /// use the <c>ZlibStream</c> to decompress data while reading, you can create /// a <c>ZlibStream</c> with <c>CompressionMode.Decompress</c>, providing a /// readable compressed data stream. Then call <c>Read()</c> on that /// <c>ZlibStream</c>, and the data will be decompressed as it is read. /// </para> /// /// <para> /// A <c>ZlibStream</c> can be used for <c>Read()</c> or <c>Write()</c>, but /// not both. /// </para> /// /// </remarks> /// /// <param name="buffer"> /// The buffer into which the read data should be placed.</param> /// /// <param name="offset"> /// the offset within that data array to put the first byte read.</param> /// /// <param name="count">the number of bytes to read.</param> /// /// <returns>the number of bytes read</returns> public override int Read(byte[] buffer, int offset, int count) { if (_disposed) throw new ObjectDisposedException("ZlibStream"); return _baseStream.Read(buffer, offset, count); } /// <summary> /// Calling this method always throws a <see cref="NotSupportedException"/>. /// </summary> /// <param name="offset"> /// The offset to seek to.... /// IF THIS METHOD ACTUALLY DID ANYTHING. /// </param> /// <param name="origin"> /// The reference specifying how to apply the offset.... IF /// THIS METHOD ACTUALLY DID ANYTHING. /// </param> /// /// <returns>nothing. This method always throws.</returns> public override long Seek(long offset, System.IO.SeekOrigin origin) { throw new NotSupportedException(); } /// <summary> /// Calling this method always throws a <see cref="NotSupportedException"/>. /// </summary> /// <param name="value"> /// The new value for the stream length.... IF /// THIS METHOD ACTUALLY DID ANYTHING. /// </param> public override void SetLength(long value) { throw new NotSupportedException(); } /// <summary> /// Write data to the stream. /// </summary> /// /// <remarks> /// /// <para> /// If you wish to use the <c>ZlibStream</c> to compress data while writing, /// you can create a <c>ZlibStream</c> with <c>CompressionMode.Compress</c>, /// and a writable output stream. Then call <c>Write()</c> on that /// <c>ZlibStream</c>, providing uncompressed data as input. The data sent to /// the output stream will be the compressed form of the data written. If you /// wish to use the <c>ZlibStream</c> to decompress data while writing, you /// can create a <c>ZlibStream</c> with <c>CompressionMode.Decompress</c>, and a /// writable output stream. Then call <c>Write()</c> on that stream, /// providing previously compressed data. The data sent to the output stream /// will be the decompressed form of the data written. /// </para> /// /// <para> /// A <c>ZlibStream</c> can be used for <c>Read()</c> or <c>Write()</c>, but not both. /// </para> /// </remarks> /// <param name="buffer">The buffer holding data to write to the stream.</param> /// <param name="offset">the offset within that data array to find the first byte to write.</param> /// <param name="count">the number of bytes to write.</param> public override void Write(byte[] buffer, int offset, int count) { if (_disposed) throw new ObjectDisposedException("ZlibStream"); _baseStream.Write(buffer, offset, count); } #endregion /// <summary> /// Compress a string into a byte array using ZLIB. /// </summary> /// /// <remarks> /// Uncompress it with <see cref="ZlibStream.UncompressString(byte[])"/>. /// </remarks> /// /// <seealso cref="ZlibStream.UncompressString(byte[])"/> /// <seealso cref="ZlibStream.CompressBuffer(byte[])"/> /// <seealso cref="GZipStream.CompressString(string)"/> /// /// <param name="s"> /// A string to compress. The string will first be encoded /// using UTF8, then compressed. /// </param> /// /// <returns>The string in compressed form</returns> public static byte[] CompressString(String s) { using (var ms = new MemoryStream()) { Stream compressor = new ZlibStream(ms, CompressionMode.Compress, CompressionLevel.BestCompression); ZlibBaseStream.CompressString(s, compressor); return ms.ToArray(); } } /// <summary> /// Compress a byte array into a new byte array using ZLIB. /// </summary> /// /// <remarks> /// Uncompress it with <see cref="ZlibStream.UncompressBuffer(byte[])"/>. /// </remarks> /// /// <seealso cref="ZlibStream.CompressString(string)"/> /// <seealso cref="ZlibStream.UncompressBuffer(byte[])"/> /// /// <param name="b"> /// A buffer to compress. /// </param> /// /// <returns>The data in compressed form</returns> public static byte[] CompressBuffer(byte[] b) { using (var ms = new MemoryStream()) { Stream compressor = new ZlibStream( ms, CompressionMode.Compress, CompressionLevel.BestCompression ); ZlibBaseStream.CompressBuffer(b, compressor); return ms.ToArray(); } } /// <summary> /// Uncompress a ZLIB-compressed byte array into a single string. /// </summary> /// /// <seealso cref="ZlibStream.CompressString(String)"/> /// <seealso cref="ZlibStream.UncompressBuffer(byte[])"/> /// /// <param name="compressed"> /// A buffer containing ZLIB-compressed data. /// </param> /// /// <returns>The uncompressed string</returns> public static String UncompressString(byte[] compressed) { using (var input = new MemoryStream(compressed)) { Stream decompressor = new ZlibStream(input, CompressionMode.Decompress); return ZlibBaseStream.UncompressString(compressed, decompressor); } } /// <summary> /// Uncompress a ZLIB-compressed byte array into a byte array. /// </summary> /// /// <seealso cref="ZlibStream.CompressBuffer(byte[])"/> /// <seealso cref="ZlibStream.UncompressString(byte[])"/> /// /// <param name="compressed"> /// A buffer containing ZLIB-compressed data. /// </param> /// /// <returns>The data in uncompressed form</returns> public static byte[] UncompressBuffer(byte[] compressed) { using (var input = new MemoryStream(compressed)) { Stream decompressor = new ZlibStream( input, CompressionMode.Decompress ); return ZlibBaseStream.UncompressBuffer(compressed, decompressor); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; namespace System { public partial class String { public bool Contains(string value) { return (IndexOf(value, StringComparison.Ordinal) >= 0); } // Returns the index of the first occurrence of value in the current instance. // The search starts at startIndex and runs thorough the next count characters. // public int IndexOf(char value) { return IndexOf(value, 0, this.Length); } public int IndexOf(char value, int startIndex) { return IndexOf(value, startIndex, this.Length - startIndex); } public unsafe int IndexOf(char value, int startIndex, int count) { if (startIndex < 0 || startIndex > Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); if (count < 0 || count > Length - startIndex) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); fixed (char* pChars = &_firstChar) { char* pCh = pChars + startIndex; while (count >= 4) { if (*pCh == value) goto ReturnIndex; if (*(pCh + 1) == value) goto ReturnIndex1; if (*(pCh + 2) == value) goto ReturnIndex2; if (*(pCh + 3) == value) goto ReturnIndex3; count -= 4; pCh += 4; } while (count > 0) { if (*pCh == value) goto ReturnIndex; count--; pCh++; } return -1; ReturnIndex3: pCh++; ReturnIndex2: pCh++; ReturnIndex1: pCh++; ReturnIndex: return (int)(pCh - pChars); } } // Returns the index of the first occurrence of any specified character in the current instance. // The search starts at startIndex and runs to startIndex + count - 1. // public int IndexOfAny(char[] anyOf) { return IndexOfAny(anyOf, 0, this.Length); } public int IndexOfAny(char[] anyOf, int startIndex) { return IndexOfAny(anyOf, startIndex, this.Length - startIndex); } public unsafe int IndexOfAny(char[] anyOf, int startIndex, int count) { if (anyOf == null) throw new ArgumentNullException(nameof(anyOf)); if (startIndex < 0 || startIndex > Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); if (count < 0 || count > Length - startIndex) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); // use probabilistic map, see InitializeProbabilisticMap uint* charMap = stackalloc uint[PROBABILISTICMAP_SIZE]; InitializeProbabilisticMap(charMap, anyOf); fixed (char* pChars = &_firstChar) { char* pCh = pChars + startIndex; for (int i = 0; i < count; i++) { char thisChar = *pCh++; if (ProbablyContains(charMap, thisChar)) if (ArrayContains(thisChar, anyOf) >= 0) return i + startIndex; } } return -1; } private const int PROBABILISTICMAP_BLOCK_INDEX_MASK = 0x7; private const int PROBABILISTICMAP_BLOCK_INDEX_SHIFT = 0x3; private const int PROBABILISTICMAP_SIZE = 0x8; // A probabilistic map is an optimization that is used in IndexOfAny/ // LastIndexOfAny methods. The idea is to create a bit map of the characters we // are searching for and use this map as a "cheap" check to decide if the // current character in the string exists in the array of input characters. // There are 256 bits in the map, with each character mapped to 2 bits. Every // character is divided into 2 bytes, and then every byte is mapped to 1 bit. // The character map is an array of 8 integers acting as map blocks. The 3 lsb // in each byte in the character is used to index into this map to get the // right block, the value of the remaining 5 msb are used as the bit position // inside this block. private static unsafe void InitializeProbabilisticMap(uint* charMap, char[] anyOf) { for (int i = 0; i < anyOf.Length; ++i) { uint hi, lo; char c = anyOf[i]; hi = ((uint)c >> 8) & 0xFF; lo = (uint)c & 0xFF; uint* value = &charMap[lo & PROBABILISTICMAP_BLOCK_INDEX_MASK]; *value |= (1u << (int)(lo >> PROBABILISTICMAP_BLOCK_INDEX_SHIFT)); value = &charMap[hi & PROBABILISTICMAP_BLOCK_INDEX_MASK]; *value |= (1u << (int)(hi >> PROBABILISTICMAP_BLOCK_INDEX_SHIFT)); } } // Use the probabilistic map to decide if the character value exists in the // map. When this method return false, we are certain the character doesn't // exist, however a true return means it *may* exist. private static unsafe bool ProbablyContains(uint* charMap, char searchValue) { uint lo, hi; lo = (uint)searchValue & 0xFF; uint value = charMap[lo & PROBABILISTICMAP_BLOCK_INDEX_MASK]; if ((value & (1u << (int)(lo >> PROBABILISTICMAP_BLOCK_INDEX_SHIFT))) != 0) { hi = ((uint)searchValue >> 8) & 0xFF; value = charMap[hi & PROBABILISTICMAP_BLOCK_INDEX_MASK]; return (value & (1u << (int)(hi >> PROBABILISTICMAP_BLOCK_INDEX_SHIFT))) != 0; } return false; } private static int ArrayContains(char searchChar, char[] anyOf) { for (int i = 0; i < anyOf.Length; i++) { if (anyOf[i] == searchChar) return i; } return -1; } public int IndexOf(String value) { return IndexOf(value, StringComparison.CurrentCulture); } public int IndexOf(String value, int startIndex, int count) { if (startIndex < 0 || startIndex > this.Length) { throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); } if (count < 0 || count > this.Length - startIndex) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); } return IndexOf(value, startIndex, count, StringComparison.CurrentCulture); } public int IndexOf(String value, int startIndex) { return IndexOf(value, startIndex, StringComparison.CurrentCulture); } public int IndexOf(String value, StringComparison comparisonType) { return IndexOf(value, 0, this.Length, comparisonType); } public int IndexOf(String value, int startIndex, StringComparison comparisonType) { return IndexOf(value, startIndex, this.Length - startIndex, comparisonType); } public int IndexOf(String value, int startIndex, int count, StringComparison comparisonType) { // Validate inputs if (value == null) throw new ArgumentNullException(nameof(value)); if (startIndex < 0 || startIndex > this.Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); if (count < 0 || startIndex > this.Length - count) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); switch (comparisonType) { case StringComparison.CurrentCulture: return FormatProvider.IndexOf(this, value, startIndex, count); case StringComparison.CurrentCultureIgnoreCase: return FormatProvider.IndexOfIgnoreCase(this, value, startIndex, count); case StringComparison.Ordinal: return FormatProvider.OrdinalIndexOf(this, value, startIndex, count); case StringComparison.OrdinalIgnoreCase: return FormatProvider.OrdinalIndexOfIgnoreCase(this, value, startIndex, count); default: throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } } // Returns the index of the last occurrence of a specified character in the current instance. // The search starts at startIndex and runs backwards to startIndex - count + 1. // The character at position startIndex is included in the search. startIndex is the larger // index within the string. // public int LastIndexOf(char value) { return LastIndexOf(value, this.Length - 1, this.Length); } public int LastIndexOf(char value, int startIndex) { return LastIndexOf(value, startIndex, startIndex + 1); } public unsafe int LastIndexOf(char value, int startIndex, int count) { if (Length == 0) return -1; if (startIndex < 0 || startIndex >= Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); if (count < 0 || count - 1 > startIndex) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); fixed (char* pChars = &_firstChar) { char* pCh = pChars + startIndex; //We search [startIndex..EndIndex] while (count >= 4) { if (*pCh == value) goto ReturnIndex; if (*(pCh - 1) == value) goto ReturnIndex1; if (*(pCh - 2) == value) goto ReturnIndex2; if (*(pCh - 3) == value) goto ReturnIndex3; count -= 4; pCh -= 4; } while (count > 0) { if (*pCh == value) goto ReturnIndex; count--; pCh--; } return -1; ReturnIndex3: pCh--; ReturnIndex2: pCh--; ReturnIndex1: pCh--; ReturnIndex: return (int)(pCh - pChars); } } // Returns the index of the last occurrence of any specified character in the current instance. // The search starts at startIndex and runs backwards to startIndex - count + 1. // The character at position startIndex is included in the search. startIndex is the larger // index within the string. // //ForceInline ... Jit can't recognize String.get_Length to determine that this is "fluff" public int LastIndexOfAny(char[] anyOf) { return LastIndexOfAny(anyOf, this.Length - 1, this.Length); } //ForceInline ... Jit can't recognize String.get_Length to determine that this is "fluff" public int LastIndexOfAny(char[] anyOf, int startIndex) { return LastIndexOfAny(anyOf, startIndex, startIndex + 1); } public unsafe int LastIndexOfAny(char[] anyOf, int startIndex, int count) { if (anyOf == null) throw new ArgumentNullException(nameof(anyOf)); if (Length == 0) return -1; if ((startIndex < 0) || (startIndex >= Length)) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); if ((count < 0) || ((count - 1) > startIndex)) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); } // use probabilistic map, see InitializeProbabilisticMap uint* charMap = stackalloc uint[PROBABILISTICMAP_SIZE]; InitializeProbabilisticMap(charMap, anyOf); fixed (char* pChars = &_firstChar) { char* pCh = pChars + startIndex; for (int i = 0; i < count; i++) { char thisChar = *pCh--; if (ProbablyContains(charMap, thisChar)) if (ArrayContains(thisChar, anyOf) >= 0) return startIndex - i; } } return -1; } // Returns the index of the last occurrence of any character in value in the current instance. // The search starts at startIndex and runs backwards to startIndex - count + 1. // The character at position startIndex is included in the search. startIndex is the larger // index within the string. // public int LastIndexOf(String value) { return LastIndexOf(value, this.Length - 1, this.Length, StringComparison.CurrentCulture); } public int LastIndexOf(String value, int startIndex) { return LastIndexOf(value, startIndex, startIndex + 1, StringComparison.CurrentCulture); } public int LastIndexOf(String value, int startIndex, int count) { if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); } return LastIndexOf(value, startIndex, count, StringComparison.CurrentCulture); } public int LastIndexOf(String value, StringComparison comparisonType) { return LastIndexOf(value, this.Length - 1, this.Length, comparisonType); } public int LastIndexOf(String value, int startIndex, StringComparison comparisonType) { return LastIndexOf(value, startIndex, startIndex + 1, comparisonType); } public int LastIndexOf(String value, int startIndex, int count, StringComparison comparisonType) { if (value == null) throw new ArgumentNullException(nameof(value)); // Special case for 0 length input strings if (this.Length == 0 && (startIndex == -1 || startIndex == 0)) return (value.Length == 0) ? 0 : -1; // Now after handling empty strings, make sure we're not out of range if (startIndex < 0 || startIndex > this.Length) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); // Make sure that we allow startIndex == this.Length if (startIndex == this.Length) { startIndex--; if (count > 0) count--; } // If we are looking for nothing, just return 0 if (value.Length == 0 && count >= 0 && startIndex - count + 1 >= 0) return startIndex; // 2nd half of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0. if (count < 0 || startIndex - count + 1 < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); switch (comparisonType) { case StringComparison.CurrentCulture: return FormatProvider.LastIndexOf(this, value, startIndex, count); case StringComparison.CurrentCultureIgnoreCase: return FormatProvider.LastIndexOfIgnoreCase(this, value, startIndex, count); case StringComparison.Ordinal: return FormatProvider.OrdinalLastIndexOf(this, value, startIndex, count); case StringComparison.OrdinalIgnoreCase: return FormatProvider.OrdinalLastIndexOfIgnoreCase(this, value, startIndex, count); default: throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } } } }
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 AnimatedSpice.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>(); } /// <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 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 get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and 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)) { 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="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <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.ActionDescriptor.ReturnType; 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, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [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 Tibia.Addresses; namespace Tibia { public partial class Version { public static void SetVersion861() { BattleList.Start = 0x634C38; BattleList.StepCreatures = 0xA8; BattleList.MaxCreatures = 250; BattleList.End = BattleList.Start + (BattleList.StepCreatures * BattleList.MaxCreatures); Client.StartTime = 0x7D5320; Client.XTeaKey = 0x78E51C; Client.SocketStruct = 0x78E4F0; Client.RecvPointer = 0x5B05E4; Client.SendPointer = 0x5B0610; Client.FrameRatePointer = 0x792604; Client.FrameRateCurrentOffset = 0x60; Client.FrameRateLimitOffset = 0x58; Client.MultiClient = 0x506BF4; Client.Status = 0x791ABC; Client.SafeMode = 0x78E944; Client.FollowMode = Client.SafeMode + 4; Client.AttackMode = Client.FollowMode + 4; Client.ActionState = 0x791B1C; Client.ActionStateFreezer = 0x518140; Client.LastMSGText = 0x789CF8; Client.LastMSGAuthor = Client.LastMSGText - 0x28; Client.StatusbarText = 0x7D5340; Client.StatusbarTime = Client.StatusbarText - 4; Client.ClickId = 0x791B5C; Client.ClickCount = Client.ClickId + 4; Client.ClickZ = Client.ClickId - 0x68; Client.SeeId = Client.ClickId + 12; Client.SeeCount = Client.SeeId + 4; Client.SeeZ = Client.SeeId - 0x68; Client.ClickContextMenuItemId = 0x791B68; Client.ClickContextMenuCreatureId = 0x791B6C; Client.LoginServerStart = 0x789458; Client.StepLoginServer = 112; Client.DistancePort = 100; Client.MaxLoginServers = 10; Client.RSA = 0x5B0980; Client.LoginCharList = 0x791A70; Client.LoginCharListLength = 0x791A74; Client.LoginSelectedChar = 0x791A6C; Client.GameWindowRectPointer = 0x640EBC; Client.GameWindowBar = 0x7D5330; Client.DatPointer = 0x78E53C; Client.EventTriggerPointer = 0x519C50; Client.DialogPointer = 0x644224; Client.DialogLeft = 0x14; Client.DialogTop = 0x18; Client.DialogWidth = 0x1C; Client.DialogHeight = 0x20; Client.DialogCaption = 0x50; Client.LastRcvPacket = 0x789CD0; Client.DecryptCall = 0x459C25; Client.LoginAccountNum = 0; Client.LoginPassword = 0x791A78; Client.LoginAccount = Client.LoginPassword + 32; Client.LoginPatch = 0; Client.LoginPatch2 = 0; Client.LoginPatchOrig = new byte[] { 0xE8, 0x0D, 0x1D, 0x09, 0x00 }; Client.LoginPatchOrig2 = new byte[] { 0xE8, 0xC8, 0x15, 0x09, 0x00 }; Client.ParserFunc = 0x459BF0; Client.GetNextPacketCall = 0x459C25; Client.RecvStream = 0x78E50C; Container.Start = 0x641970; Container.StepContainer = 492; Container.StepSlot = 12; Container.MaxContainers = 16; Container.MaxStack = 100; Container.DistanceIsOpen = 0; Container.DistanceId = 4; Container.DistanceName = 16; Container.DistanceVolume = 48; Container.DistanceAmount = 56; Container.DistanceItemId = 60; Container.DistanceItemCount = 64; Container.End = Container.Start + (Container.MaxContainers * Container.StepContainer); ContextMenus.AddContextMenuPtr = 0x450140; ContextMenus.OnClickContextMenuPtr = 0x44CD60; ContextMenus.OnClickContextMenuVf = 0x5B5668; ContextMenus.AddSetOutfitContextMenu = 0x45105C; ContextMenus.AddPartyActionContextMenu = 0x451489; ContextMenus.AddCopyNameContextMenu = 0x45152D; ContextMenus.AddTradeWithContextMenu = 0x450CE9; ContextMenus.AddLookContextMenu = 0x450B9F; Creature.DistanceId = 0; Creature.DistanceType = 3; Creature.DistanceName = 4; Creature.DistanceX = 36; Creature.DistanceY = 40; Creature.DistanceZ = 44; Creature.DistanceScreenOffsetHoriz = 48; Creature.DistanceScreenOffsetVert = 52; Creature.DistanceIsWalking = 76; Creature.DistanceWalkSpeed = 140; Creature.DistanceDirection = 80; Creature.DistanceIsVisible = 144; Creature.DistanceBlackSquare = 132; Creature.DistanceLight = 120; Creature.DistanceLightColor = 124; Creature.DistanceHPBar = 136; Creature.DistanceSkull = 148; Creature.DistanceParty = 152; Creature.DistanceWarIcon = 160; Creature.DistanceIsBlocking = 164; Creature.DistanceOutfit = 96; Creature.DistanceColorHead = 100; Creature.DistanceColorBody = 104; Creature.DistanceColorLegs = 108; Creature.DistanceColorFeet = 112; Creature.DistanceAddon = 116; DatItem.StepItems = 0x4C; DatItem.Width = 0; DatItem.Height = 4; DatItem.MaxSizeInPixels = 8; DatItem.Layers = 12; DatItem.PatternX = 16; DatItem.PatternY = 20; DatItem.PatternDepth = 24; DatItem.Phase = 28; DatItem.Sprite = 32; DatItem.Flags = 36; DatItem.CanLookAt = 0; DatItem.WalkSpeed = 40; DatItem.TextLimit = 44; DatItem.LightRadius = 48; DatItem.LightColor = 52; DatItem.ShiftX = 56; DatItem.ShiftY = 60; DatItem.WalkHeight = 64; DatItem.Automap = 68; DatItem.LensHelp = 72; DrawItem.DrawItemFunc = 0x4B0E70; DrawSkin.DrawSkinFunc = 0x4B4AC0; Hotkey.SendAutomaticallyStart = 0x78EB40; Hotkey.SendAutomaticallyStep = 0x01; Hotkey.TextStart = 0x78EB68; Hotkey.TextStep = 0x100; Hotkey.ObjectStart = 0x78EAB0; Hotkey.ObjectStep = 0x04; Hotkey.ObjectUseTypeStart = 0x78E990; Hotkey.ObjectUseTypeStep = 0x04; Hotkey.MaxHotkeys = 36; Map.MapPointer = 0x648D78; Map.StepTile = 168; Map.StepTileObject = 12; Map.DistanceTileObjectCount = 0; Map.DistanceTileObjects = 4; Map.DistanceObjectId = 0; Map.DistanceObjectData = 4; Map.DistanceObjectDataEx = 8; Map.MaxTileObjects = 10; Map.MaxX = 18; Map.MaxY = 14; Map.MaxZ = 8; Map.MaxTiles = 2016; Map.ZAxisDefault = 7; Map.NameSpy1 = 0x4ED739; Map.NameSpy2 = 0x4ED743; Map.NameSpy1Default = 19061; Map.NameSpy2Default = 16501; Map.LevelSpy1 = 0x4EF5EA; Map.LevelSpy2 = 0x4EF6EF; Map.LevelSpy3 = 0x4EF770; Map.LevelSpyPtr = 0x640EBC; Map.LevelSpyAdd1 = 28; Map.LevelSpyAdd2 = 0x2A88; Map.LevelSpyDefault = new byte[] { 0x89, 0x86, 0x88, 0x2A, 0x00, 0x00 }; Map.FullLightNop = 0x4E5ED9; Map.FullLightAdr = 0x4E5EDC; Map.FullLightNopDefault = new byte[] { 0x7E, 0x05 }; Map.FullLightNopEdited = new byte[] { 0x90, 0x90 }; Map.FullLightAdrDefault = 0x80; Map.FullLightAdrEdited = 0xFF; Player.Experience = 0x634BCC; Player.Flags = Player.Experience - 108; Player.Id = Player.Experience + 12; Player.Health = Player.Experience + 8; Player.HealthMax = Player.Experience + 4; Player.Level = Player.Experience - 4; Player.MagicLevel = Player.Experience - 8; Player.LevelPercent = Player.Experience - 12; Player.MagicLevelPercent = Player.Experience - 16; Player.Mana = Player.Experience - 20; Player.ManaMax = Player.Experience - 24; Player.Soul = Player.Experience - 28; Player.Stamina = Player.Experience - 32; Player.Capacity = Player.Experience - 36; Player.FistPercent = 0x634B64; Player.ClubPercent = Player.FistPercent + 4; Player.SwordPercent = Player.FistPercent + 8; Player.AxePercent = Player.FistPercent + 12; Player.DistancePercent = Player.FistPercent + 16; Player.ShieldingPercent = Player.FistPercent + 20; Player.FishingPercent = Player.FistPercent + 24; Player.Fist = Player.FistPercent + 28; Player.Club = Player.FistPercent + 32; Player.Sword = Player.FistPercent + 36; Player.Axe = Player.FistPercent + 40; Player.Distance = Player.FistPercent + 44; Player.Shielding = Player.FistPercent + 48; Player.Fishing = Player.FistPercent + 52; Player.SlotHead = 0x6418F8; Player.SlotNeck = Player.SlotHead + 12; Player.SlotBackpack = Player.SlotHead + 24; Player.SlotArmor = Player.SlotHead + 36; Player.SlotRight = Player.SlotHead + 48; Player.SlotLeft = Player.SlotHead + 60; Player.SlotLegs = Player.SlotHead + 72; Player.SlotFeet = Player.SlotHead + 84; Player.SlotRing = Player.SlotHead + 96; Player.SlotAmmo = Player.SlotHead + 108; Player.MaxSlots = 10; Player.DistanceSlotCount = 4; Player.CurrentTileToGo = 0x634BE0; Player.TilesToGo = 0x634BE4; Player.GoToX = Player.Experience + 80; Player.GoToY = Player.GoToX - 4; Player.GoToZ = Player.GoToX - 8; Player.RedSquare = 0x634BA4; Player.GreenSquare = Player.RedSquare - 4; Player.WhiteSquare = Player.GreenSquare - 8; Player.AccessN = 0; Player.AccessS = 0; Player.TargetId = Player.RedSquare; Player.TargetBattlelistId = Player.TargetId - 8; Player.TargetBattlelistType = Player.TargetId - 5; Player.TargetType = Player.TargetId + 3; Player.Z = 0x644260; Player.AttackCount = 0x632780; Player.FollowCount = Player.AttackCount + 0x20; TextDisplay.PrintName = 0x4F0753; TextDisplay.PrintFPS = 0x457C28; TextDisplay.ShowFPS = 0x63287C; TextDisplay.PrintTextFunc = 0x4B02B0; TextDisplay.NopFPS = 0x457B64; Vip.Start = 0x6328F8; Vip.StepPlayers = 0x2C; Vip.MaxPlayers = 200; Vip.DistanceId = 0; Vip.DistanceName = 4; Vip.DistanceStatus = 34; Vip.DistanceIcon = 40; Vip.End = Vip.Start + (Vip.StepPlayers * Vip.MaxPlayers); } } }
// Copyright 2014 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Original code by Nora // http://stereoarts.jp // // Retrieved from: // https://developer.oculusvr.com/forums/viewtopic.php?f=37&t=844#p28982 // // Modified by Google: // Combined the 6 separate meshes into a single mesh with submeshes. using UnityEngine; /// @ingroup LegacyScripts /// This script builds a stereo correct version of the skybox. /// /// Unity 4's built-in skybox backgrounds do not work correctly for stereo rendering. /// Since the same exact image is rendered to each eye, the background has zero /// parallax. Given the optics of Cardboard, this yields an effective stereo depth /// that is likely right in the middle, or worse, front of the scene. The results /// in a visually painful parallax clash with other objects in the scene. /// /// This script should be attached to the Camera which represents the primary /// viewpoint of the player (such as _Main Camera_). At runtime it builds a mesh that /// will be textured with the camera's skybox material. The mesh is scaled up to /// just fit inside the far clipping plane, and kept centered on the camera's /// position. [RequireComponent(typeof(Camera))] public class SkyboxMesh : MonoBehaviour { #if UNITY_5 void Awake() { Debug.Log("SkyboxMesh is not needed in Unity 5"); Component.Destroy(this); } #else /// The overall shape of the generated sky mesh. public enum Shape { Sphere, Cube, } /// The overall shape of the generated sky mesh. The mesh has 6 sides regardless /// of shape, one for each texture in the skybox material. The `shape` simply /// determines whether those sides are convex or flat. public Shape shape = Shape.Sphere; /// Controls the mesh resolution: Each side of the mesh is an NxN grid of /// triangles, where N = `segments`. public int segments = 32; /// The skybox mesh will be set to this layer. If you wish for only certain /// cameras to see the skybox mesh, choose a layer for it and make sure that /// only those cameras render that layer. public int layer = 0; private GameObject skybox; void Awake() { var sky = GetComponent<Skybox>(); Material skymat = sky != null ? sky.material : RenderSettings.skybox; if (skymat == null) { enabled = false; return; } skybox = new GameObject(skymat.name + "SkyMesh"); skybox.transform.parent = transform; skybox.transform.localPosition = Vector3.zero; skybox.layer = layer; var filter = skybox.AddComponent<MeshFilter>(); filter.mesh = _CreateSkyboxMesh(); Material mat = new Material(Shader.Find("Cardboard/SkyboxMesh")); var render = skybox.AddComponent<MeshRenderer>(); render.sharedMaterials = new Material[] { new Material(mat) { mainTexture = skymat.GetTexture("_FrontTex") }, new Material(mat) { mainTexture = skymat.GetTexture("_LeftTex") }, new Material(mat) { mainTexture = skymat.GetTexture("_BackTex") }, new Material(mat) { mainTexture = skymat.GetTexture("_RightTex") }, new Material(mat) { mainTexture = skymat.GetTexture("_UpTex") }, new Material(mat) { mainTexture = skymat.GetTexture("_DownTex") } }; render.castShadows = false; render.receiveShadows = false; } void LateUpdate() { var camera = GetComponent<Camera>(); // Only visible if the owning camera needs it. skybox.GetComponent<Renderer>().enabled = camera.enabled && (camera.clearFlags == CameraClearFlags.Skybox); // Scale up to just fit inside the far clip plane. Vector3 scale = transform.lossyScale; float far = camera.farClipPlane * 0.95f; if (shape == Shape.Cube) { far /= Mathf.Sqrt(3); // Corners need to fit inside the frustum. } scale.x = far / scale.x; scale.y = far / scale.y; scale.z = far / scale.z; // Center on the camera. skybox.transform.localPosition = Vector3.zero; skybox.transform.localScale = scale; // Keep orientation fixed in the world. skybox.transform.rotation = Quaternion.identity; } Mesh _CreateMesh() { Mesh mesh = new Mesh(); int hvCount2 = this.segments + 1; int hvCount2Half = hvCount2 / 2; int numVertices = hvCount2 * hvCount2; int numTriangles = this.segments * this.segments * 6; Vector3[] vertices = new Vector3[numVertices]; Vector2[] uvs = new Vector2[numVertices]; int[] triangles = new int[numTriangles]; float scaleFactor = 2.0f / (float)this.segments; float uvFactor = 1.0f / (float)this.segments; if (this.segments <= 1 || this.shape == Shape.Cube) { float ty = 0.0f, py = -1.0f; int index = 0; for (int y = 0; y < hvCount2; ++y, ty += uvFactor, py += scaleFactor) { float tx = 0.0f, px = -1.0f; for (int x = 0; x < hvCount2; ++x, ++index, tx += uvFactor, px += scaleFactor) { vertices[index] = new Vector3(px, py, 1.0f); uvs[index] = new Vector2(tx, ty); } } } else { float ty = 0.0f, py = -1.0f; int index = 0, indexY = 0; for (int y = 0; y <= hvCount2Half; ++y, indexY += hvCount2, ty += uvFactor, py += scaleFactor) { float tx = 0.0f, px = -1.0f, py2 = py * py; int x = 0; for (; x <= hvCount2Half; ++x, ++index, tx += uvFactor, px += scaleFactor) { float d = Mathf.Sqrt(px * px + py2 + 1.0f); float theta = Mathf.Acos(1.0f / d); float phi = Mathf.Atan2(py, px); float sinTheta = Mathf.Sin(theta); vertices[index] = new Vector3( sinTheta * Mathf.Cos(phi), sinTheta * Mathf.Sin(phi), Mathf.Cos(theta)); uvs[index] = new Vector2(tx, ty); } int indexX = hvCount2Half - 1; for (; x < hvCount2; ++x, ++index, --indexX, tx += uvFactor, px += scaleFactor) { Vector3 v = vertices[indexY + indexX]; vertices[index] = new Vector3(-v.x, v.y, v.z); uvs[index] = new Vector2(tx, ty); } } indexY = (hvCount2Half - 1) * hvCount2; for (int y = hvCount2Half + 1; y < hvCount2; ++y, indexY -= hvCount2, ty += uvFactor, py += scaleFactor) { float tx = 0.0f, px = -1.0f; int x = 0; for (; x <= hvCount2Half; ++x, ++index, tx += uvFactor, px += scaleFactor) { Vector3 v = vertices[indexY + x]; vertices[index] = new Vector3(v.x, -v.y, v.z); uvs[index] = new Vector2(tx, ty); } int indexX = hvCount2Half - 1; for (; x < hvCount2; ++x, ++index, --indexX, tx += uvFactor, px += scaleFactor) { Vector3 v = vertices[indexY + indexX]; vertices[index] = new Vector3(-v.x, -v.y, v.z); uvs[index] = new Vector2(tx, ty); } } } for (int y = 0, index = 0, ofst = 0; y < this.segments; ++y, ofst += hvCount2) { int y0 = ofst, y1 = ofst + hvCount2; for (int x = 0; x < this.segments; ++x, index += 6) { triangles[index + 0] = y0 + x; triangles[index + 1] = y1 + x; triangles[index + 2] = y0 + x + 1; triangles[index + 3] = y1 + x; triangles[index + 4] = y1 + x + 1; triangles[index + 5] = y0 + x + 1; } } mesh.vertices = vertices; mesh.uv = uvs; mesh.triangles = triangles; return mesh; } CombineInstance _CreatePlane(Mesh mesh, Quaternion rotation) { return new CombineInstance() { mesh = mesh, subMeshIndex = 0, transform = Matrix4x4.TRS(Vector3.zero, rotation, Vector3.one)}; } Mesh _CreateSkyboxMesh() { Mesh mesh = _CreateMesh(); var comb = new CombineInstance[] { _CreatePlane(mesh, Quaternion.identity), _CreatePlane(mesh, Quaternion.Euler(0.0f, 90.0f, 0.0f)), _CreatePlane(mesh, Quaternion.Euler(0.0f, 180.0f, 0.0f)), _CreatePlane(mesh, Quaternion.Euler(0.0f, 270.0f, 0.0f)), _CreatePlane(mesh, Quaternion.Euler(-90.0f, 0.0f, 0.0f)), _CreatePlane(mesh, Quaternion.Euler(90.0f, 0.0f, 0.0f))}; Mesh skymesh = new Mesh(); skymesh.CombineMeshes(comb, false, true); return skymesh; } #endif }
using System; using System.IO; using System.ComponentModel; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using ChargeBee.Internal; using ChargeBee.Api; using ChargeBee.Models.Enums; using ChargeBee.Filters.Enums; namespace ChargeBee.Models { public class Item : Resource { public Item() { } public Item(Stream stream) { using (StreamReader reader = new StreamReader(stream)) { JObj = JToken.Parse(reader.ReadToEnd()); apiVersionCheck (JObj); } } public Item(TextReader reader) { JObj = JToken.Parse(reader.ReadToEnd()); apiVersionCheck (JObj); } public Item(String jsonString) { JObj = JToken.Parse(jsonString); apiVersionCheck (JObj); } #region Methods public static CreateRequest Create() { string url = ApiUtil.BuildUrl("items"); return new CreateRequest(url, HttpMethod.POST); } public static EntityRequest<Type> Retrieve(string id) { string url = ApiUtil.BuildUrl("items", CheckNull(id)); return new EntityRequest<Type>(url, HttpMethod.GET); } public static UpdateRequest Update(string id) { string url = ApiUtil.BuildUrl("items", CheckNull(id)); return new UpdateRequest(url, HttpMethod.POST); } public static ItemListRequest List() { string url = ApiUtil.BuildUrl("items"); return new ItemListRequest(url); } public static EntityRequest<Type> Delete(string id) { string url = ApiUtil.BuildUrl("items", CheckNull(id), "delete"); return new EntityRequest<Type>(url, HttpMethod.POST); } #endregion #region Properties public string Id { get { return GetValue<string>("id", true); } } public string Name { get { return GetValue<string>("name", true); } } public string Description { get { return GetValue<string>("description", false); } } public StatusEnum? Status { get { return GetEnum<StatusEnum>("status", false); } } public long? ResourceVersion { get { return GetValue<long?>("resource_version", false); } } public DateTime? UpdatedAt { get { return GetDateTime("updated_at", false); } } public string ItemFamilyId { get { return GetValue<string>("item_family_id", false); } } public TypeEnum ItemType { get { return GetEnum<TypeEnum>("type", true); } } public bool? IsShippable { get { return GetValue<bool?>("is_shippable", false); } } public bool IsGiftable { get { return GetValue<bool>("is_giftable", true); } } public string RedirectUrl { get { return GetValue<string>("redirect_url", false); } } public bool EnabledForCheckout { get { return GetValue<bool>("enabled_for_checkout", true); } } public bool EnabledInPortal { get { return GetValue<bool>("enabled_in_portal", true); } } public bool? IncludedInMrr { get { return GetValue<bool?>("included_in_mrr", false); } } public ItemApplicabilityEnum ItemApplicability { get { return GetEnum<ItemApplicabilityEnum>("item_applicability", true); } } public string GiftClaimRedirectUrl { get { return GetValue<string>("gift_claim_redirect_url", false); } } public string Unit { get { return GetValue<string>("unit", false); } } public bool Metered { get { return GetValue<bool>("metered", true); } } public UsageCalculationEnum? UsageCalculation { get { return GetEnum<UsageCalculationEnum>("usage_calculation", false); } } public DateTime? ArchivedAt { get { return GetDateTime("archived_at", false); } } public List<ItemApplicableItem> ApplicableItems { get { return GetResourceList<ItemApplicableItem>("applicable_items"); } } public JToken Metadata { get { return GetJToken("metadata", false); } } #endregion #region Requests public class CreateRequest : EntityRequest<CreateRequest> { public CreateRequest(string url, HttpMethod method) : base(url, method) { } public CreateRequest Id(string id) { m_params.Add("id", id); return this; } public CreateRequest Name(string name) { m_params.Add("name", name); return this; } public CreateRequest Type(Item.TypeEnum type) { m_params.Add("type", type); return this; } public CreateRequest Description(string description) { m_params.AddOpt("description", description); return this; } public CreateRequest ItemFamilyId(string itemFamilyId) { m_params.AddOpt("item_family_id", itemFamilyId); return this; } public CreateRequest IsGiftable(bool isGiftable) { m_params.AddOpt("is_giftable", isGiftable); return this; } public CreateRequest IsShippable(bool isShippable) { m_params.AddOpt("is_shippable", isShippable); return this; } public CreateRequest EnabledInPortal(bool enabledInPortal) { m_params.AddOpt("enabled_in_portal", enabledInPortal); return this; } public CreateRequest RedirectUrl(string redirectUrl) { m_params.AddOpt("redirect_url", redirectUrl); return this; } public CreateRequest EnabledForCheckout(bool enabledForCheckout) { m_params.AddOpt("enabled_for_checkout", enabledForCheckout); return this; } public CreateRequest ItemApplicability(Item.ItemApplicabilityEnum itemApplicability) { m_params.AddOpt("item_applicability", itemApplicability); return this; } public CreateRequest ApplicableItems(List<string> applicableItems) { m_params.AddOpt("applicable_items", applicableItems); return this; } public CreateRequest Unit(string unit) { m_params.AddOpt("unit", unit); return this; } public CreateRequest GiftClaimRedirectUrl(string giftClaimRedirectUrl) { m_params.AddOpt("gift_claim_redirect_url", giftClaimRedirectUrl); return this; } public CreateRequest IncludedInMrr(bool includedInMrr) { m_params.AddOpt("included_in_mrr", includedInMrr); return this; } public CreateRequest Metered(bool metered) { m_params.AddOpt("metered", metered); return this; } public CreateRequest UsageCalculation(Item.UsageCalculationEnum usageCalculation) { m_params.AddOpt("usage_calculation", usageCalculation); return this; } public CreateRequest Metadata(JToken metadata) { m_params.AddOpt("metadata", metadata); return this; } } public class UpdateRequest : EntityRequest<UpdateRequest> { public UpdateRequest(string url, HttpMethod method) : base(url, method) { } public UpdateRequest Name(string name) { m_params.AddOpt("name", name); return this; } public UpdateRequest Description(string description) { m_params.AddOpt("description", description); return this; } public UpdateRequest IsShippable(bool isShippable) { m_params.AddOpt("is_shippable", isShippable); return this; } public UpdateRequest ItemFamilyId(string itemFamilyId) { m_params.AddOpt("item_family_id", itemFamilyId); return this; } public UpdateRequest EnabledInPortal(bool enabledInPortal) { m_params.AddOpt("enabled_in_portal", enabledInPortal); return this; } public UpdateRequest RedirectUrl(string redirectUrl) { m_params.AddOpt("redirect_url", redirectUrl); return this; } public UpdateRequest EnabledForCheckout(bool enabledForCheckout) { m_params.AddOpt("enabled_for_checkout", enabledForCheckout); return this; } public UpdateRequest ItemApplicability(Item.ItemApplicabilityEnum itemApplicability) { m_params.AddOpt("item_applicability", itemApplicability); return this; } [Obsolete] public UpdateRequest ClearApplicableItems(bool clearApplicableItems) { m_params.AddOpt("clear_applicable_items", clearApplicableItems); return this; } public UpdateRequest ApplicableItems(List<string> applicableItems) { m_params.AddOpt("applicable_items", applicableItems); return this; } public UpdateRequest Unit(string unit) { m_params.AddOpt("unit", unit); return this; } public UpdateRequest GiftClaimRedirectUrl(string giftClaimRedirectUrl) { m_params.AddOpt("gift_claim_redirect_url", giftClaimRedirectUrl); return this; } public UpdateRequest Metadata(JToken metadata) { m_params.AddOpt("metadata", metadata); return this; } public UpdateRequest IncludedInMrr(bool includedInMrr) { m_params.AddOpt("included_in_mrr", includedInMrr); return this; } public UpdateRequest Status(Item.StatusEnum status) { m_params.AddOpt("status", status); return this; } } public class ItemListRequest : ListRequestBase<ItemListRequest> { public ItemListRequest(string url) : base(url) { } public StringFilter<ItemListRequest> Id() { return new StringFilter<ItemListRequest>("id", this).SupportsMultiOperators(true); } public StringFilter<ItemListRequest> ItemFamilyId() { return new StringFilter<ItemListRequest>("item_family_id", this).SupportsMultiOperators(true); } public EnumFilter<Item.TypeEnum, ItemListRequest> Type() { return new EnumFilter<Item.TypeEnum, ItemListRequest>("type", this); } public StringFilter<ItemListRequest> Name() { return new StringFilter<ItemListRequest>("name", this); } public EnumFilter<Item.ItemApplicabilityEnum, ItemListRequest> ItemApplicability() { return new EnumFilter<Item.ItemApplicabilityEnum, ItemListRequest>("item_applicability", this); } public EnumFilter<Item.StatusEnum, ItemListRequest> Status() { return new EnumFilter<Item.StatusEnum, ItemListRequest>("status", this); } public BooleanFilter<ItemListRequest> IsGiftable() { return new BooleanFilter<ItemListRequest>("is_giftable", this); } public TimestampFilter<ItemListRequest> UpdatedAt() { return new TimestampFilter<ItemListRequest>("updated_at", this); } public BooleanFilter<ItemListRequest> EnabledForCheckout() { return new BooleanFilter<ItemListRequest>("enabled_for_checkout", this); } public BooleanFilter<ItemListRequest> EnabledInPortal() { return new BooleanFilter<ItemListRequest>("enabled_in_portal", this); } public BooleanFilter<ItemListRequest> Metered() { return new BooleanFilter<ItemListRequest>("metered", this); } public EnumFilter<Item.UsageCalculationEnum, ItemListRequest> UsageCalculation() { return new EnumFilter<Item.UsageCalculationEnum, ItemListRequest>("usage_calculation", this); } public ItemListRequest SortByName(SortOrderEnum order) { m_params.AddOpt("sort_by["+order.ToString().ToLower()+"]","name"); return this; } public ItemListRequest SortById(SortOrderEnum order) { m_params.AddOpt("sort_by["+order.ToString().ToLower()+"]","id"); return this; } public ItemListRequest SortByUpdatedAt(SortOrderEnum order) { m_params.AddOpt("sort_by["+order.ToString().ToLower()+"]","updated_at"); return this; } } #endregion public enum StatusEnum { UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a dotnet-client version incompatibility. We suggest you to upgrade to the latest version */ [EnumMember(Value = "active")] Active, [EnumMember(Value = "archived")] Archived, [EnumMember(Value = "deleted")] Deleted, } public enum TypeEnum { UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a dotnet-client version incompatibility. We suggest you to upgrade to the latest version */ [EnumMember(Value = "plan")] Plan, [EnumMember(Value = "addon")] Addon, [EnumMember(Value = "charge")] Charge, } public enum ItemApplicabilityEnum { UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a dotnet-client version incompatibility. We suggest you to upgrade to the latest version */ [EnumMember(Value = "all")] All, [EnumMember(Value = "restricted")] Restricted, } public enum UsageCalculationEnum { UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a dotnet-client version incompatibility. We suggest you to upgrade to the latest version */ [EnumMember(Value = "sum_of_usages")] SumOfUsages, [EnumMember(Value = "last_usage")] LastUsage, [EnumMember(Value = "max_usage")] MaxUsage, } #region Subclasses public class ItemApplicableItem : Resource { public string Id { get { return GetValue<string>("id", false); } } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #nullable enable using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.ExceptionServices; using Microsoft.AspNetCore.Hosting.Builder; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.Hosting { /// <summary> /// A builder for <see cref="IWebHost"/> /// </summary> public class WebHostBuilder : IWebHostBuilder { private readonly HostingEnvironment _hostingEnvironment; private readonly IConfiguration _config; private readonly WebHostBuilderContext _context; private WebHostOptions? _options; private bool _webHostBuilt; private Action<WebHostBuilderContext, IServiceCollection>? _configureServices; private Action<WebHostBuilderContext, IConfigurationBuilder>? _configureAppConfigurationBuilder; /// <summary> /// Initializes a new instance of the <see cref="WebHostBuilder"/> class. /// </summary> public WebHostBuilder() { _hostingEnvironment = new HostingEnvironment(); _config = new ConfigurationBuilder() .AddEnvironmentVariables(prefix: "ASPNETCORE_") .Build(); if (string.IsNullOrEmpty(GetSetting(WebHostDefaults.EnvironmentKey))) { // Try adding legacy environment keys, never remove these. UseSetting(WebHostDefaults.EnvironmentKey, Environment.GetEnvironmentVariable("Hosting:Environment") ?? Environment.GetEnvironmentVariable("ASPNET_ENV")); } if (string.IsNullOrEmpty(GetSetting(WebHostDefaults.ServerUrlsKey))) { // Try adding legacy url key, never remove this. UseSetting(WebHostDefaults.ServerUrlsKey, Environment.GetEnvironmentVariable("ASPNETCORE_SERVER.URLS")); } _context = new WebHostBuilderContext { Configuration = _config }; } /// <summary> /// Get the setting value from the configuration. /// </summary> /// <param name="key">The key of the setting to look up.</param> /// <returns>The value the setting currently contains.</returns> public string? GetSetting(string key) { return _config[key]; } /// <summary> /// Add or replace a setting in the configuration. /// </summary> /// <param name="key">The key of the setting to add or replace.</param> /// <param name="value">The value of the setting to add or replace.</param> /// <returns>The <see cref="IWebHostBuilder"/>.</returns> public IWebHostBuilder UseSetting(string key, string? value) { _config[key] = value; return this; } /// <summary> /// Adds a delegate for configuring additional services for the host or web application. This may be called /// multiple times. /// </summary> /// <param name="configureServices">A delegate for configuring the <see cref="IServiceCollection"/>.</param> /// <returns>The <see cref="IWebHostBuilder"/>.</returns> public IWebHostBuilder ConfigureServices(Action<IServiceCollection> configureServices) { if (configureServices == null) { throw new ArgumentNullException(nameof(configureServices)); } return ConfigureServices((_, services) => configureServices(services)); } /// <summary> /// Adds a delegate for configuring additional services for the host or web application. This may be called /// multiple times. /// </summary> /// <param name="configureServices">A delegate for configuring the <see cref="IServiceCollection"/>.</param> /// <returns>The <see cref="IWebHostBuilder"/>.</returns> public IWebHostBuilder ConfigureServices(Action<WebHostBuilderContext, IServiceCollection> configureServices) { _configureServices += configureServices; return this; } /// <summary> /// Adds a delegate for configuring the <see cref="IConfigurationBuilder"/> that will construct an <see cref="IConfiguration"/>. /// </summary> /// <param name="configureDelegate">The delegate for configuring the <see cref="IConfigurationBuilder" /> that will be used to construct an <see cref="IConfiguration" />.</param> /// <returns>The <see cref="IWebHostBuilder"/>.</returns> /// <remarks> /// The <see cref="IConfiguration"/> and <see cref="ILoggerFactory"/> on the <see cref="WebHostBuilderContext"/> are uninitialized at this stage. /// The <see cref="IConfigurationBuilder"/> is pre-populated with the settings of the <see cref="IWebHostBuilder"/>. /// </remarks> public IWebHostBuilder ConfigureAppConfiguration(Action<WebHostBuilderContext, IConfigurationBuilder> configureDelegate) { _configureAppConfigurationBuilder += configureDelegate; return this; } /// <summary> /// Builds the required services and an <see cref="IWebHost"/> which hosts a web application. /// </summary> public IWebHost Build() { if (_webHostBuilt) { throw new InvalidOperationException(Resources.WebHostBuilder_SingleInstance); } _webHostBuilt = true; var hostingServices = BuildCommonServices(out var hostingStartupErrors); var applicationServices = hostingServices.Clone(); var hostingServiceProvider = GetProviderFromFactory(hostingServices); if (!_options.SuppressStatusMessages) { // Warn about deprecated environment variables if (Environment.GetEnvironmentVariable("Hosting:Environment") != null) { Console.WriteLine("The environment variable 'Hosting:Environment' is obsolete and has been replaced with 'ASPNETCORE_ENVIRONMENT'"); } if (Environment.GetEnvironmentVariable("ASPNET_ENV") != null) { Console.WriteLine("The environment variable 'ASPNET_ENV' is obsolete and has been replaced with 'ASPNETCORE_ENVIRONMENT'"); } if (Environment.GetEnvironmentVariable("ASPNETCORE_SERVER.URLS") != null) { Console.WriteLine("The environment variable 'ASPNETCORE_SERVER.URLS' is obsolete and has been replaced with 'ASPNETCORE_URLS'"); } } AddApplicationServices(applicationServices, hostingServiceProvider); var host = new WebHost( applicationServices, hostingServiceProvider, _options, _config, hostingStartupErrors); try { host.Initialize(); // resolve configuration explicitly once to mark it as resolved within the // service provider, ensuring it will be properly disposed with the provider _ = host.Services.GetService<IConfiguration>(); var logger = host.Services.GetRequiredService<ILogger<WebHost>>(); // Warn about duplicate HostingStartupAssemblies var assemblyNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (var assemblyName in _options.GetFinalHostingStartupAssemblies()) { if (!assemblyNames.Add(assemblyName)) { logger.LogWarning($"The assembly {assemblyName} was specified multiple times. Hosting startup assemblies should only be specified once."); } } return host; } catch { // Dispose the host if there's a failure to initialize, this should dispose // services that were constructed until the exception was thrown host.Dispose(); throw; } IServiceProvider GetProviderFromFactory(IServiceCollection collection) { var provider = collection.BuildServiceProvider(); var factory = provider.GetService<IServiceProviderFactory<IServiceCollection>>(); if (factory != null && !(factory is DefaultServiceProviderFactory)) { using (provider) { return factory.CreateServiceProvider(factory.CreateBuilder(collection)); } } return provider; } } [MemberNotNull(nameof(_options))] private IServiceCollection BuildCommonServices(out AggregateException? hostingStartupErrors) { hostingStartupErrors = null; _options = new WebHostOptions(_config, Assembly.GetEntryAssembly()?.GetName().Name ?? string.Empty); if (!_options.PreventHostingStartup) { var exceptions = new List<Exception>(); var processed = new HashSet<Assembly>(); // Execute the hosting startup assemblies foreach (var assemblyName in _options.GetFinalHostingStartupAssemblies()) { try { var assembly = Assembly.Load(new AssemblyName(assemblyName)); if (!processed.Add(assembly)) { // Already processed, skip it continue; } foreach (var attribute in assembly.GetCustomAttributes<HostingStartupAttribute>()) { var hostingStartup = (IHostingStartup)Activator.CreateInstance(attribute.HostingStartupType)!; hostingStartup.Configure(this); } } catch (Exception ex) { // Capture any errors that happen during startup exceptions.Add(new InvalidOperationException($"Startup assembly {assemblyName} failed to execute. See the inner exception for more details.", ex)); } } if (exceptions.Count > 0) { hostingStartupErrors = new AggregateException(exceptions); } } var contentRootPath = ResolveContentRootPath(_options.ContentRootPath, AppContext.BaseDirectory); // Initialize the hosting environment ((IWebHostEnvironment)_hostingEnvironment).Initialize(contentRootPath, _options); _context.HostingEnvironment = _hostingEnvironment; var services = new ServiceCollection(); services.AddSingleton(_options); services.AddSingleton<IWebHostEnvironment>(_hostingEnvironment); services.AddSingleton<IHostEnvironment>(_hostingEnvironment); #pragma warning disable CS0618 // Type or member is obsolete services.AddSingleton<AspNetCore.Hosting.IHostingEnvironment>(_hostingEnvironment); services.AddSingleton<Extensions.Hosting.IHostingEnvironment>(_hostingEnvironment); #pragma warning restore CS0618 // Type or member is obsolete services.AddSingleton(_context); var builder = new ConfigurationBuilder() .SetBasePath(_hostingEnvironment.ContentRootPath) .AddConfiguration(_config, shouldDisposeConfiguration: true); _configureAppConfigurationBuilder?.Invoke(_context, builder); var configuration = builder.Build(); // register configuration as factory to make it dispose with the service provider services.AddSingleton<IConfiguration>(_ => configuration); _context.Configuration = configuration; services.TryAddSingleton(sp => new DiagnosticListener("Microsoft.AspNetCore")); services.TryAddSingleton<DiagnosticSource>(sp => sp.GetRequiredService<DiagnosticListener>()); services.TryAddSingleton(sp => new ActivitySource("Microsoft.AspNetCore")); services.TryAddSingleton(DistributedContextPropagator.Current); services.AddTransient<IApplicationBuilderFactory, ApplicationBuilderFactory>(); services.AddTransient<IHttpContextFactory, DefaultHttpContextFactory>(); services.AddScoped<IMiddlewareFactory, MiddlewareFactory>(); services.AddOptions(); services.AddLogging(); services.AddTransient<IServiceProviderFactory<IServiceCollection>, DefaultServiceProviderFactory>(); if (!string.IsNullOrEmpty(_options.StartupAssembly)) { try { var startupType = StartupLoader.FindStartupType(_options.StartupAssembly, _hostingEnvironment.EnvironmentName); if (typeof(IStartup).IsAssignableFrom(startupType)) { services.AddSingleton(typeof(IStartup), startupType); } else { services.AddSingleton(typeof(IStartup), sp => { var hostingEnvironment = sp.GetRequiredService<IHostEnvironment>(); var methods = StartupLoader.LoadMethods(sp, startupType, hostingEnvironment.EnvironmentName); return new ConventionBasedStartup(methods); }); } } catch (Exception ex) { var capture = ExceptionDispatchInfo.Capture(ex); services.AddSingleton<IStartup>(_ => { capture.Throw(); return null; }); } } _configureServices?.Invoke(_context, services); return services; } private static void AddApplicationServices(IServiceCollection services, IServiceProvider hostingServiceProvider) { // We are forwarding services from hosting container so hosting container // can still manage their lifetime (disposal) shared instances with application services. // NOTE: This code overrides original services lifetime. Instances would always be singleton in // application container. var listener = hostingServiceProvider.GetService<DiagnosticListener>(); services.Replace(ServiceDescriptor.Singleton(typeof(DiagnosticListener), listener!)); services.Replace(ServiceDescriptor.Singleton(typeof(DiagnosticSource), listener!)); var activitySource = hostingServiceProvider.GetService<ActivitySource>(); services.Replace(ServiceDescriptor.Singleton(typeof(ActivitySource), activitySource!)); } private static string ResolveContentRootPath(string? contentRootPath, string basePath) { if (string.IsNullOrEmpty(contentRootPath)) { return basePath; } if (Path.IsPathRooted(contentRootPath)) { return contentRootPath; } return Path.Combine(Path.GetFullPath(basePath), contentRootPath); } } }
// // Copyright 2014-2015 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // Licensed under the Amazon Software License (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/asl/ // // or in the "license" file accompanying this file. This file is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, express or implied. See the License // for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using ThirdParty.Json.LitJson; using Amazon.Runtime.Internal.Util; namespace Amazon.Runtime.Internal.Transform { /// <summary> /// Wraps a json string for unmarshalling. /// /// Each <c>Read()</c> operation gets the next token. /// <c>TestExpression()</c> is used to match the current key-chain /// to an xpath expression. The general pattern looks like this: /// <code> /// JsonUnmarshallerContext context = new JsonUnmarshallerContext(jsonString); /// while (context.Read()) /// { /// if (context.IsKey) /// { /// if (context.TestExpresion("path/to/element")) /// { /// myObject.stringMember = stringUnmarshaller.GetInstance().Unmarshall(context); /// continue; /// } /// } /// } /// </code> /// </summary> public class JsonUnmarshallerContext : UnmarshallerContext { private const string DELIMITER = "/"; #region Private members private StreamReader streamReader = null; private JsonReader jsonReader = null; private JsonPathStack stack = new JsonPathStack(); private string currentField; private JsonToken? currentToken = null; private bool disposed = false; private bool wasPeeked = false; #endregion #region Constructors /// <summary> /// Wrap the jsonstring for unmarshalling. /// </summary> /// <param name="responseStream">Stream that contains the JSON for unmarshalling</param> /// <param name="maintainResponseBody"> If set to true, maintains a copy of the complete response body as the stream is being read.</param> /// <param name="responseData">Response data coming back from the request</param> public JsonUnmarshallerContext(Stream responseStream, bool maintainResponseBody, IWebResponseData responseData) { if (maintainResponseBody) { this.WrappingStream = new CachingWrapperStream(responseStream); responseStream = this.WrappingStream; } this.WebResponseData = responseData; this.MaintainResponseBody = maintainResponseBody; long contentLength; if (responseData != null && long.TryParse(responseData.GetHeaderValue("Content-Length"), out contentLength)) { base.SetupCRCStream(responseData, responseStream, contentLength); } if (this.CrcStream != null) streamReader = new StreamReader(this.CrcStream); else streamReader = new StreamReader(responseStream); jsonReader = new JsonReader(streamReader); } #endregion #region Overrides /// <summary> /// Are we at the start of the json document. /// </summary> public override bool IsStartOfDocument { get { return (CurrentTokenType == JsonToken.None) && (!streamReader.EndOfStream); } } /// <summary> /// Is the current token the end of an object /// </summary> public override bool IsEndElement { get { return CurrentTokenType == JsonToken.ObjectEnd; } } /// <summary> /// Is the current token the start of an object /// </summary> public override bool IsStartElement { get { return CurrentTokenType == JsonToken.ObjectStart; } } /// <summary> /// Returns the element depth of the parser's current position in the json /// document being parsed. /// </summary> public override int CurrentDepth { get { return this.stack.CurrentDepth; } } /// <summary> /// The current Json path that is being unmarshalled. /// </summary> public override string CurrentPath { get { return this.stack.CurrentPath; } } /// <summary> /// Reads to the next token in the json document, and updates the context /// accordingly. /// </summary> /// <returns> /// True if a token was read, false if there are no more tokens to read. /// </returns> public override bool Read() { if (wasPeeked) { wasPeeked = false; return currentToken == null; } bool result = jsonReader.Read(); if (result) { currentToken = jsonReader.Token; UpdateContext(); } else { currentToken = null; } wasPeeked = false; return result; } /// <summary> /// Peeks at the next token. This peek implementation /// reads the next token and makes the subsequent Read() return the same data. /// If Peek is called successively, it will return the same data. /// Only the first one calls Read(), subsequent calls /// will return the same data until a Read() call is made. /// </summary> /// <param name="token">Token to peek.</param> /// <returns>Returns true if the peeked token matches given token.</returns> public bool Peek(JsonToken token) { if (wasPeeked) return currentToken != null && currentToken == token; if (Read()) { wasPeeked = true; return currentToken == token; } return false; } /// <summary> /// Returns the text contents of the current token being parsed. /// </summary> /// <returns> /// The text contents of the current token being parsed. /// </returns> public override string ReadText() { object data = jsonReader.Value; string text; switch (currentToken) { case JsonToken.Null: text = null; break; case JsonToken.String: case JsonToken.PropertyName: text = data as string; break; case JsonToken.Boolean: case JsonToken.Int: case JsonToken.Long: IFormattable iformattable = data as IFormattable; if (iformattable != null) text = iformattable.ToString(null, CultureInfo.InvariantCulture); else text = data.ToString(); break; case JsonToken.Double: var formattable = data as IFormattable; if (formattable != null) text = formattable.ToString("R", CultureInfo.InvariantCulture); else text = data.ToString(); break; default: throw new AmazonClientException( "We expected a VALUE token but got: " + currentToken); } return text; } #endregion #region Public properties /// <summary> /// The type of the current token /// </summary> public JsonToken CurrentTokenType { get { return currentToken.Value; } } #endregion #region Internal methods/properties /// <summary> /// Get the base stream of the jsonStream. /// </summary> public Stream Stream { get { return streamReader.BaseStream; } } /// <summary> /// Peeks at the next (non-whitespace) character in the jsonStream. /// </summary> /// <returns>The next (non-whitespace) character in the jsonStream, or -1 if at the end.</returns> public int Peek() { while (Char.IsWhiteSpace((char)StreamPeek())) { streamReader.Read(); } return StreamPeek(); } #endregion #region Private methods /// <summary> /// Peeks at the next character in the stream. /// If the data isn't buffered into the StreamReader (Peek() returns -1), /// we flush the buffered data and try one more time. /// </summary> /// <returns></returns> private int StreamPeek() { int peek = streamReader.Peek(); if (peek == -1) { streamReader.DiscardBufferedData(); peek = streamReader.Peek(); } return peek; } private void UpdateContext() { if (!currentToken.HasValue) return; if (currentToken.Value == JsonToken.ObjectStart || currentToken.Value == JsonToken.ArrayStart) { // Push '/' for object start and array start. stack.Push(DELIMITER); } else if (currentToken.Value == JsonToken.ObjectEnd || currentToken.Value == JsonToken.ArrayEnd) { if (object.ReferenceEquals(stack.Peek(),DELIMITER)) { // Pop '/' associated with corresponding object start and array start. stack.Pop(); if (stack.Count > 0 && ! object.ReferenceEquals(stack.Peek(),DELIMITER)) { // Pop the property name associated with the // object or array if present. // e.g. {"a":["1","2","3"]} stack.Pop(); } } currentField = null; } else if (currentToken.Value == JsonToken.PropertyName) { string t = ReadText(); currentField = t; // Push property name, it's appended to the stack's CurrentPath, // it this does not affect the depth. stack.Push(currentField); } else if (currentToken.Value != JsonToken.None && !stack.CurrentPath.EndsWith(DELIMITER, StringComparison.OrdinalIgnoreCase)) { // Pop if you encounter a simple data type or null // This will pop the property name associated with it in cases like {"a":"b"}. // Exclude the case where it's a value in an array so we dont end poping the start of array and // property name e.g. {"a":["1","2","3"]} stack.Pop(); } } #endregion protected override void Dispose(bool disposing) { if (!disposed) { if (disposing) { if (streamReader != null) { streamReader.Dispose(); streamReader = null; } } disposed = true; } base.Dispose(disposing); } class JsonPathStack { private Stack<string> stack = new Stack<string>(); int currentDepth = 0; private StringBuilder stackStringBuilder = new StringBuilder(128); private string stackString; public int CurrentDepth { get { return this.currentDepth; } } public string CurrentPath { get { if (this.stackString == null) this.stackString = this.stackStringBuilder.ToString(); return this.stackString; } } public void Push(string value) { if (value == "/") currentDepth++; stackStringBuilder.Append(value); stackString = null; stack.Push(value); } public string Pop() { var value = this.stack.Pop(); if (value == "/") currentDepth--; stackStringBuilder.Remove(stackStringBuilder.Length - value.Length, value.Length); stackString = null; return value; } public string Peek() { return this.stack.Peek(); } public int Count { get { return this.stack.Count; } } } } }
#region WatiN Copyright (C) 2006-2011 Jeroen van Menen //Copyright 2006-2011 Jeroen van Menen // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion Copyright namespace WatiN.Core.Native.Mozilla { using System; using System.IO; using System.Net.Sockets; using System.Text; using System.Windows.Forms; using Logging; using Windows; using UtilityClasses; /// <summary> /// The firefox client port used to communicate with the remote automation server jssh. /// </summary> public class FireFoxClientPort : ClientPortBase { public const string LOCAL_IP_ADRESS = "127.0.0.1"; public static int DEFAULT_PORT = 9997; public string IpAdress { get; set; } public int Port { get; set; } /// <summary> /// Name of the javascript variable that references the DOM:window object. /// </summary> public const string WindowVariableName = "window"; /// <summary> /// Name of the javascript function to retrieve only child elements (skip text nodes). /// </summary> public const string GetChildElementsFunctionName = "WATINgetChildElements"; /// <summary> /// <c>true</c> if the <see cref="Dispose()"/> method has been called to release resources. /// </summary> private bool _disposed; /// <summary> /// Underlying socket used to create a <see cref="NetworkStream"/>. /// </summary> private Socket _telnetSocket; private bool _emulateActiveElement; private bool _emulateActiveElementChecked; public FireFoxClientPort(string ipAdress, int port) { IpAdress = ipAdress; Port = port; } /// <summary> /// Finalizes an instance of the <see cref="FireFoxClientPort"/> class. /// Releases unmanaged resources and performs other cleanup operations before the /// <see cref="FireFox"/> is reclaimed by garbage collection. /// </summary> ~FireFoxClientPort() { Dispose(false); } /// <summary> /// Gets a value indicating whether this <see cref="FireFoxClientPort"/> is connected. /// </summary> /// <value><c>true</c> if connected; otherwise, <c>false</c>.</value> public bool Connected { get; private set; } /// <summary> /// Gets the name of the javascript variable that references the DOM:document object. /// </summary> public override string DocumentVariableName { get { return "doc"; } } /// <summary> /// Gets the type of java script engine. /// </summary> /// <value>The type of java script engine.</value> public override JavaScriptEngineType JavaScriptEngine { get { return JavaScriptEngineType.Mozilla; } } /// <summary> /// Gets the name of the browser variable. /// </summary> /// <value>The name of the browser variable.</value> public override string BrowserVariableName { get { return "browser"; } } /// <summary> /// Gets a value indicating whether the main FireFox window is visible, it's possible that the /// main FireFox window is not visible if a previous shutdown didn't complete correctly /// in which case the restore / resume previous session dialog may be visible. /// </summary> private bool IsMainWindowVisible { get { var result = NativeMethods.GetWindowText(Process.MainWindowHandle).Contains("Mozilla Firefox"); return result; } } /// <summary> /// Gets a value indicating whether IsRestoreSessionDialogVisible. /// </summary> /// <value> /// The is restore session dialog visible. /// </value> private bool IsRestoreSessionDialogVisible { get { var result = NativeMethods.GetWindowText(Process.MainWindowHandle).Contains("Firefox - "); return result; } } /// <summary> /// </summary> /// <param name="url"> /// The url. /// </param> /// <exception cref="FireFoxException"> /// </exception> public override void Connect(string url) { Connect(url, true); } /// <summary> /// </summary> /// <exception cref="FireFoxException"> /// </exception> public virtual void ConnectToExisting() { Connect(null, false); } private void Connect(string url, bool createNewFireFoxInstance) { ThrowExceptionIfConnected(); // Init _disposed = false; LastResponse = string.Empty; Response = new StringBuilder(); if (createNewFireFoxInstance) CreateNewFireFoxInstance(url); Logger.LogDebug("Attempting to connect to jssh server on localhost port 9997."); ConnectToJsshServer(); WaitForConnectionEstablished(); Logger.LogDebug("Successfully connected to FireFox using jssh."); if (createNewFireFoxInstance) DefineDefaultJSVariablesForWindow(0); } private void ConnectToJsshServer() { _telnetSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) {Blocking = true}; try { _telnetSocket.Connect(IpAdress, Port); Connected = true; } catch (SocketException sockException) { Logger.LogDebug(string.Format("Failed connecting to jssh server.\nError code:{0}\nError message:{1}", sockException.ErrorCode, sockException.Message)); throw new FireFoxException("Unable to connect to jssh server, please make sure you have correctly installed the jssh.xpi plugin", sockException); } } internal override System.Diagnostics.Process Process { get { return FireFox.CurrentProcess; } set { // not possible; } } private void CreateNewFireFoxInstance(string url) { Logger.LogDebug("Starting a new Firefox instance."); CloseExistingFireFoxInstances(); if (string.IsNullOrEmpty(url)) url = "about:blank"; FireFox.CreateProcess(url + " -jssh", true); if (IsMainWindowVisible) return; if (!IsRestoreSessionDialogVisible) return; NativeMethods.SetForegroundWindow(Process.MainWindowHandle); // TODO replace SendKeys cause they will hang the test when running test in a service or on // a remote desktop session or on a locked system SendKeys.SendWait("{TAB}"); SendKeys.SendWait("{ENTER}"); } private void ThrowExceptionIfConnected() { if (Connected) { throw new FireFoxException("Already connected to jssh server."); } } ///<summary> ///Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. ///</summary> ///<filterpriority>2</filterpriority> public override void Dispose() { Dispose(true); // This object will be cleaned up by the Dispose method. // Therefore, you should call GC.SupressFinalize to // take this object off the finalization queue // and prevent finalization code for this object // from executing a second time. GC.SuppressFinalize(this); } /// <summary> /// Reloads the javascript variables that are scoped at the document level. /// </summary> public override void InitializeDocument() { // Check to see if setting the reference (and doing the loop for activeElement which is time consuming) // is needed. var needToUpdateDocumentReference = WriteAndReadAsBool("{0} != {1}.document", DocumentVariableName, WindowVariableName); if (!needToUpdateDocumentReference) return; // Sets up the document variable Write("var {0} = {1}.document;", DocumentVariableName, WindowVariableName); if (!EmulateActiveElement()) return; // Javascript to implement document.activeElement if not supported by browser (FireFox 2.x) Write(DocumentVariableName + ".activeElement = " + DocumentVariableName + ".body;" + "var allElements = " + DocumentVariableName + ".getElementsByTagName(\"*\");" + "for (i = 0; i < allElements.length; i++){" + "allElements[i].addEventListener(\"focus\", function (event) {" + DocumentVariableName + ".activeElement = event.target;}, false);}"); } private bool EmulateActiveElement() { if (!_emulateActiveElementChecked) { _emulateActiveElement = WriteAndReadAsBool(DocumentVariableName + ".activeElement == null"); _emulateActiveElementChecked = true; } return _emulateActiveElement; } /// <summary> /// Releases unmanaged and - optionally - managed resources /// </summary> /// <param name="disposing"> /// <c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources. /// </param> protected void Dispose(bool disposing) { // Check to see if Dispose has already been called. if (!_disposed) { // If disposing equals true, dispose all managed // and unmanaged resources. if (disposing) { // Dispose managed resources. if (_telnetSocket != null && _telnetSocket.Connected && (Process == null || !Process.HasExited)) { try { var windowCount = WriteAndReadAsInt("getWindows().length", null); Logger.LogDebug(string.Format("Closing window. {0} total windows found", windowCount)); SendCommand(string.Format("{0}.close();", WindowVariableName)); if (windowCount == 1) { Logger.LogDebug("No further windows remain open."); CloseConnection(); CloseFireFoxProcess(); } else { TryFuncUntilTimeOut waiter = new TryFuncUntilTimeOut(TimeSpan.FromMilliseconds(2000)); bool windowClosed = waiter.Try<bool>(() => { return WriteAndReadAsInt("getWindows().length", null) == windowCount - 1; }); } } catch (IOException ex) { Logger.LogDebug("Error communicating with jssh server to initiate shut down, message: {0}", ex.Message); } } } } _disposed = true; Connected = false; } private void CloseFireFoxProcess() { //if (Process == null) return; //Process.WaitForExit(5000); //if (Process == null || Process.HasExited) return; System.Diagnostics.Process firefoxProcess = FireFox.CurrentProcess; if (firefoxProcess == null) { return; } firefoxProcess.WaitForExit(5000); firefoxProcess = FireFox.CurrentProcess; if (firefoxProcess == null) { return; } else if (firefoxProcess.HasExited) { TryFuncUntilTimeOut waiter = new TryFuncUntilTimeOut(TimeSpan.FromMilliseconds(5000)); bool procIsNull = waiter.Try<bool>(() => { firefoxProcess = FireFox.CurrentProcess; return firefoxProcess == null; }); if (procIsNull) { if (!waiter.DidTimeOut && firefoxProcess == null) { return; } } } Logger.LogDebug("Killing FireFox process"); UtilityClass.TryActionIgnoreException(() => Process.Kill()); } public void CloseConnection() { Logger.LogDebug("Closing connection to jssh."); _telnetSocket.Close(); Connected = false; } /// <summary> /// Writes the specified data to the jssh server. /// </summary> /// <param name="data"> /// The data. /// </param> /// <param name="resultExpected"> /// </param> /// <param name="checkForErrors"> /// </param> /// <param name="args"> /// </param> protected override void SendAndRead(string data, bool resultExpected, bool checkForErrors, params object[] args) { var command = UtilityClass.StringFormat(data, args); SendCommand(command); ReadResponse(resultExpected, checkForErrors); } /// <summary> /// </summary> /// <param name="response"> /// The response. /// </param> /// <exception cref="FireFoxException"> /// </exception> private static void CheckForError(string response) { if (string.IsNullOrEmpty(response)) { return; } if (response.StartsWith("SyntaxError", StringComparison.InvariantCultureIgnoreCase) || response.StartsWith("TypeError", StringComparison.InvariantCultureIgnoreCase) || response.StartsWith("uncaught exception", StringComparison.InvariantCultureIgnoreCase) || response.StartsWith("ReferenceError:", StringComparison.InvariantCultureIgnoreCase)) { throw new FireFoxException(string.Format("Error sending last message to jssh server: {0}", response)); } } /// <summary> /// Cleans the response. /// </summary> /// <param name="response"> /// The response. /// </param> /// <returns> /// Response from FireFox with out any of the telnet UI characters /// </returns> private static string CleanTelnetResponse(string response) { // HACK refactor in the future, should find a cleaner way of doing if (!string.IsNullOrEmpty(response)) { if (response.EndsWith(string.Format("{0}>", "\n"))) { response = response.Substring(0, response.Length - 2); } else if (response.EndsWith(string.Format("?{0}> ", "\n"))) { response = response.Substring(0, response.Length - 4); } else if (response.EndsWith(string.Format("{0}> ", "\n"))) { response = response.Substring(0, response.Length - 3); } else if (response.EndsWith(string.Format("{0}> {0}", "\n"))) { response = response.Substring(0, response.Length - 4); } else if (response.EndsWith(string.Format("{0}> {0}{0}", "\n"))) { response = response.Substring(0, response.Length - 5); } else if (response.EndsWith(string.Format("{0}>", Environment.NewLine))) { response = response.Substring(0, response.Length - 3); } else if (response.EndsWith(string.Format("{0}> ", Environment.NewLine))) { response = response.Substring(0, response.Length - 4); } else if (response.EndsWith(string.Format("{0}> {0}", Environment.NewLine))) { response = response.Substring(0, response.Length - 6); } else if (response.EndsWith(string.Format("{0}> {0}{0}", Environment.NewLine))) { response = response.Substring(0, response.Length - 8); } if (response.StartsWith("> ")) { response = response.Substring(2); } else if (response.StartsWith(string.Format("{0}> ", "\n"))) { response = response.Substring(3); } } return response; } /// <summary> /// Defines the default JS variables used to automate this FireFox window. /// </summary> /// <param name="windowIndex">Index of the window.</param> internal void DefineDefaultJSVariablesForWindow(int windowIndex) { Write("var w0 = getWindows()[{0}];", windowIndex.ToString()); Write("var {0} = {1}", GetChildElementsFunctionName, GetChildElementsFunction()); Write("var {0} = w0.content;", WindowVariableName); Write("var {0} = w0.document;", DocumentVariableName); Write("var {0} = w0.getBrowser();", BrowserVariableName); } private static string GetChildElementsFunction() { return "function(node){var a=[];var tags=node.childNodes;for (var i=0;i<tags.length;++i){if (tags[i].nodeType!=3) a.push(tags[i]);} return a;}"; } /// <summary> /// Reads the response from the jssh server. /// </summary> /// <param name="resultExpected"> /// The result Expected. /// </param> /// <param name="checkForErrors"> /// The check For Errors. /// </param> private void ReadResponse(bool resultExpected, bool checkForErrors) { var stream = new NetworkStream(_telnetSocket); LastResponse = string.Empty; LastResponseRaw = string.Empty; const int bufferSize = 4096; var buffer = new byte[bufferSize]; while (!stream.CanRead) { // TODO: need to work out a better way for this System.Threading.Thread.Sleep(10); } string readData; do { var read = stream.Read(buffer, 0, bufferSize); readData = Encoding.UTF8.GetString(buffer, 0, read); Logger.LogDebug("jssh says: '{0}'", readData.Replace("\n", "[newline]")); LastResponseRaw += readData; AddToLastResponse(CleanTelnetResponse(readData)); } while (!readData.EndsWith("> ") || stream.DataAvailable || (resultExpected && string.IsNullOrEmpty(LastResponse))); // Convert \n to newline if (LastResponse != null) { LastResponse = LastResponse.Replace("\n", Environment.NewLine); } Response.Append(LastResponse); if (checkForErrors) { CheckForError(LastResponse); } } /// <summary> /// Sends a command to the FireFox remote server. /// </summary> /// <param name="data"> /// The data to send. /// </param> /// <exception cref="FireFoxException">When not connected.</exception> private void SendCommand(string data) { if (!Connected) { throw new FireFoxException("You must connect before writing to the server."); } var bytes = Encoding.ASCII.GetBytes(data + "\n"); Logger.LogDebug("sending: {0}", data); using (var networkStream = new NetworkStream(_telnetSocket)) { networkStream.Write(bytes, 0, bytes.Length); networkStream.Flush(); } } /// <summary> /// </summary> /// <exception cref="FireFoxException"> /// </exception> private void CloseExistingFireFoxInstances() { System.Diagnostics.Process firefoxProcess = FireFox.CurrentProcess; if (firefoxProcess != null && !Settings.CloseExistingFireFoxInstances) { throw new FireFoxException("Existing instances of FireFox detected."); } var currentProcess = FireFox.CurrentProcess; if (currentProcess != null && !currentProcess.HasExited) { firefoxProcess.Kill(); } } /// <summary> /// Writes a line to the jssh server. /// </summary> private void WaitForConnectionEstablished() { SendCommand("\n"); var rawResponse = string.Empty; var responseToWaitFor = "Welcome to the Mozilla JavaScript Shell!\n\n> \n> \n> "; // .Replace("\n", Environment.NewLine); while (rawResponse != responseToWaitFor) { ReadResponse(false, true); rawResponse += LastResponseRaw; } } } }
namespace javax.net.ssl { [global::MonoJavaBridge.JavaClass(typeof(global::javax.net.ssl.SSLSocket_))] public abstract partial class SSLSocket : java.net.Socket { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected SSLSocket(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public abstract global::java.lang.String[] getSupportedCipherSuites(); private static global::MonoJavaBridge.MethodId _m1; public abstract global::javax.net.ssl.SSLSession getSession(); private static global::MonoJavaBridge.MethodId _m2; public abstract global::java.lang.String[] getEnabledCipherSuites(); private static global::MonoJavaBridge.MethodId _m3; public abstract void setEnabledCipherSuites(java.lang.String[] arg0); private static global::MonoJavaBridge.MethodId _m4; public abstract global::java.lang.String[] getSupportedProtocols(); private static global::MonoJavaBridge.MethodId _m5; public abstract global::java.lang.String[] getEnabledProtocols(); private static global::MonoJavaBridge.MethodId _m6; public abstract void setEnabledProtocols(java.lang.String[] arg0); private static global::MonoJavaBridge.MethodId _m7; public abstract void addHandshakeCompletedListener(javax.net.ssl.HandshakeCompletedListener arg0); private static global::MonoJavaBridge.MethodId _m8; public abstract void removeHandshakeCompletedListener(javax.net.ssl.HandshakeCompletedListener arg0); private static global::MonoJavaBridge.MethodId _m9; public abstract void startHandshake(); private static global::MonoJavaBridge.MethodId _m10; public abstract void setUseClientMode(bool arg0); private static global::MonoJavaBridge.MethodId _m11; public abstract bool getUseClientMode(); private static global::MonoJavaBridge.MethodId _m12; public abstract void setNeedClientAuth(bool arg0); private static global::MonoJavaBridge.MethodId _m13; public abstract bool getNeedClientAuth(); private static global::MonoJavaBridge.MethodId _m14; public abstract void setWantClientAuth(bool arg0); private static global::MonoJavaBridge.MethodId _m15; public abstract bool getWantClientAuth(); private static global::MonoJavaBridge.MethodId _m16; public abstract void setEnableSessionCreation(bool arg0); private static global::MonoJavaBridge.MethodId _m17; public abstract bool getEnableSessionCreation(); private static global::MonoJavaBridge.MethodId _m18; protected SSLSocket() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::javax.net.ssl.SSLSocket._m18.native == global::System.IntPtr.Zero) global::javax.net.ssl.SSLSocket._m18 = @__env.GetMethodIDNoThrow(global::javax.net.ssl.SSLSocket.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(javax.net.ssl.SSLSocket.staticClass, global::javax.net.ssl.SSLSocket._m18); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m19; protected SSLSocket(java.lang.String arg0, int arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::javax.net.ssl.SSLSocket._m19.native == global::System.IntPtr.Zero) global::javax.net.ssl.SSLSocket._m19 = @__env.GetMethodIDNoThrow(global::javax.net.ssl.SSLSocket.staticClass, "<init>", "(Ljava/lang/String;I)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(javax.net.ssl.SSLSocket.staticClass, global::javax.net.ssl.SSLSocket._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m20; protected SSLSocket(java.net.InetAddress arg0, int arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::javax.net.ssl.SSLSocket._m20.native == global::System.IntPtr.Zero) global::javax.net.ssl.SSLSocket._m20 = @__env.GetMethodIDNoThrow(global::javax.net.ssl.SSLSocket.staticClass, "<init>", "(Ljava/net/InetAddress;I)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(javax.net.ssl.SSLSocket.staticClass, global::javax.net.ssl.SSLSocket._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m21; protected SSLSocket(java.lang.String arg0, int arg1, java.net.InetAddress arg2, int arg3) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::javax.net.ssl.SSLSocket._m21.native == global::System.IntPtr.Zero) global::javax.net.ssl.SSLSocket._m21 = @__env.GetMethodIDNoThrow(global::javax.net.ssl.SSLSocket.staticClass, "<init>", "(Ljava/lang/String;ILjava/net/InetAddress;I)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(javax.net.ssl.SSLSocket.staticClass, global::javax.net.ssl.SSLSocket._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m22; protected SSLSocket(java.net.InetAddress arg0, int arg1, java.net.InetAddress arg2, int arg3) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::javax.net.ssl.SSLSocket._m22.native == global::System.IntPtr.Zero) global::javax.net.ssl.SSLSocket._m22 = @__env.GetMethodIDNoThrow(global::javax.net.ssl.SSLSocket.staticClass, "<init>", "(Ljava/net/InetAddress;ILjava/net/InetAddress;I)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(javax.net.ssl.SSLSocket.staticClass, global::javax.net.ssl.SSLSocket._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); Init(@__env, handle); } static SSLSocket() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::javax.net.ssl.SSLSocket.staticClass = @__env.NewGlobalRef(@__env.FindClass("javax/net/ssl/SSLSocket")); } } [global::MonoJavaBridge.JavaProxy(typeof(global::javax.net.ssl.SSLSocket))] internal sealed partial class SSLSocket_ : javax.net.ssl.SSLSocket { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal SSLSocket_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public override global::java.lang.String[] getSupportedCipherSuites() { return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.String>(this, global::javax.net.ssl.SSLSocket_.staticClass, "getSupportedCipherSuites", "()[Ljava/lang/String;", ref global::javax.net.ssl.SSLSocket_._m0) as java.lang.String[]; } private static global::MonoJavaBridge.MethodId _m1; public override global::javax.net.ssl.SSLSession getSession() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<javax.net.ssl.SSLSession>(this, global::javax.net.ssl.SSLSocket_.staticClass, "getSession", "()Ljavax/net/ssl/SSLSession;", ref global::javax.net.ssl.SSLSocket_._m1) as javax.net.ssl.SSLSession; } private static global::MonoJavaBridge.MethodId _m2; public override global::java.lang.String[] getEnabledCipherSuites() { return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.String>(this, global::javax.net.ssl.SSLSocket_.staticClass, "getEnabledCipherSuites", "()[Ljava/lang/String;", ref global::javax.net.ssl.SSLSocket_._m2) as java.lang.String[]; } private static global::MonoJavaBridge.MethodId _m3; public override void setEnabledCipherSuites(java.lang.String[] arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.net.ssl.SSLSocket_.staticClass, "setEnabledCipherSuites", "([Ljava/lang/String;)V", ref global::javax.net.ssl.SSLSocket_._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m4; public override global::java.lang.String[] getSupportedProtocols() { return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.String>(this, global::javax.net.ssl.SSLSocket_.staticClass, "getSupportedProtocols", "()[Ljava/lang/String;", ref global::javax.net.ssl.SSLSocket_._m4) as java.lang.String[]; } private static global::MonoJavaBridge.MethodId _m5; public override global::java.lang.String[] getEnabledProtocols() { return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.String>(this, global::javax.net.ssl.SSLSocket_.staticClass, "getEnabledProtocols", "()[Ljava/lang/String;", ref global::javax.net.ssl.SSLSocket_._m5) as java.lang.String[]; } private static global::MonoJavaBridge.MethodId _m6; public override void setEnabledProtocols(java.lang.String[] arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.net.ssl.SSLSocket_.staticClass, "setEnabledProtocols", "([Ljava/lang/String;)V", ref global::javax.net.ssl.SSLSocket_._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m7; public override void addHandshakeCompletedListener(javax.net.ssl.HandshakeCompletedListener arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.net.ssl.SSLSocket_.staticClass, "addHandshakeCompletedListener", "(Ljavax/net/ssl/HandshakeCompletedListener;)V", ref global::javax.net.ssl.SSLSocket_._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m8; public override void removeHandshakeCompletedListener(javax.net.ssl.HandshakeCompletedListener arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.net.ssl.SSLSocket_.staticClass, "removeHandshakeCompletedListener", "(Ljavax/net/ssl/HandshakeCompletedListener;)V", ref global::javax.net.ssl.SSLSocket_._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m9; public override void startHandshake() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.net.ssl.SSLSocket_.staticClass, "startHandshake", "()V", ref global::javax.net.ssl.SSLSocket_._m9); } private static global::MonoJavaBridge.MethodId _m10; public override void setUseClientMode(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.net.ssl.SSLSocket_.staticClass, "setUseClientMode", "(Z)V", ref global::javax.net.ssl.SSLSocket_._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m11; public override bool getUseClientMode() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::javax.net.ssl.SSLSocket_.staticClass, "getUseClientMode", "()Z", ref global::javax.net.ssl.SSLSocket_._m11); } private static global::MonoJavaBridge.MethodId _m12; public override void setNeedClientAuth(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.net.ssl.SSLSocket_.staticClass, "setNeedClientAuth", "(Z)V", ref global::javax.net.ssl.SSLSocket_._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m13; public override bool getNeedClientAuth() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::javax.net.ssl.SSLSocket_.staticClass, "getNeedClientAuth", "()Z", ref global::javax.net.ssl.SSLSocket_._m13); } private static global::MonoJavaBridge.MethodId _m14; public override void setWantClientAuth(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.net.ssl.SSLSocket_.staticClass, "setWantClientAuth", "(Z)V", ref global::javax.net.ssl.SSLSocket_._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m15; public override bool getWantClientAuth() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::javax.net.ssl.SSLSocket_.staticClass, "getWantClientAuth", "()Z", ref global::javax.net.ssl.SSLSocket_._m15); } private static global::MonoJavaBridge.MethodId _m16; public override void setEnableSessionCreation(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::javax.net.ssl.SSLSocket_.staticClass, "setEnableSessionCreation", "(Z)V", ref global::javax.net.ssl.SSLSocket_._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m17; public override bool getEnableSessionCreation() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::javax.net.ssl.SSLSocket_.staticClass, "getEnableSessionCreation", "()Z", ref global::javax.net.ssl.SSLSocket_._m17); } static SSLSocket_() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::javax.net.ssl.SSLSocket_.staticClass = @__env.NewGlobalRef(@__env.FindClass("javax/net/ssl/SSLSocket")); } } }
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 CodeJewels.Services.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>(); } /// <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 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 get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and 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)) { 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="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <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.ActionDescriptor.ReturnType; 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, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [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.IO; using System.Linq; using System.Threading.Tasks; using EasyNetQ; using Marten; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Observatory.EventModels; using Observatory.EventModels.HostEvents; using Observatory.DataModels.Hosts; namespace Observatory.DatabaseWorker.Services { public class HostsService { private readonly IBus _bus; private readonly IDocumentStore _documentStore; public HostsService(IBus bus, IDocumentStore documentStore) { _bus = bus; _documentStore = documentStore; Register(); } public void Register() { _bus.RespondAsync<GetAllHosts, GetAllHostsResponse>(request => ProcessGetAllHosts(request)); _bus.RespondAsync<GetHost, GetHostResponse>(request => ProcessGetHost(request)); _bus.RespondAsync<CreateHost, GenericResponse>(request => ProcessCreateHost(request)); _bus.RespondAsync<UpdateHost, GenericResponse>(request => ProcessUpdateHost(request)); _bus.RespondAsync<UpdateHostData, GenericResponse>(request => ProcessUpdateHostData(request)); _bus.RespondAsync<DeleteHost, GenericResponse>(request => ProcessDeleteHost(request)); _bus.RespondAsync<AddTagToHost, GenericResponse>(request => ProcessAddTagToHost(request)); _bus.RespondAsync<RemoveTagFromHost, GenericResponse>(request => ProcessRemoveTagFromHost(request)); _bus.RespondAsync<GetHostStateData, GetHostStateDataResponse>(request => ProcessGetHostStateData(request)); _bus.RespondAsync<GetHostsStateData, GetHostsStateDataResponse>(request => ProcessGetHostsStateData(request)); _bus.RespondAsync<AddHostStateData, GenericResponse>(request => ProcessAddHostStateData(request)); _bus.RespondAsync<UpdateHostStateData, GenericResponse>(request => ProcessUpdateHostStateData(request)); _bus.RespondAsync<CleanHostStateData, GenericResponse>(request => ProcessCleanHostStateData(request)); } private async Task<GetAllHostsResponse> ProcessGetAllHosts(GetAllHosts request) { using (var session = _documentStore.LightweightSession()) { var reply = await session.Query<Host>() .OrderBy(x => x.Hostname) .Skip(request.Skip).Take(request.Take) .ToListAsync(); var hosts = reply.Select(x => new Host { Id = x.Id, Hostname = x.Hostname, Alias = x.Alias, Description = x.Description, NoteFilePath = x.NoteFilePath, Tags = x.Tags }); return new GetAllHostsResponse { Hosts = hosts.ToList() }; } } private async Task<GetHostResponse> ProcessGetHost(GetHost request) { using (var session = _documentStore.QuerySession()) { var reply = await session.Query<Host>() .Where(x => x.Id == request.HostId) .Select(x => new Host { Id = x.Id, Hostname = x.Hostname, Alias = x.Alias, Description = x.Description, NoteFilePath = x.NoteFilePath, Tags = x.Tags }).SingleAsync(); var host = reply; return new GetHostResponse { Host = host }; } } private async Task<GenericResponse> ProcessCreateHost(CreateHost request) { using (var session = _documentStore.LightweightSession()) { request.Host.Hostname = request.Host.Hostname.Trim(); if (0 < await session.Query<Host>().Where(x => x.Hostname == request.Host.Hostname).CountAsync()) return new GenericResponse { Success = false }; session.Insert<Host>(request.Host); await session.SaveChangesAsync(); } return new GenericResponse { Success = true }; } private async Task<GenericResponse> ProcessUpdateHost(UpdateHost request) { using (var session = _documentStore.LightweightSession()) { session.Store<Host>(request.Host); await session.SaveChangesAsync(); } return new GenericResponse { Success = true }; } private async Task<GenericResponse> ProcessUpdateHostData(UpdateHostData request) { using (var session = _documentStore.LightweightSession()) { var id = request.Host.Id; session.Patch<Host>(id).Set(x => x.Hostname, request.Host.Hostname); session.Patch<Host>(id).Set(x => x.Alias, request.Host.Alias); session.Patch<Host>(id).Set(x => x.Description, request.Host.Description); session.Patch<Host>(id).Set(x => x.NoteFilePath, request.Host.NoteFilePath); await session.SaveChangesAsync(); } return new GenericResponse { Success = true }; } private async Task<GenericResponse> ProcessDeleteHost(DeleteHost request) { using (var session = _documentStore.LightweightSession()) { session.Delete<Host>(request.HostId); await session.SaveChangesAsync(); } return new GenericResponse { Success = true }; } private async Task<GenericResponse> ProcessAddTagToHost(AddTagToHost request) { using (var session = _documentStore.LightweightSession()) { session.Patch<Host>(request.HostId) // .Append(x => x.Tags, tag); .AppendIfNotExists(x => x.Tags, request.Tag); await session.SaveChangesAsync(); } return new GenericResponse { Success = true }; } private async Task<GenericResponse> ProcessRemoveTagFromHost(RemoveTagFromHost request) { using (var session = _documentStore.LightweightSession()) { session.Patch<Host>(request.HostId).Remove(x => x.Tags, request.Tag); await session.SaveChangesAsync(); } return new GenericResponse { Success = true }; } private async Task<GetHostStateDataResponse> ProcessGetHostStateData(GetHostStateData request) { using (var session = _documentStore.QuerySession()) if (request.Count > 0) return new GetHostStateDataResponse { StateEntries = (await session.LoadAsync<Host>(request.HostId)).StateEntries.Take(request.Count).ToList() }; else return new GetHostStateDataResponse { StateEntries = (await session.LoadAsync<Host>(request.HostId)).StateEntries }; } private async Task<GetHostsStateDataResponse> ProcessGetHostsStateData(GetHostsStateData request) { using (var session = _documentStore.QuerySession()) return new GetHostsStateDataResponse { Hosts = (await session.LoadManyAsync<Host>(request.HostIds.ToArray())) .Select(host => new Host { Id = host.Id, StateEntries = host.StateEntries.Take(request.Count).ToList() }) .ToList() }; } private async Task<GenericResponse> ProcessAddHostStateData(AddHostStateData request) { using (var session = _documentStore.LightweightSession()) { session.Patch<Host>(request.HostId).Insert(x => x.StateEntries, request.StateEntry); await session.SaveChangesAsync(); } return new GenericResponse { Success = true }; } private async Task<GenericResponse> ProcessUpdateHostStateData(UpdateHostStateData request) { using (var session = _documentStore.LightweightSession()) { var host = await session.LoadAsync<Host>(request.HostId); host.StateEntries.First().Time = request.StateEntry.Time; host.StateEntries.First().StatusCode = request.StateEntry.StatusCode; session.Patch<Host>(request.HostId).Set(x => x.StateEntries, host.StateEntries); ; await session.SaveChangesAsync(); } return new GenericResponse { Success = true }; } private async Task<GenericResponse> ProcessCleanHostStateData(CleanHostStateData request) { using (var session = _documentStore.LightweightSession()) { var host = await session.LoadAsync<Host>(request.HostId); var temp = host.StateEntries.Take(500).ToList(); session.Patch<Host>(request.HostId).Set(x => x.StateEntries, temp); await session.SaveChangesAsync(); } return new GenericResponse { Success = true }; } } }
#region License // Copyright 2010 Buu Nguyen, Morten Mertner // // 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. // // The latest version of this file can be found at http://fasterflect.codeplex.com/ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Fasterflect.Emitter; namespace Fasterflect { /// <summary> /// Extension methods for locating and accessing fields. /// </summary> public static class FieldExtensions { #region Field Access /// <summary> /// Sets the field specified by <paramref name="name"/> on the given <paramref name="obj"/> /// to the specified <paramref name="value" />. /// </summary> /// <returns><paramref name="obj"/>.</returns> public static object SetFieldValue( this object obj, string name, object value ) { DelegateForSetFieldValue( obj.GetTypeAdjusted(), name )( obj, value ); return obj; } /// <summary> /// Gets the value of the field specified by <paramref name="name"/> on the given <paramref name="obj"/>. /// </summary> public static object GetFieldValue( this object obj, string name ) { return DelegateForGetFieldValue( obj.GetTypeAdjusted(), name )( obj ); } /// <summary> /// Sets the field specified by <paramref name="name"/> and matching <paramref name="bindingFlags"/> /// on the given <paramref name="obj"/> to the specified <paramref name="value" />. /// </summary> /// <returns><paramref name="obj"/>.</returns> public static object SetFieldValue( this object obj, string name, object value, Flags bindingFlags ) { DelegateForSetFieldValue( obj.GetTypeAdjusted(), name, bindingFlags )( obj, value ); return obj; } /// <summary> /// Gets the value of the field specified by <paramref name="name"/> and matching <paramref name="bindingFlags"/> /// on the given <paramref name="obj"/>. /// </summary> public static object GetFieldValue( this object obj, string name, Flags bindingFlags ) { return DelegateForGetFieldValue( obj.GetTypeAdjusted(), name, bindingFlags )( obj ); } /// <summary> /// Creates a delegate which can set the value of the field specified by <paramref name="name"/> on /// the given <paramref name="type"/>. /// </summary> public static MemberSetter DelegateForSetFieldValue( this Type type, string name ) { return DelegateForSetFieldValue( type, name, Flags.StaticInstanceAnyVisibility ); } /// <summary> /// Creates a delegate which can get the value of the field specified by <paramref name="name"/> on /// the given <paramref name="type"/>. /// </summary> public static MemberGetter DelegateForGetFieldValue( this Type type, string name ) { return DelegateForGetFieldValue( type, name, Flags.StaticInstanceAnyVisibility ); } /// <summary> /// Creates a delegate which can set the value of the field specified by <paramref name="name"/> and /// matching <paramref name="bindingFlags"/> on the given <paramref name="type"/>. /// </summary> public static MemberSetter DelegateForSetFieldValue( this Type type, string name, Flags bindingFlags ) { var callInfo = new CallInfo(type, null, bindingFlags, MemberTypes.Field, name, null, null, false); return (MemberSetter) new MemberSetEmitter( callInfo ).GetDelegate(); } /// <summary> /// Creates a delegate which can get the value of the field specified by <paramref name="name"/> and /// matching <paramref name="bindingFlags"/> on the given <paramref name="type"/>. /// </summary> public static MemberGetter DelegateForGetFieldValue( this Type type, string name, Flags bindingFlags ) { var callInfo = new CallInfo(type, null, bindingFlags, MemberTypes.Field, name, null, null, true); return (MemberGetter) new MemberGetEmitter( callInfo ).GetDelegate(); } #endregion #region Field Lookup (Single) /// <summary> /// Gets the field identified by <paramref name="name"/> on the given <paramref name="type"/>. This method /// searches for public and non-public instance fields on both the type itself and all parent classes. /// </summary> /// <returns>A single FieldInfo instance of the first found match or null if no match was found.</returns> public static FieldInfo Field( this Type type, string name ) { return type.Field( name, Flags.InstanceAnyVisibility ); } /// <summary> /// Gets the field identified by <paramref name="name"/> on the given <paramref name="type"/>. /// Use the <paramref name="bindingFlags"/> parameter to define the scope of the search. /// </summary> /// <returns>A single FieldInfo instance of the first found match or null if no match was found.</returns> public static FieldInfo Field( this Type type, string name, Flags bindingFlags ) { // we need to check all fields to do partial name matches if( bindingFlags.IsAnySet( Flags.PartialNameMatch | Flags.TrimExplicitlyImplemented ) ) { return type.Fields( bindingFlags, name ).FirstOrDefault(); } var result = type.GetField( name, bindingFlags ); if( result == null && bindingFlags.IsNotSet( Flags.DeclaredOnly ) ) { if( type.BaseType != typeof(object) && type.BaseType != null ) { return type.BaseType.Field( name, bindingFlags ); } } bool hasSpecialFlags = bindingFlags.IsAnySet( Flags.ExcludeBackingMembers | Flags.ExcludeExplicitlyImplemented | Flags.ExcludeHiddenMembers ); if( hasSpecialFlags ) { IList<FieldInfo> fields = new List<FieldInfo> { result }; fields = fields.Filter( bindingFlags ); return fields.Count > 0 ? fields[ 0 ] : null; } return result; } #endregion #region Field Lookup (Multiple) /// <summary> /// Gets all public and non-public instance fields on the given <paramref name="type"/>, /// including fields defined on base types. /// </summary> /// <param name="type">The type on which to reflect.</param> /// <param name="names">The optional list of names against which to filter the result. If this parameter is /// <c>null</c> or empty no name filtering will be applied. This method will check for an exact, /// case-sensitive match.</param> /// <returns>A list of all instance fields on the type. This value will never be null.</returns> public static IList<FieldInfo> Fields( this Type type, params string[] names ) { return type.Fields( Flags.InstanceAnyVisibility, names ); } /// <summary> /// Gets all fields on the given <paramref name="type"/> that match the specified <paramref name="bindingFlags"/>. /// </summary> /// <param name="type">The type on which to reflect.</param> /// <param name="bindingFlags">The <see cref="BindingFlags"/> or <see cref="Flags"/> combination used to define /// the search behavior and result filtering.</param> /// <param name="names">The optional list of names against which to filter the result. If this parameter is /// <c>null</c> or empty no name filtering will be applied. The default behavior is to check for an exact, /// case-sensitive match. Pass <see href="Flags.ExcludeExplicitlyImplemented"/> to exclude explicitly implemented /// interface members, <see href="Flags.PartialNameMatch"/> to locate by substring, and /// <see href="Flags.IgnoreCase"/> to ignore case.</param> /// <returns>A list of all matching fields on the type. This value will never be null.</returns> public static IList<FieldInfo> Fields( this Type type, Flags bindingFlags, params string[] names ) { if( type == null || type == typeof(object) ) { return new FieldInfo[0]; } bool recurse = bindingFlags.IsNotSet( Flags.DeclaredOnly ); bool hasNames = names != null && names.Length > 0; bool hasSpecialFlags = bindingFlags.IsAnySet( Flags.ExcludeBackingMembers | Flags.ExcludeExplicitlyImplemented | Flags.ExcludeHiddenMembers ); if( ! recurse && ! hasNames && ! hasSpecialFlags ) { return type.GetFields( bindingFlags ) ?? new FieldInfo[0]; } var fields = GetFields( type, bindingFlags ); fields = hasSpecialFlags ? fields.Filter( bindingFlags ) : fields; fields = hasNames ? fields.Filter( bindingFlags, names ) : fields; return fields; } private static IList<FieldInfo> GetFields( Type type, Flags bindingFlags ) { bool recurse = bindingFlags.IsNotSet( Flags.DeclaredOnly ); if( ! recurse ) { return type.GetFields( bindingFlags ) ?? new FieldInfo[0]; } bindingFlags |= Flags.DeclaredOnly; bindingFlags &= ~BindingFlags.FlattenHierarchy; var fields = new List<FieldInfo>(); fields.AddRange( type.GetFields( bindingFlags ) ); Type baseType = type.BaseType; while( baseType != null && baseType != typeof(object) ) { fields.AddRange( baseType.GetFields( bindingFlags ) ); baseType = baseType.BaseType; } return fields; } #endregion #region Field Combined #region TryGetValue /// <summary> /// Gets the first (public or non-public) instance field with the given <paramref name="name"/> on the given /// <paramref name="obj"/> object. Returns the value of the field if a match was found and null otherwise. /// </summary> /// <remarks> /// When using this method it is not possible to distinguish between a missing field and a field whose value is null. /// </remarks> /// <param name="obj">The source object on which to find the field</param> /// <param name="name">The name of the field whose value should be retrieved</param> /// <returns>The value of the field or null if no field was found</returns> public static object TryGetFieldValue( this object obj, string name ) { return TryGetFieldValue( obj, name, Flags.InstanceAnyVisibility ); } /// <summary> /// Gets the first field with the given <paramref name="name"/> on the given <paramref name="obj"/> object. /// Returns the value of the field if a match was found and null otherwise. /// Use the <paramref name="bindingFlags"/> parameter to limit the scope of the search. /// </summary> /// <remarks> /// When using this method it is not possible to distinguish between a missing field and a field whose value is null. /// </remarks> /// <param name="obj">The source object on which to find the field</param> /// <param name="name">The name of the field whose value should be retrieved</param> /// <param name="bindingFlags">A combination of Flags that define the scope of the search</param> /// <returns>The value of the field or null if no field was found</returns> public static object TryGetFieldValue( this object obj, string name, Flags bindingFlags ) { try { return obj.GetFieldValue( name, bindingFlags ); } catch( MissingFieldException ) { return null; } } #endregion #region TrySetValue /// <summary> /// Sets the first (public or non-public) instance field with the given <paramref name="name"/> on the /// given <paramref name="obj"/> object to supplied <paramref name="value"/>. Returns true if a value /// was assigned to a field and false otherwise. /// </summary> /// <param name="obj">The source object on which to find the field</param> /// <param name="name">The name of the field whose value should be retrieved</param> /// <param name="value">The value that should be assigned to the field</param> /// <returns>True if the value was assigned to a field and false otherwise</returns> public static bool TrySetFieldValue( this object obj, string name, object value ) { return TrySetFieldValue( obj, name, value, Flags.InstanceAnyVisibility ); } /// <summary> /// Sets the first field with the given <paramref name="name"/> on the given <paramref name="obj"/> object /// to the supplied <paramref name="value"/>. Returns true if a value was assigned to a field and false otherwise. /// Use the <paramref name="bindingFlags"/> parameter to limit the scope of the search. /// </summary> /// <param name="obj">The source object on which to find the field</param> /// <param name="name">The name of the field whose value should be retrieved</param> /// <param name="value">The value that should be assigned to the field</param> /// <param name="bindingFlags">A combination of Flags that define the scope of the search</param> /// <returns>True if the value was assigned to a field and false otherwise</returns> public static bool TrySetFieldValue( this object obj, string name, object value, Flags bindingFlags ) { try { obj.SetFieldValue(name, value, bindingFlags ); return true; } catch( MissingFieldException ) { return false; } } #endregion #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // QuerySettings.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Threading; using System.Threading.Tasks; using System.Diagnostics; namespace System.Linq.Parallel { /// <summary> /// This type contains query execution options specified by the user. /// QuerySettings are used as follows: /// - in the query construction phase, some settings may be uninitialized. /// - at the start of the query opening phase, the WithDefaults method /// is used to initialize all uninitialized settings. /// - in the rest of the query opening phase, we assume that all settings /// have been initialized. /// </summary> internal struct QuerySettings { private TaskScheduler _taskScheduler; private int? _degreeOfParallelism; private CancellationState _cancellationState; private ParallelExecutionMode? _executionMode; private ParallelMergeOptions? _mergeOptions; private int _queryId; internal CancellationState CancellationState { get { return _cancellationState; } set { _cancellationState = value; Debug.Assert(_cancellationState != null); } } // The task manager on which to execute the query. internal TaskScheduler TaskScheduler { get { return _taskScheduler; } set { _taskScheduler = value; } } // The number of parallel tasks to utilize. internal int? DegreeOfParallelism { get { return _degreeOfParallelism; } set { _degreeOfParallelism = value; } } // The mode in which to execute this query. internal ParallelExecutionMode? ExecutionMode { get { return _executionMode; } set { _executionMode = value; } } internal ParallelMergeOptions? MergeOptions { get { return _mergeOptions; } set { _mergeOptions = value; } } internal int QueryId { get { return _queryId; } } //----------------------------------------------------------------------------------- // Constructs a new settings structure. // internal QuerySettings(TaskScheduler taskScheduler, int? degreeOfParallelism, CancellationToken externalCancellationToken, ParallelExecutionMode? executionMode, ParallelMergeOptions? mergeOptions) { _taskScheduler = taskScheduler; _degreeOfParallelism = degreeOfParallelism; _cancellationState = new CancellationState(externalCancellationToken); _executionMode = executionMode; _mergeOptions = mergeOptions; _queryId = -1; Debug.Assert(_cancellationState != null); } //----------------------------------------------------------------------------------- // Combines two sets of options. // internal QuerySettings Merge(QuerySettings settings2) { if (this.TaskScheduler != null && settings2.TaskScheduler != null) { throw new InvalidOperationException(SR.ParallelQuery_DuplicateTaskScheduler); } if (this.DegreeOfParallelism != null && settings2.DegreeOfParallelism != null) { throw new InvalidOperationException(SR.ParallelQuery_DuplicateDOP); } if (this.CancellationState.ExternalCancellationToken.CanBeCanceled && settings2.CancellationState.ExternalCancellationToken.CanBeCanceled) { throw new InvalidOperationException(SR.ParallelQuery_DuplicateWithCancellation); } if (this.ExecutionMode != null && settings2.ExecutionMode != null) { throw new InvalidOperationException(SR.ParallelQuery_DuplicateExecutionMode); } if (this.MergeOptions != null && settings2.MergeOptions != null) { throw new InvalidOperationException(SR.ParallelQuery_DuplicateMergeOptions); } TaskScheduler tm = (this.TaskScheduler == null) ? settings2.TaskScheduler : this.TaskScheduler; int? dop = this.DegreeOfParallelism.HasValue ? this.DegreeOfParallelism : settings2.DegreeOfParallelism; CancellationToken externalCancellationToken = (this.CancellationState.ExternalCancellationToken.CanBeCanceled) ? this.CancellationState.ExternalCancellationToken : settings2.CancellationState.ExternalCancellationToken; ParallelExecutionMode? executionMode = this.ExecutionMode.HasValue ? this.ExecutionMode : settings2.ExecutionMode; ParallelMergeOptions? mergeOptions = this.MergeOptions.HasValue ? this.MergeOptions : settings2.MergeOptions; return new QuerySettings(tm, dop, externalCancellationToken, executionMode, mergeOptions); } internal QuerySettings WithPerExecutionSettings() { return WithPerExecutionSettings(new CancellationTokenSource(), new Shared<bool>(false)); } internal QuerySettings WithPerExecutionSettings(CancellationTokenSource topLevelCancellationTokenSource, Shared<bool> topLevelDisposedFlag) { //Initialize a new QuerySettings structure and copy in the current settings. //Note: this has the very important effect of newing a fresh CancellationSettings, // and _not_ copying in the current internalCancellationSource or topLevelDisposedFlag which should not be // propogated to internal query executions. (This affects SelectMany execution) // The fresh toplevel parameters are used instead. QuerySettings settings = new QuerySettings(TaskScheduler, DegreeOfParallelism, CancellationState.ExternalCancellationToken, ExecutionMode, MergeOptions); Debug.Assert(topLevelCancellationTokenSource != null, "There should always be a top-level cancellation signal specified."); settings.CancellationState.InternalCancellationTokenSource = topLevelCancellationTokenSource; //Merge internal and external tokens to form the combined token settings.CancellationState.MergedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(settings.CancellationState.InternalCancellationTokenSource.Token, settings.CancellationState.ExternalCancellationToken); // and copy in the topLevelDisposedFlag settings.CancellationState.TopLevelDisposedFlag = topLevelDisposedFlag; Debug.Assert(settings.CancellationState.InternalCancellationTokenSource != null); Debug.Assert(settings.CancellationState.MergedCancellationToken.CanBeCanceled); Debug.Assert(settings.CancellationState.TopLevelDisposedFlag != null); // Finally, assign a query Id to the settings settings._queryId = PlinqEtwProvider.NextQueryId(); return settings; } //----------------------------------------------------------------------------------- // Copies the settings, replacing unspecified settings with defaults. // internal QuerySettings WithDefaults() { QuerySettings settings = this; if (settings.TaskScheduler == null) { settings.TaskScheduler = TaskScheduler.Default; } if (settings.DegreeOfParallelism == null) { settings.DegreeOfParallelism = Scheduling.GetDefaultDegreeOfParallelism(); } if (settings.ExecutionMode == null) { settings.ExecutionMode = ParallelExecutionMode.Default; } if (settings.MergeOptions == null) { settings.MergeOptions = ParallelMergeOptions.Default; } if (settings.MergeOptions == ParallelMergeOptions.Default) { settings.MergeOptions = ParallelMergeOptions.AutoBuffered; } Debug.Assert(settings.TaskScheduler != null); Debug.Assert(settings.DegreeOfParallelism.HasValue); Debug.Assert(settings.DegreeOfParallelism.Value >= 1 && settings.DegreeOfParallelism <= Scheduling.MAX_SUPPORTED_DOP); Debug.Assert(settings.ExecutionMode != null); Debug.Assert(settings.MergeOptions != null); Debug.Assert(settings.MergeOptions != ParallelMergeOptions.Default); return settings; } // Returns the default settings internal static QuerySettings Empty { get { return new QuerySettings(null, null, new CancellationToken(), null, null); } } // Cleanup internal state once the entire query is complete. // (this should not be performed after a 'premature-query' completes as the state should live // uninterrupted for the duration of the full query.) public void CleanStateAtQueryEnd() { _cancellationState.MergedCancellationTokenSource.Dispose(); } } }
// // Copyright 2013-2014 Frank A. Krueger // // 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.Linq.Expressions; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Diagnostics; using System.ComponentModel; using Core; namespace Praeclarum.Bind { /// <summary> /// Abstract class that represents bindings between values in an applications. /// Binding are created using Create and removed by calling Unbind. /// </summary> public abstract class Binding { /// <summary> /// Unbind this instance. This cannot be undone. /// </summary> public virtual void Unbind () { } /// <summary> /// Uses the lambda expression to create data bindings. /// Equality expression (==) become data bindings. /// And expressions (&&) can be used to group the data bindings. /// </summary> /// <param name="specifications">The binding specifications.</param> public static Binding Create<T> (Expression<Func<T>> specifications) { return BindExpression (specifications.Body); } public static Binding Create<T> (Expression<Func<T>> specifications, IValueConverter converter) { return BindExpression (specifications.Body); } static Binding BindExpression (Expression expr) { // // Is this a group of bindings // if (expr.NodeType == ExpressionType.AndAlso) { var b = (BinaryExpression)expr; var parts = new List<Expression> (); while (b != null) { var l = b.Left; parts.Add (b.Right); if (l.NodeType == ExpressionType.AndAlso) { b = (BinaryExpression)l; } else { parts.Add (l); b = null; } } parts.Reverse (); return new MultipleBindings (parts.Select (BindExpression)); } // // Are we binding two values? // if (expr.NodeType == ExpressionType.Equal) { var b = (BinaryExpression)expr; return new EqualityBinding (b.Left, b.Right); } // // This must be a new object binding (a template) // throw new NotSupportedException ("Only equality bindings are supported."); } protected static bool SetValue (Expression expr, object value, int changeId) { if (expr.NodeType == ExpressionType.MemberAccess) { var m = (MemberExpression)expr; var mem = m.Member; var target = Evaluator.EvalExpression (m.Expression); var f = mem as FieldInfo; var p = mem as PropertyInfo; if (f != null) { f.SetValue (target, value); } else if (p != null) { p.SetValue (target, value, null); } else { ReportError ("Trying to SetValue on " + mem.GetType () + " member"); return false; } InvalidateMember (target, mem, changeId); return true; } ReportError ("Trying to SetValue on " + expr.NodeType + " expression"); return false; } public static event Action<string> Error = delegate {}; static void ReportError (string message) { Debug.WriteLine (message); Error (message); } static void ReportError (object errorObject) { ReportError (errorObject.ToString ()); } #region Change Notification class MemberActions { readonly object target; readonly MemberInfo member; EventInfo eventInfo; Delegate eventHandler; public MemberActions (object target, MemberInfo mem) { this.target = target; member = mem; } void AddChangeNotificationEventHandler () { if (target != null) { var npc = target as INotifyPropertyChanged; if (npc != null && (member is PropertyInfo)) { npc.PropertyChanged += HandleNotifyPropertyChanged; } else { AddHandlerForFirstExistingEvent (member.Name + "Changed", "EditingDidEnd", "ValueChanged", "Changed"); // if (!added) { // Debug.WriteLine ("Failed to bind to change event for " + target); // } } } } bool AddHandlerForFirstExistingEvent (params string[] names) { var type = target.GetType (); foreach (var name in names) { var ev = GetEvent (type, name); if (ev != null) { eventInfo = ev; var isClassicHandler = typeof(EventHandler).GetTypeInfo ().IsAssignableFrom (ev.EventHandlerType.GetTypeInfo ()); eventHandler = isClassicHandler ? (EventHandler)HandleAnyEvent : CreateGenericEventHandler (ev, () => HandleAnyEvent (null, EventArgs.Empty)); ev.AddEventHandler(target, eventHandler); Debug.WriteLine ("BIND: Added handler for {0} on {1}", eventInfo.Name, target); return true; } } return false; } static EventInfo GetEvent (Type type, string eventName) { var t = type; while (t != null && t != typeof(object)) { var ti = t.GetTypeInfo (); var ev = t.GetTypeInfo ().GetDeclaredEvent (eventName); if (ev != null) return ev; t = ti.BaseType; } return null; } static Delegate CreateGenericEventHandler (EventInfo evt, Action d) { var handlerType = evt.EventHandlerType; var handlerTypeInfo = handlerType.GetTypeInfo (); var handlerInvokeInfo = handlerTypeInfo.GetDeclaredMethod ("Invoke"); var eventParams = handlerInvokeInfo.GetParameters(); //lambda: (object x0, EventArgs x1) => d() var parameters = eventParams.Select(p => Expression.Parameter(p.ParameterType, p.Name)).ToArray (); var body = Expression.Call(Expression.Constant(d), d.GetType().GetTypeInfo ().GetDeclaredMethod ("Invoke")); var lambda = Expression.Lambda(body, parameters); var delegateInvokeInfo = lambda.Compile ().GetMethodInfo (); return delegateInvokeInfo.CreateDelegate (handlerType, null); } void UnsubscribeFromChangeNotificationEvent () { var npc = target as INotifyPropertyChanged; if (npc != null && (member is PropertyInfo)) { npc.PropertyChanged -= HandleNotifyPropertyChanged; return; } if (eventInfo == null) return; eventInfo.RemoveEventHandler (target, eventHandler); Debug.WriteLine ("BIND: Removed handler for {0} on {1}", eventInfo.Name, target); eventInfo = null; eventHandler = null; } void HandleNotifyPropertyChanged (object sender, PropertyChangedEventArgs e) { if (e.PropertyName == member.Name) Binding.InvalidateMember (target, member); } void HandleAnyEvent (object sender, EventArgs e) { Binding.InvalidateMember (target, member); } readonly List<MemberChangeAction> actions = new List<MemberChangeAction> (); /// <summary> /// Add the specified action to be executed when Notify() is called. /// </summary> /// <param name="action">Action.</param> public void AddAction (MemberChangeAction action) { if (actions.Count == 0) { AddChangeNotificationEventHandler (); } actions.Add (action); } public void RemoveAction (MemberChangeAction action) { actions.Remove (action); if (actions.Count == 0) { UnsubscribeFromChangeNotificationEvent (); } } /// <summary> /// Execute all the actions. /// </summary> /// <param name="changeId">Change identifier.</param> public void Notify (int changeId) { foreach (var s in actions) { s.Notify (changeId); } } } static readonly Dictionary<Tuple<Object, MemberInfo>, MemberActions> objectSubs = new Dictionary<Tuple<Object, MemberInfo>, MemberActions> (); internal static MemberChangeAction AddMemberChangeAction (object target, MemberInfo member, Action<int> k) { var key = Tuple.Create (target, member); MemberActions subs; if (!objectSubs.TryGetValue (key, out subs)) { subs = new MemberActions (target, member); objectSubs.Add (key, subs); } // Debug.WriteLine ("ADD CHANGE ACTION " + target + " " + member); var sub = new MemberChangeAction (target, member, k); subs.AddAction (sub); return sub; } internal static void RemoveMemberChangeAction (MemberChangeAction sub) { var key = Tuple.Create (sub.Target, sub.Member); MemberActions subs; if (objectSubs.TryGetValue (key, out subs)) { // Debug.WriteLine ("REMOVE CHANGE ACTION " + sub.Target + " " + sub.Member); subs.RemoveAction (sub); } } /// <summary> /// Invalidate the specified object member. This will cause all actions /// associated with that member to be executed. /// This is the main mechanism by which binding values are distributed. /// </summary> /// <param name="target">Target object</param> /// <param name="member">Member of the object that changed</param> /// <param name="changeId">Change identifier</param> public static void InvalidateMember (object target, MemberInfo member, int changeId = 0) { var key = Tuple.Create (target, member); MemberActions subs; if (objectSubs.TryGetValue (key, out subs)) { // Debug.WriteLine ("INVALIDATE {0} {1}", target, member.Name); subs.Notify (changeId); } } #endregion } /// <summary> /// An action tied to a particular member of an object. /// When Notify is called, the action is executed. /// </summary> class MemberChangeAction { readonly Action<int> action; public object Target { get; private set; } public MemberInfo Member { get; private set; } public MemberChangeAction (object target, MemberInfo member, Action<int> action) { Target = target; if (member == null) throw new ArgumentNullException ("member"); Member = member; if (action == null) throw new ArgumentNullException ("action"); this.action = action; } public void Notify (int changeId) { action (changeId); } } /// <summary> /// Methods that can evaluate Linq expressions. /// </summary> static class Evaluator { /// <summary> /// Gets the value of a Linq expression. /// </summary> /// <param name="expr">The expresssion.</param> public static object EvalExpression (Expression expr) { // // Easy case // if (expr.NodeType == ExpressionType.Constant) { return ((ConstantExpression)expr).Value; } // // General case // // Debug.WriteLine ("WARNING EVAL COMPILED {0}", expr); var lambda = Expression.Lambda (expr, Enumerable.Empty<ParameterExpression> ()); return lambda.Compile ().DynamicInvoke (); } } /// <summary> /// Binding between two values. When one changes, the other /// is set. /// </summary> class EqualityBinding : Binding { object Value; class Trigger { public Expression Expression; public MemberInfo Member; public MemberChangeAction ChangeAction; } readonly List<Trigger> leftTriggers = new List<Trigger> (); readonly List<Trigger> rightTriggers = new List<Trigger> (); public EqualityBinding (Expression left, Expression right) { // Try evaling the right and assigning left Value = Evaluator.EvalExpression (right); var leftSet = SetValue (left, Value, nextChangeId); // If that didn't work, then try the other direction if (!leftSet) { Value = Evaluator.EvalExpression (left); SetValue (right, Value, nextChangeId); } nextChangeId++; CollectTriggers (left, leftTriggers); CollectTriggers (right, rightTriggers); Resubscribe (leftTriggers, left, right); Resubscribe (rightTriggers, right, left); } public override void Unbind () { Unsubscribe (leftTriggers); Unsubscribe (rightTriggers); base.Unbind (); } void Resubscribe (List<Trigger> triggers, Expression expr, Expression dependentExpr) { Unsubscribe (triggers); Subscribe (triggers, changeId => OnSideChanged (expr, dependentExpr, changeId)); } int nextChangeId = 1; readonly HashSet<int> activeChangeIds = new HashSet<int> (); void OnSideChanged (Expression expr, Expression dependentExpr, int causeChangeId) { if (activeChangeIds.Contains (causeChangeId)) return; var v = Evaluator.EvalExpression (expr); if (v == null && Value == null) return; if ((v == null && Value != null) || (v != null && Value == null) || ((v is IComparable) && ((IComparable)v).CompareTo (Value) != 0)) { Value = v; var changeId = nextChangeId++; activeChangeIds.Add (changeId); SetValue (dependentExpr, v, changeId); activeChangeIds.Remove (changeId); } // else { // Debug.WriteLine ("Prevented needless update"); // } } static void Unsubscribe (List<Trigger> triggers) { foreach (var t in triggers) { if (t.ChangeAction != null) { RemoveMemberChangeAction (t.ChangeAction); } } } static void Subscribe (List<Trigger> triggers, Action<int> action) { foreach (var t in triggers) { t.ChangeAction = AddMemberChangeAction (Evaluator.EvalExpression (t.Expression), t.Member, action); } } void CollectTriggers (Expression s, List<Trigger> triggers) { if (s.NodeType == ExpressionType.MemberAccess) { var m = (MemberExpression)s; CollectTriggers (m.Expression, triggers); var t = new Trigger { Expression = m.Expression, Member = m.Member }; triggers.Add (t); } else { var b = s as BinaryExpression; if (b != null) { CollectTriggers (b.Left, triggers); CollectTriggers (b.Right, triggers); } } } } /// <summary> /// Multiple bindings grouped under a single binding to make adding and removing easier. /// </summary> class MultipleBindings : Binding { readonly List<Binding> bindings; public MultipleBindings (IEnumerable<Binding> bindings) { this.bindings = bindings.Where (x => x != null).ToList (); } public override void Unbind () { base.Unbind (); foreach (var b in bindings) { b.Unbind (); } bindings.Clear (); } } #if __IOS__ [MonoTouch.Foundation.Preserve] static class PreserveEventsAndSettersHack { [MonoTouch.Foundation.Preserve] static void Hack () { var l = new MonoTouch.UIKit.UILabel (); l.Text = l.Text + ""; var tf = new MonoTouch.UIKit.UITextField (); tf.Text = tf.Text + ""; tf.EditingDidEnd += delegate {}; tf.ValueChanged += delegate {}; var vc = new MonoTouch.UIKit.UIViewController (); vc.Title = vc.Title + ""; vc.Editing = !vc.Editing; } } #endif }
// 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.Diagnostics; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using Microsoft.Win32.SafeHandles; namespace Internal.Cryptography.Pal { internal class OpenSslX509Encoder : IX509Pal { public AsymmetricAlgorithm DecodePublicKey(Oid oid, byte[] encodedKeyValue, byte[] encodedParameters) { switch (oid.Value) { case Oids.RsaRsa: return BuildRsaPublicKey(encodedKeyValue); } // NotSupportedException is what desktop and CoreFx-Windows throw in this situation. throw new NotSupportedException(SR.NotSupported_KeyAlgorithm); } public unsafe string X500DistinguishedNameDecode(byte[] encodedDistinguishedName, X500DistinguishedNameFlags flag) { using (SafeX509NameHandle x509Name = Interop.libcrypto.OpenSslD2I(Interop.libcrypto.d2i_X509_NAME, encodedDistinguishedName)) { Interop.libcrypto.CheckValidOpenSslHandle(x509Name); using (SafeBioHandle bioHandle = Interop.libcrypto.BIO_new(Interop.libcrypto.BIO_s_mem())) { Interop.libcrypto.CheckValidOpenSslHandle(bioHandle); OpenSslX09NameFormatFlags nativeFlags = ConvertFormatFlags(flag); int written = Interop.libcrypto.X509_NAME_print_ex( bioHandle, x509Name, 0, new UIntPtr((uint)nativeFlags)); // X509_NAME_print_ex returns how many bytes were written into the buffer. // BIO_gets wants to ensure that the response is NULL-terminated. // So add one to leave space for the NULL. StringBuilder builder = new StringBuilder(written + 1); int read = Interop.libcrypto.BIO_gets(bioHandle, builder, builder.Capacity); if (read < 0) { throw Interop.libcrypto.CreateOpenSslCryptographicException(); } return builder.ToString(); } } } public byte[] X500DistinguishedNameEncode(string distinguishedName, X500DistinguishedNameFlags flag) { throw new NotImplementedException(); } public string X500DistinguishedNameFormat(byte[] encodedDistinguishedName, bool multiLine) { throw new NotImplementedException(); } public X509ContentType GetCertContentType(byte[] rawData) { throw new NotImplementedException(); } public X509ContentType GetCertContentType(string fileName) { throw new NotImplementedException(); } public byte[] EncodeX509KeyUsageExtension(X509KeyUsageFlags keyUsages) { throw new NotImplementedException(); } public unsafe void DecodeX509KeyUsageExtension(byte[] encoded, out X509KeyUsageFlags keyUsages) { using (SafeAsn1BitStringHandle bitString = Interop.libcrypto.OpenSslD2I(Interop.libcrypto.d2i_ASN1_BIT_STRING, encoded)) { Interop.libcrypto.CheckValidOpenSslHandle(bitString); byte[] decoded = Interop.NativeCrypto.GetAsn1StringBytes(bitString.DangerousGetHandle()); // Only 9 bits are defined. if (decoded.Length > 2) { throw new CryptographicException(); } // DER encodings of BIT_STRING values number the bits as // 01234567 89 (big endian), plus a number saying how many bits of the last byte were padding. // // So digitalSignature (0) doesn't mean 2^0 (0x01), it means the most significant bit // is set in this byte stream. // // BIT_STRING values are compact. So a value of cRLSign (6) | keyEncipherment (2), which // is 0b0010001 => 0b0010 0010 (1 bit padding) => 0x22 encoded is therefore // 0x02 (length remaining) 0x01 (1 bit padding) 0x22. // // OpenSSL's d2i_ASN1_BIT_STRING is going to take that, and return 0x22. 0x22 lines up // exactly with X509KeyUsageFlags.CrlSign (0x20) | X509KeyUsageFlags.KeyEncipherment (0x02) // // Once the decipherOnly (8) bit is added to the mix, the values become: // 0b001000101 => 0b0010 0010 1000 0000 (7 bits padding) // { 0x03 0x07 0x22 0x80 } // And OpenSSL returns new byte[] { 0x22 0x80 } // // The value of X509KeyUsageFlags.DecipherOnly is 0x8000. 0x8000 in a little endian // representation is { 0x00 0x80 }. This means that the DER storage mechanism has effectively // ended up being little-endian for BIT_STRING values. Untwist the bytes, and now the bits all // line up with the existing X509KeyUsageFlags. int value = 0; if (decoded.Length > 0) { value = decoded[0]; } if (decoded.Length > 1) { value |= decoded[1] << 8; } keyUsages = (X509KeyUsageFlags)value; } } public byte[] EncodeX509BasicConstraints2Extension( bool certificateAuthority, bool hasPathLengthConstraint, int pathLengthConstraint) { throw new NotImplementedException(); } public void DecodeX509BasicConstraintsExtension( byte[] encoded, out bool certificateAuthority, out bool hasPathLengthConstraint, out int pathLengthConstraint) { throw new NotImplementedException(); } public unsafe void DecodeX509BasicConstraints2Extension( byte[] encoded, out bool certificateAuthority, out bool hasPathLengthConstraint, out int pathLengthConstraint) { using (SafeBasicConstraintsHandle constraints = Interop.libcrypto.OpenSslD2I(Interop.libcrypto.d2i_BASIC_CONSTRAINTS, encoded)) { Interop.libcrypto.CheckValidOpenSslHandle(constraints); Interop.libcrypto.BASIC_CONSTRAINTS* data = (Interop.libcrypto.BASIC_CONSTRAINTS*)constraints.DangerousGetHandle(); certificateAuthority = data->CA != 0; if (data->pathlen != IntPtr.Zero) { hasPathLengthConstraint = true; pathLengthConstraint = Interop.libcrypto.ASN1_INTEGER_get(data->pathlen).ToInt32(); } else { hasPathLengthConstraint = false; pathLengthConstraint = 0; } } } public byte[] EncodeX509EnhancedKeyUsageExtension(OidCollection usages) { throw new NotImplementedException(); } public unsafe void DecodeX509EnhancedKeyUsageExtension(byte[] encoded, out OidCollection usages) { OidCollection oids = new OidCollection(); using (SafeEkuExtensionHandle eku = Interop.libcrypto.OpenSslD2I(Interop.libcrypto.d2i_EXTENDED_KEY_USAGE, encoded)) { Interop.libcrypto.CheckValidOpenSslHandle(eku); int count = Interop.NativeCrypto.GetX509EkuFieldCount(eku); for (int i = 0; i < count; i++) { IntPtr oidPtr = Interop.NativeCrypto.GetX509EkuField(eku, i); if (oidPtr == IntPtr.Zero) { throw Interop.libcrypto.CreateOpenSslCryptographicException(); } string oidValue = Interop.libcrypto.OBJ_obj2txt_helper(oidPtr); oids.Add(new Oid(oidValue)); } } usages = oids; } public byte[] EncodeX509SubjectKeyIdentifierExtension(byte[] subjectKeyIdentifier) { throw new NotImplementedException(); } public unsafe void DecodeX509SubjectKeyIdentifierExtension(byte[] encoded, out byte[] subjectKeyIdentifier) { using (SafeAsn1OctetStringHandle octetString = Interop.libcrypto.OpenSslD2I(Interop.libcrypto.d2i_ASN1_OCTET_STRING, encoded)) { Interop.libcrypto.CheckValidOpenSslHandle(octetString); subjectKeyIdentifier = Interop.NativeCrypto.GetAsn1StringBytes(octetString.DangerousGetHandle()); } } public byte[] ComputeCapiSha1OfPublicKey(PublicKey key) { throw new NotImplementedException(); } private static OpenSslX09NameFormatFlags ConvertFormatFlags(X500DistinguishedNameFlags inFlags) { OpenSslX09NameFormatFlags outFlags = 0; if (inFlags.HasFlag(X500DistinguishedNameFlags.Reversed)) { outFlags |= OpenSslX09NameFormatFlags.XN_FLAG_DN_REV; } if (inFlags.HasFlag(X500DistinguishedNameFlags.UseSemicolons)) { outFlags |= OpenSslX09NameFormatFlags.XN_FLAG_SEP_SPLUS_SPC; } else if (inFlags.HasFlag(X500DistinguishedNameFlags.UseNewLines)) { outFlags |= OpenSslX09NameFormatFlags.XN_FLAG_SEP_MULTILINE; } else { outFlags |= OpenSslX09NameFormatFlags.XN_FLAG_SEP_CPLUS_SPC; } if (inFlags.HasFlag(X500DistinguishedNameFlags.DoNotUseQuotes)) { // TODO: Handle this. } if (inFlags.HasFlag(X500DistinguishedNameFlags.ForceUTF8Encoding)) { // TODO: Handle this. } if (inFlags.HasFlag(X500DistinguishedNameFlags.UseUTF8Encoding)) { // TODO: Handle this. } else if (inFlags.HasFlag(X500DistinguishedNameFlags.UseT61Encoding)) { // TODO: Handle this. } return outFlags; } private static unsafe RSA BuildRsaPublicKey(byte[] encodedData) { using (SafeRsaHandle rsaHandle = Interop.libcrypto.OpenSslD2I(Interop.libcrypto.d2i_RSAPublicKey, encodedData)) { Interop.libcrypto.CheckValidOpenSslHandle(rsaHandle); RSAParameters rsaParameters = Interop.libcrypto.ExportRsaParameters(rsaHandle, false); RSA rsa = new RSAOpenSsl(); rsa.ImportParameters(rsaParameters); return rsa; } } [Flags] private enum OpenSslX09NameFormatFlags : uint { XN_FLAG_SEP_MASK = (0xf << 16), // O=Apache HTTP Server, OU=Test Certificate, CN=localhost // Note that this is the only not-reversed value, since XN_FLAG_COMPAT | XN_FLAG_DN_REV produces nothing. XN_FLAG_COMPAT = 0, // CN=localhost,OU=Test Certificate,O=Apache HTTP Server XN_FLAG_SEP_COMMA_PLUS = (1 << 16), // CN=localhost, OU=Test Certificate, O=Apache HTTP Server XN_FLAG_SEP_CPLUS_SPC = (2 << 16), // CN=localhost; OU=Test Certificate; O=Apache HTTP Server XN_FLAG_SEP_SPLUS_SPC = (3 << 16), // CN=localhost // OU=Test Certificate // O=Apache HTTP Server XN_FLAG_SEP_MULTILINE = (4 << 16), XN_FLAG_DN_REV = (1 << 20), XN_FLAG_FN_MASK = (0x3 << 21), // CN=localhost, OU=Test Certificate, O=Apache HTTP Server XN_FLAG_FN_SN = 0, // commonName=localhost, organizationalUnitName=Test Certificate, organizationName=Apache HTTP Server XN_FLAG_FN_LN = (1 << 21), // 2.5.4.3=localhost, 2.5.4.11=Test Certificate, 2.5.4.10=Apache HTTP Server XN_FLAG_FN_OID = (2 << 21), // localhost, Test Certificate, Apache HTTP Server XN_FLAG_FN_NONE = (3 << 21), // CN = localhost, OU = Test Certificate, O = Apache HTTP Server XN_FLAG_SPC_EQ = (1 << 23), XN_FLAG_DUMP_UNKNOWN_FIELDS = (1 << 24), XN_FLAG_FN_ALIGN = (1 << 25), } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Input; using System.Windows.Markup; using JetBrains.Annotations; using MahApps.Metro.ValueBoxes; namespace MahApps.Metro.Controls { /// <summary> /// Represents a base-class for time picking. /// </summary> [TemplatePart(Name = ElementButton, Type = typeof(Button))] [TemplatePart(Name = ElementHourHand, Type = typeof(UIElement))] [TemplatePart(Name = ElementHourPicker, Type = typeof(Selector))] [TemplatePart(Name = ElementMinuteHand, Type = typeof(UIElement))] [TemplatePart(Name = ElementSecondHand, Type = typeof(UIElement))] [TemplatePart(Name = ElementSecondPicker, Type = typeof(Selector))] [TemplatePart(Name = ElementMinutePicker, Type = typeof(Selector))] [TemplatePart(Name = ElementAmPmSwitcher, Type = typeof(Selector))] [TemplatePart(Name = ElementTextBox, Type = typeof(DatePickerTextBox))] [TemplatePart(Name = ElementPopup, Type = typeof(Popup))] [DefaultEvent("SelectedDateTimeChanged")] public abstract class TimePickerBase : Control { private const string ElementAmPmSwitcher = "PART_AmPmSwitcher"; private const string ElementButton = "PART_Button"; private const string ElementHourHand = "PART_HourHand"; private const string ElementHourPicker = "PART_HourPicker"; private const string ElementMinuteHand = "PART_MinuteHand"; private const string ElementMinutePicker = "PART_MinutePicker"; private const string ElementPopup = "PART_Popup"; private const string ElementSecondHand = "PART_SecondHand"; private const string ElementSecondPicker = "PART_SecondPicker"; private const string ElementTextBox = "PART_TextBox"; private Selector? ampmSwitcher; private Button? dropDownButton; private bool deactivateRangeBaseEvent; private bool deactivateTextChangedEvent; private bool textInputChanged; private UIElement? hourHand; protected Selector? hourInput; private UIElement? minuteHand; private Selector? minuteInput; private Popup? popUp; private bool disablePopupReopen; private UIElement? secondHand; private Selector? secondInput; protected DatePickerTextBox? textBox; protected DateTime? originalSelectedDateTime; /// <summary> /// This list contains values from 0 to 55 with an interval of 5. It can be used to bind to <see cref="SourceMinutes"/> and <see cref="SourceSeconds"/>. /// </summary> /// <example> /// <code>&lt;MahApps:TimePicker SourceSeconds="{x:Static MahApps:TimePickerBase.IntervalOf5}" /&gt;</code> /// <code>&lt;MahApps:DateTimePicker SourceSeconds="{x:Static MahApps:TimePickerBase.IntervalOf5}" /&gt;</code> /// </example> /// <returns> /// Returns a list containing {0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55}. /// </returns> public static readonly IEnumerable<int> IntervalOf5 = CreateValueList(5); /// <summary> /// This list contains values from 0 to 50 with an interval of 10. It can be used to bind to <see cref="SourceMinutes"/> and <see cref="SourceSeconds"/>. /// </summary> /// <example> /// <code>&lt;MahApps:TimePicker SourceSeconds="{x:Static MahApps:TimePickerBase.IntervalOf10}" /&gt;</code> /// <code>&lt;MahApps:DateTimePicker SourceSeconds="{x:Static MahApps:TimePickerBase.IntervalOf10}" /&gt;</code> /// </example> /// <returns> /// Returns a list containing {0, 10, 20, 30, 40, 50}. /// </returns> public static readonly IEnumerable<int> IntervalOf10 = CreateValueList(10); /// <summary> /// This list contains values from 0 to 45 with an interval of 15. It can be used to bind to <see cref="SourceMinutes"/> and <see cref="SourceSeconds"/>. /// </summary> /// <example> /// <code>&lt;MahApps:TimePicker SourceSeconds="{x:Static MahApps:TimePickerBase.IntervalOf15}" /&gt;</code> /// <code>&lt;MahApps:DateTimePicker SourceSeconds="{x:Static MahApps:TimePickerBase.IntervalOf15}" /&gt;</code> /// </example> /// <returns> /// Returns a list containing {0, 15, 30, 45}. /// </returns> public static readonly IEnumerable<int> IntervalOf15 = CreateValueList(15); /// <summary>Identifies the <see cref="SourceHours"/> dependency property.</summary> public static readonly DependencyProperty SourceHoursProperty = DependencyProperty.Register(nameof(SourceHours), typeof(IEnumerable<int>), typeof(TimePickerBase), new FrameworkPropertyMetadata(Enumerable.Range(0, 24), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, null, CoerceSourceHours)); [MustUseReturnValue] private static object CoerceSourceHours(DependencyObject d, object? basevalue) { if (d is TimePickerBase timePicker && basevalue is IEnumerable<int> hourList) { if (timePicker.IsMilitaryTime) { if (timePicker.SourceHoursAmPmComparer is not null) { return hourList.Where(i => i > 0 && i <= 12).OrderBy(i => i, timePicker.SourceHoursAmPmComparer); } return hourList.Where(i => i > 0 && i <= 12); } return hourList.Where(i => i >= 0 && i < 24); } return Enumerable.Empty<int>(); } /// <summary> /// Gets or sets a collection used to generate the content for selecting the hours. /// </summary> /// <returns> /// A collection that is used to generate the content for selecting the hours. The default is a list of integer from 0 /// to 23 if <see cref="IsMilitaryTime" /> is false or a list of integer from /// 1 to 12 otherwise. /// </returns> [Category("Common")] public IEnumerable<int> SourceHours { get => (IEnumerable<int>)this.GetValue(SourceHoursProperty); set => this.SetValue(SourceHoursProperty, value); } /// <summary>Identifies the <see cref="SourceHoursAmPmComparer"/> dependency property.</summary> public static readonly DependencyProperty SourceHoursAmPmComparerProperty = DependencyProperty.Register(nameof(SourceHoursAmPmComparer), typeof(IComparer<int>), typeof(TimePickerBase), new FrameworkPropertyMetadata(null, OnSourceHoursAmPmComparerPropertyChanged)); private static void OnSourceHoursAmPmComparerPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is TimePickerBase timePicker && e.OldValue != e.NewValue) { timePicker.CoerceValue(SourceHoursProperty); } } /// <summary> /// Gets or sets a comparer for the Am/Pm collection used to generate the content for selecting the hours. /// </summary> [Category("Common")] public IComparer<int>? SourceHoursAmPmComparer { get => (IComparer<int>?)this.GetValue(SourceHoursAmPmComparerProperty); set => this.SetValue(SourceHoursAmPmComparerProperty, value); } /// <summary>Identifies the <see cref="SourceMinutes"/> dependency property.</summary> public static readonly DependencyProperty SourceMinutesProperty = DependencyProperty.Register(nameof(SourceMinutes), typeof(IEnumerable<int>), typeof(TimePickerBase), new FrameworkPropertyMetadata(Enumerable.Range(0, 60), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, null, CoerceSource60)); [MustUseReturnValue] private static object CoerceSource60(DependencyObject d, object? basevalue) { if (basevalue is IEnumerable<int> list) { return list.Where(i => i >= 0 && i < 60); } return Enumerable.Empty<int>(); } /// <summary> /// Gets or sets a collection used to generate the content for selecting the minutes. /// </summary> /// <returns> /// A collection that is used to generate the content for selecting the minutes. The default is a list of int from /// 0 to 59. /// </returns> [Category("Common")] public IEnumerable<int> SourceMinutes { get => (IEnumerable<int>)this.GetValue(SourceMinutesProperty); set => this.SetValue(SourceMinutesProperty, value); } /// <summary>Identifies the <see cref="SourceSeconds"/> dependency property.</summary> public static readonly DependencyProperty SourceSecondsProperty = DependencyProperty.Register(nameof(SourceSeconds), typeof(IEnumerable<int>), typeof(TimePickerBase), new FrameworkPropertyMetadata(Enumerable.Range(0, 60), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, null, CoerceSource60)); /// <summary> /// Gets or sets a collection used to generate the content for selecting the seconds. /// </summary> /// <returns> /// A collection that is used to generate the content for selecting the minutes. The default is a list of int from /// 0 to 59. /// </returns> [Category("Common")] public IEnumerable<int> SourceSeconds { get => (IEnumerable<int>)this.GetValue(SourceSecondsProperty); set => this.SetValue(SourceSecondsProperty, value); } /// <summary>Identifies the <see cref="IsDropDownOpen"/> dependency property.</summary> public static readonly DependencyProperty IsDropDownOpenProperty = DatePicker.IsDropDownOpenProperty.AddOwner(typeof(TimePickerBase), new FrameworkPropertyMetadata(BooleanBoxes.FalseBox, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnIsDropDownOpenChanged, OnCoerceIsDropDownOpen)); [MustUseReturnValue] private static object? OnCoerceIsDropDownOpen(DependencyObject d, object? baseValue) { if (d is TimePickerBase tp && !tp.IsEnabled) { return false; } return baseValue; } /// <summary> /// IsDropDownOpenProperty property changed handler. /// </summary> /// <param name="d">DatePicker that changed its IsDropDownOpen.</param> /// <param name="e">DependencyPropertyChangedEventArgs.</param> private static void OnIsDropDownOpenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is not TimePickerBase tp) { return; } bool newValue = (bool)e.NewValue; if (tp.popUp != null && tp.popUp.IsOpen != newValue) { tp.popUp.IsOpen = newValue; if (newValue) { tp.originalSelectedDateTime = tp.SelectedDateTime; tp.FocusElementAfterIsDropDownOpenChanged(); } } } /// <summary> /// Gets or sets a value indicating whether the drop-down for a <see cref="TimePickerBase"/> box is currently /// open. /// </summary> /// <returns>true if the drop-down is open; otherwise, false. The default is false.</returns> public bool IsDropDownOpen { get => (bool)this.GetValue(IsDropDownOpenProperty); set => this.SetValue(IsDropDownOpenProperty, BooleanBoxes.Box(value)); } /// <summary> /// This method is invoked when the <see cref="IsDropDownOpenProperty"/> changes. /// </summary> protected virtual void FocusElementAfterIsDropDownOpenChanged() { // noting here } /// <summary>Identifies the <see cref="IsClockVisible"/> dependency property.</summary> public static readonly DependencyProperty IsClockVisibleProperty = DependencyProperty.Register(nameof(IsClockVisible), typeof(bool), typeof(TimePickerBase), new PropertyMetadata(BooleanBoxes.TrueBox)); /// <summary> /// Gets or sets a value indicating whether the clock of this control is visible in the user interface (UI). This is a /// dependency property. /// </summary> /// <remarks> /// If this value is set to false then <see cref="Orientation" /> is set to /// <see cref="System.Windows.Controls.Orientation.Vertical" /> /// </remarks> /// <returns> /// true if the clock is visible; otherwise, false. The default value is true. /// </returns> [Category("Appearance")] public bool IsClockVisible { get => (bool)this.GetValue(IsClockVisibleProperty); set => this.SetValue(IsClockVisibleProperty, BooleanBoxes.Box(value)); } /// <summary>Identifies the <see cref="IsReadOnly"/> dependency property.</summary> public static readonly DependencyProperty IsReadOnlyProperty = DependencyProperty.Register(nameof(IsReadOnly), typeof(bool), typeof(TimePickerBase), new PropertyMetadata(BooleanBoxes.FalseBox)); /// <summary> /// Gets or sets a value indicating whether the contents of the <see cref="TimePickerBase" /> are not editable. /// </summary> /// <returns> /// true if the <see cref="TimePickerBase" /> is read-only; otherwise, false. The default is false. /// </returns> public bool IsReadOnly { get => (bool)this.GetValue(IsReadOnlyProperty); set => this.SetValue(IsReadOnlyProperty, BooleanBoxes.Box(value)); } /// <summary>Identifies the <see cref="HandVisibility"/> dependency property.</summary> public static readonly DependencyProperty HandVisibilityProperty = DependencyProperty.Register(nameof(HandVisibility), typeof(TimePartVisibility), typeof(TimePickerBase), new PropertyMetadata(TimePartVisibility.All, OnHandVisibilityChanged)); private static void OnHandVisibilityChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ((TimePickerBase)d).SetHandVisibility((TimePartVisibility)e.NewValue); } /// <summary> /// Gets or sets a value indicating the visibility of the clock hands in the user interface (UI). /// </summary> /// <returns> /// The visibility definition of the clock hands. The default is <see cref="TimePartVisibility.All" />. /// </returns> [Category("Appearance")] [DefaultValue(TimePartVisibility.All)] public TimePartVisibility HandVisibility { get => (TimePartVisibility)this.GetValue(HandVisibilityProperty); set => this.SetValue(HandVisibilityProperty, value); } /// <summary>Identifies the <see cref="Culture"/> dependency property.</summary> public static readonly DependencyProperty CultureProperty = DependencyProperty.Register(nameof(Culture), typeof(CultureInfo), typeof(TimePickerBase), new PropertyMetadata(null, OnCultureChanged)); private static void OnCultureChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var timePartPickerBase = (TimePickerBase)d; timePartPickerBase.Language = e.NewValue is CultureInfo info ? XmlLanguage.GetLanguage(info.IetfLanguageTag) : XmlLanguage.Empty; timePartPickerBase.ApplyCulture(); } /// <summary> /// Gets or sets a value indicating the culture to be used in string formatting operations. /// </summary> [Category("Behavior")] [DefaultValue(null)] public CultureInfo? Culture { get => (CultureInfo?)this.GetValue(CultureProperty); set => this.SetValue(CultureProperty, value); } /// <summary>Identifies the <see cref="PickerVisibility"/> dependency property.</summary> public static readonly DependencyProperty PickerVisibilityProperty = DependencyProperty.Register(nameof(PickerVisibility), typeof(TimePartVisibility), typeof(TimePickerBase), new PropertyMetadata(TimePartVisibility.All, OnPickerVisibilityChanged)); private static void OnPickerVisibilityChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ((TimePickerBase)d).SetPickerVisibility((TimePartVisibility)e.NewValue); } /// <summary> /// Gets or sets a value indicating the visibility of the selectable date-time-parts in the user interface (UI). /// </summary> /// <returns> /// visibility definition of the selectable date-time-parts. The default is <see cref="TimePartVisibility.All" />. /// </returns> [Category("Appearance")] [DefaultValue(TimePartVisibility.All)] public TimePartVisibility PickerVisibility { get => (TimePartVisibility)this.GetValue(PickerVisibilityProperty); set => this.SetValue(PickerVisibilityProperty, value); } public static readonly RoutedEvent SelectedDateTimeChangedEvent = EventManager.RegisterRoutedEvent(nameof(SelectedDateTimeChanged), RoutingStrategy.Bubble, typeof(RoutedPropertyChangedEventHandler<DateTime?>), typeof(TimePickerBase)); /// <summary> /// Occurs when the <see cref="SelectedDateTime" /> property is changed. /// </summary> public event RoutedPropertyChangedEventHandler<DateTime?> SelectedDateTimeChanged { add => this.AddHandler(SelectedDateTimeChangedEvent, value); remove => this.RemoveHandler(SelectedDateTimeChangedEvent, value); } /// <summary>Identifies the <see cref="SelectedDateTime"/> dependency property.</summary> public static readonly DependencyProperty SelectedDateTimeProperty = DependencyProperty.Register(nameof(SelectedDateTime), typeof(DateTime?), typeof(TimePickerBase), new FrameworkPropertyMetadata(default(DateTime?), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnSelectedDateTimeChanged)); private static void OnSelectedDateTimeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var timePartPickerBase = (TimePickerBase)d; if (timePartPickerBase.deactivateRangeBaseEvent) { return; } timePartPickerBase.OnSelectedDateTimeChanged(e.OldValue as DateTime?, e.NewValue as DateTime?); timePartPickerBase.WriteValueToTextBox(); timePartPickerBase.RaiseSelectedDateTimeChangedEvent(e.OldValue as DateTime?, e.NewValue as DateTime?); } /// <summary> /// Gets or sets the currently selected date and time. /// </summary> /// <returns> /// The date and time which is currently selected. The default is null. /// </returns> public DateTime? SelectedDateTime { get => (DateTime?)this.GetValue(SelectedDateTimeProperty); set => this.SetValue(SelectedDateTimeProperty, value); } /// <summary>Identifies the <see cref="SelectedTimeFormat"/> dependency property.</summary> public static readonly DependencyProperty SelectedTimeFormatProperty = DependencyProperty.Register(nameof(SelectedTimeFormat), typeof(TimePickerFormat), typeof(TimePickerBase), new PropertyMetadata(TimePickerFormat.Long, OnSelectedTimeFormatChanged)); /// <summary> /// Gets or sets the format that is used to display the selected time. /// </summary> [Category("Appearance")] [DefaultValue(TimePickerFormat.Long)] public TimePickerFormat SelectedTimeFormat { get => (TimePickerFormat)this.GetValue(SelectedTimeFormatProperty); set => this.SetValue(SelectedTimeFormatProperty, value); } /// <summary>Identifies the <see cref="HoursItemStringFormat"/> dependency property.</summary> public static readonly DependencyProperty HoursItemStringFormatProperty = DependencyProperty.Register(nameof(HoursItemStringFormat), typeof(string), typeof(TimePickerBase), new FrameworkPropertyMetadata(null)); /// <summary> /// Gets or sets a composite string that specifies how to format the hour items. /// </summary> public string? HoursItemStringFormat { get => (string?)this.GetValue(HoursItemStringFormatProperty); set => this.SetValue(HoursItemStringFormatProperty, value); } /// <summary>Identifies the <see cref="MinutesItemStringFormat"/> dependency property.</summary> public static readonly DependencyProperty MinutesItemStringFormatProperty = DependencyProperty.Register(nameof(MinutesItemStringFormat), typeof(string), typeof(TimePickerBase), new FrameworkPropertyMetadata(null)); /// <summary> /// Gets or sets a composite string that specifies how to format the minute items. /// </summary> public string? MinutesItemStringFormat { get => (string?)this.GetValue(MinutesItemStringFormatProperty); set => this.SetValue(MinutesItemStringFormatProperty, value); } /// <summary>Identifies the <see cref="SecondsItemStringFormat"/> dependency property.</summary> public static readonly DependencyProperty SecondsItemStringFormatProperty = DependencyProperty.Register(nameof(SecondsItemStringFormat), typeof(string), typeof(TimePickerBase), new FrameworkPropertyMetadata(null)); /// <summary> /// Gets or sets a composite string that specifies how to format the second items. /// </summary> public string? SecondsItemStringFormat { get => (string?)this.GetValue(SecondsItemStringFormatProperty); set => this.SetValue(SecondsItemStringFormatProperty, value); } #region Do not change order of fields inside this region /// <summary> /// This readonly dependency property is to control whether to show the date-picker (in case of <see cref="DateTimePicker"/>) or hide it (in case of <see cref="TimePicker"/>. /// </summary> private static readonly DependencyPropertyKey IsDatePickerVisiblePropertyKey = DependencyProperty.RegisterReadOnly(nameof(IsDatePickerVisible), typeof(bool), typeof(TimePickerBase), new PropertyMetadata(BooleanBoxes.TrueBox)); /// <summary>Identifies the <see cref="IsDatePickerVisible"/> dependency property.</summary> [SuppressMessage("StyleCop.CSharp.OrderingRules", "SA1202:ElementsMustBeOrderedByAccess", Justification = "Otherwise we have \"Static member initializer refers to static member below or in other type part\" and thus resulting in having \"null\" as value")] public static readonly DependencyProperty IsDatePickerVisibleProperty = IsDatePickerVisiblePropertyKey.DependencyProperty; /// <summary> /// Gets or sets a value indicating whether the date can be selected or not. This property is read-only. /// </summary> public bool IsDatePickerVisible { get => (bool)this.GetValue(IsDatePickerVisibleProperty); protected set => this.SetValue(IsDatePickerVisiblePropertyKey, BooleanBoxes.Box(value)); } #endregion static TimePickerBase() { DefaultStyleKeyProperty.OverrideMetadata(typeof(TimePickerBase), new FrameworkPropertyMetadata(typeof(TimePickerBase))); EventManager.RegisterClassHandler(typeof(TimePickerBase), GotFocusEvent, new RoutedEventHandler(OnGotFocus)); VerticalContentAlignmentProperty.OverrideMetadata(typeof(TimePickerBase), new FrameworkPropertyMetadata(VerticalAlignment.Center)); LanguageProperty.OverrideMetadata(typeof(TimePickerBase), new FrameworkPropertyMetadata(OnLanguageChanged)); IsEnabledProperty.OverrideMetadata(typeof(TimePickerBase), new UIPropertyMetadata(OnIsEnabledChanged)); } protected TimePickerBase() { this.SetCurrentValue(SourceHoursAmPmComparerProperty, new AmPmComparer()); Mouse.AddPreviewMouseDownOutsideCapturedElementHandler(this, this.OutsideCapturedElementHandler); } private static void OnLanguageChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var timePartPickerBase = (TimePickerBase)d; timePartPickerBase.Language = e.NewValue as XmlLanguage ?? XmlLanguage.Empty; timePartPickerBase.ApplyCulture(); } private static void OnIsEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is TimePickerBase tp) { tp.CoerceValue(IsDropDownOpenProperty); } } /// <summary> /// Gets a value indicating whether the <see cref="DateTimeFormatInfo.AMDesignator" /> that is specified by the /// <see cref="CultureInfo" /> /// set by the <see cref="Culture" /> (<see cref="FrameworkElement.Language" /> if null) has not a value. /// </summary> public bool IsMilitaryTime { get { var dateTimeFormat = this.SpecificCultureInfo.DateTimeFormat; return !string.IsNullOrEmpty(dateTimeFormat.AMDesignator) && (dateTimeFormat.ShortTimePattern.Contains("h") || dateTimeFormat.LongTimePattern.Contains("h")); } } protected CultureInfo SpecificCultureInfo => this.Culture ?? this.Language.GetSpecificCulture(); /// <summary> /// When overridden in a derived class, is invoked whenever application code or internal processes call /// <see cref="M:System.Windows.FrameworkElement.ApplyTemplate" />. /// </summary> public override void OnApplyTemplate() { this.UnSubscribeEvents(); base.OnApplyTemplate(); this.popUp = this.GetTemplateChild(ElementPopup) as Popup; this.dropDownButton = this.GetTemplateChild(ElementButton) as Button; this.hourInput = this.GetTemplateChild(ElementHourPicker) as Selector; this.minuteInput = this.GetTemplateChild(ElementMinutePicker) as Selector; this.secondInput = this.GetTemplateChild(ElementSecondPicker) as Selector; this.hourHand = this.GetTemplateChild(ElementHourHand) as FrameworkElement; this.ampmSwitcher = this.GetTemplateChild(ElementAmPmSwitcher) as Selector; this.minuteHand = this.GetTemplateChild(ElementMinuteHand) as FrameworkElement; this.secondHand = this.GetTemplateChild(ElementSecondHand) as FrameworkElement; this.textBox = this.GetTemplateChild(ElementTextBox) as DatePickerTextBox; this.SetHandVisibility(this.HandVisibility); this.SetPickerVisibility(this.PickerVisibility); this.SetHourPartValues(this.SelectedDateTime.GetValueOrDefault().TimeOfDay); this.WriteValueToTextBox(); this.SetDefaultTimeOfDayValues(); this.SubscribeEvents(); this.ApplyCulture(); } protected virtual void ApplyCulture() { this.deactivateRangeBaseEvent = true; try { if (this.ampmSwitcher != null) { this.ampmSwitcher.Items.Clear(); if (!string.IsNullOrEmpty(this.SpecificCultureInfo.DateTimeFormat.AMDesignator)) { this.ampmSwitcher.Items.Add(this.SpecificCultureInfo.DateTimeFormat.AMDesignator); } if (!string.IsNullOrEmpty(this.SpecificCultureInfo.DateTimeFormat.PMDesignator)) { this.ampmSwitcher.Items.Add(this.SpecificCultureInfo.DateTimeFormat.PMDesignator); } } this.SetAmPmVisibility(); this.CoerceValue(SourceHoursProperty); if (this.SelectedDateTime.HasValue) { this.SetHourPartValues(this.SelectedDateTime.Value.TimeOfDay); } this.SetDefaultTimeOfDayValues(); } finally { this.deactivateRangeBaseEvent = false; } this.WriteValueToTextBox(); } protected Binding GetBinding(DependencyProperty property, BindingMode bindingMode = BindingMode.Default) { return new Binding(property.Name) { Source = this, Mode = bindingMode }; } protected virtual string? GetValueForTextBox() { var format = this.SelectedTimeFormat == TimePickerFormat.Long ? string.Intern(this.SpecificCultureInfo.DateTimeFormat.LongTimePattern) : string.Intern(this.SpecificCultureInfo.DateTimeFormat.ShortTimePattern); var valueForTextBox = this.SelectedDateTime?.ToString(string.Intern(format), this.SpecificCultureInfo); return valueForTextBox; } protected virtual void ClockSelectedTimeChanged() { var time = this.GetSelectedTimeFromGUI() ?? TimeSpan.Zero; var date = this.SelectedDateTime ?? DateTime.Today; this.SetCurrentValue(SelectedDateTimeProperty, date.Date + time); } protected void RaiseSelectedDateTimeChangedEvent(DateTime? oldValue, DateTime? newValue) { var args = new RoutedPropertyChangedEventArgs<DateTime?>(oldValue, newValue) { RoutedEvent = SelectedDateTimeChangedEvent }; this.RaiseEvent(args); } private static void OnSelectedTimeFormatChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is TimePickerBase tp) { tp.WriteValueToTextBox(); } } protected void SetDefaultTimeOfDayValues() { SetDefaultTimeOfDayValue(this.hourInput, this.hourInput?.Items.IndexOf(this.IsMilitaryTime ? 12 : 0)); SetDefaultTimeOfDayValue(this.minuteInput, 0); SetDefaultTimeOfDayValue(this.secondInput, 0); SetDefaultTimeOfDayValue(this.ampmSwitcher, 0); } private void SubscribeEvents() { if (this.popUp != null) { this.popUp.AddHandler(PreviewMouseLeftButtonDownEvent, new MouseButtonEventHandler(this.PopUp_PreviewMouseLeftButtonDown)); this.popUp.Opened += this.PopUp_Opened; this.popUp.Closed += this.PopUp_Closed; if (this.IsDropDownOpen) { this.popUp.IsOpen = true; } } this.SubscribeTimePickerEvents(this.hourInput, this.minuteInput, this.secondInput, this.ampmSwitcher); if (this.dropDownButton != null) { this.dropDownButton.Click += this.OnDropDownButtonClicked; this.dropDownButton.AddHandler(MouseLeaveEvent, new MouseEventHandler(this.DropDownButton_MouseLeave), true); } if (this.textBox != null) { this.textBox.AddHandler(KeyDownEvent, new KeyEventHandler(this.TextBox_KeyDown), true); this.textBox.TextChanged += this.TextBox_TextChanged; this.textBox.LostFocus += this.TextBox_LostFocus; } } private void UnSubscribeEvents() { if (this.popUp != null) { this.popUp.RemoveHandler(PreviewMouseLeftButtonDownEvent, new MouseButtonEventHandler(this.PopUp_PreviewMouseLeftButtonDown)); this.popUp.Opened -= this.PopUp_Opened; this.popUp.Closed -= this.PopUp_Closed; } this.UnsubscribeTimePickerEvents(this.hourInput, this.minuteInput, this.secondInput, this.ampmSwitcher); if (this.dropDownButton != null) { this.dropDownButton.Click -= this.OnDropDownButtonClicked; this.dropDownButton.RemoveHandler(MouseLeaveEvent, new MouseEventHandler(this.DropDownButton_MouseLeave)); } if (this.textBox != null) { this.textBox.RemoveHandler(KeyDownEvent, new KeyEventHandler(this.TextBox_KeyDown)); this.textBox.TextChanged -= this.TextBox_TextChanged; this.textBox.LostFocus -= this.TextBox_LostFocus; } } private void OutsideCapturedElementHandler(object sender, MouseButtonEventArgs e) { if (this.IsDropDownOpen) { if (!(this.dropDownButton?.InputHitTest(e.GetPosition(this.dropDownButton)) is null)) { return; } this.SetCurrentValue(IsDropDownOpenProperty, BooleanBoxes.FalseBox); } } private void PopUp_PreviewMouseLeftButtonDown(object? sender, MouseButtonEventArgs e) { if (sender is Popup popup && !popup.StaysOpen) { if (this.dropDownButton?.InputHitTest(e.GetPosition(this.dropDownButton)) != null) { // This popup is being closed by a mouse press on the drop down button // The following mouse release will cause the closed popup to immediately reopen. // Raise a flag to block reopeneing the popup this.disablePopupReopen = true; } } } private void PopUp_Opened(object? sender, EventArgs e) { if (!this.IsDropDownOpen) { this.SetCurrentValue(IsDropDownOpenProperty, BooleanBoxes.TrueBox); } this.OnPopUpOpened(); } protected virtual void OnPopUpOpened() { // nothing here } private void PopUp_Closed(object? sender, EventArgs e) { if (this.IsDropDownOpen) { this.SetCurrentValue(IsDropDownOpenProperty, BooleanBoxes.FalseBox); } this.OnPopUpClosed(); } protected virtual void OnPopUpClosed() { // nothing here } protected virtual void WriteValueToTextBox() { if (this.textBox != null) { this.deactivateTextChangedEvent = true; this.textBox.Text = this.GetValueForTextBox(); this.deactivateTextChangedEvent = false; } } private static IList<int> CreateValueList(int interval) { return Enumerable.Repeat(interval, 60 / interval) .Select((value, index) => value * index) .ToList(); } private void TimePickerPreviewKeyDown(object sender, RoutedEventArgs e) { if (e.OriginalSource is not Selector) { return; } var selector = sender as Selector; var keyEventArgs = (KeyEventArgs)e; Debug.Assert(selector != null); Debug.Assert(keyEventArgs != null); if (keyEventArgs is not null && (keyEventArgs.Key == Key.Escape || keyEventArgs.Key == Key.Enter || keyEventArgs.Key == Key.Space)) { this.SetCurrentValue(IsDropDownOpenProperty, BooleanBoxes.FalseBox); if (keyEventArgs.Key == Key.Escape) { this.SetCurrentValue(SelectedDateTimeProperty, this.originalSelectedDateTime); } } } private void TimePickerSelectionChanged(object sender, SelectionChangedEventArgs e) { if (this.deactivateRangeBaseEvent) { return; } this.ClockSelectedTimeChanged(); } private static void OnGotFocus(object sender, RoutedEventArgs e) { TimePickerBase picker = (TimePickerBase)sender; if (!e.Handled && picker.Focusable) { if (Equals(e.OriginalSource, picker)) { // MoveFocus takes a TraversalRequest as its argument. var request = new TraversalRequest((Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift ? FocusNavigationDirection.Previous : FocusNavigationDirection.Next); // Gets the element with keyboard focus. // Change keyboard focus. if (Keyboard.FocusedElement is UIElement elementWithFocus) { elementWithFocus.MoveFocus(request); } else { picker.Focus(); } e.Handled = true; } else if (picker.textBox != null && Equals(e.OriginalSource, picker.textBox)) { picker.textBox.SelectAll(); e.Handled = true; } } } protected virtual void OnSelectedDateTimeChanged(DateTime? oldValue, DateTime? newValue) { this.SetHourPartValues(newValue.GetValueOrDefault().TimeOfDay); } private static void SetVisibility(UIElement? partHours, UIElement? partMinutes, UIElement? partSeconds, TimePartVisibility visibility) { if (partHours != null) { partHours.Visibility = visibility.HasFlag(TimePartVisibility.Hour) ? Visibility.Visible : Visibility.Collapsed; } if (partMinutes != null) { partMinutes.Visibility = visibility.HasFlag(TimePartVisibility.Minute) ? Visibility.Visible : Visibility.Collapsed; } if (partSeconds != null) { partSeconds.Visibility = visibility.HasFlag(TimePartVisibility.Second) ? Visibility.Visible : Visibility.Collapsed; } } private static bool IsValueSelected(Selector? selector) { return selector?.SelectedItem is not null; } private static void SetDefaultTimeOfDayValue(Selector? selector, int? defaultIndex) { if (selector is not null && selector.SelectedValue is null) { selector.SelectedIndex = defaultIndex.GetValueOrDefault(0); } } protected TimeSpan? GetSelectedTimeFromGUI() { if (IsValueSelected(this.hourInput) && IsValueSelected(this.minuteInput) && IsValueSelected(this.secondInput)) { var hours = (int)this.hourInput!.SelectedItem; var minutes = (int)this.minuteInput!.SelectedItem; var seconds = (int)this.secondInput!.SelectedItem; hours += this.GetAmPmOffset(hours); return new TimeSpan(hours, minutes, seconds); } return null; } /// <summary> /// Gets the offset from the selected <paramref name="currentHour" /> to use it in <see cref="TimeSpan" /> as hour /// parameter. /// </summary> /// <param name="currentHour">The current hour.</param> /// <returns> /// An integer representing the offset to add to the hour that is selected in the hour-picker for setting the correct /// <see cref="DateTime.TimeOfDay" />. The offset is determined as follows: /// <list type="table"> /// <listheader> /// <term>Condition</term><description>Offset</description> /// </listheader> /// <item> /// <term><see cref="IsMilitaryTime" /> is false</term><description>0</description> /// </item> /// <item> /// <term>Selected hour is between 1 AM and 11 AM</term><description>0</description> /// </item> /// <item> /// <term>Selected hour is 12 AM</term><description>-12h</description> /// </item> /// <item> /// <term>Selected hour is between 12 PM and 11 PM</term><description>+12h</description> /// </item> /// </list> /// </returns> private int GetAmPmOffset(int currentHour) { if (this.IsMilitaryTime && this.ampmSwitcher is not null) { if (currentHour == 12) { if (Equals(this.ampmSwitcher.SelectedItem, this.SpecificCultureInfo.DateTimeFormat.AMDesignator)) { return -12; } } else if (Equals(this.ampmSwitcher.SelectedItem, this.SpecificCultureInfo.DateTimeFormat.PMDesignator)) { return 12; } } return 0; } private void OnDropDownButtonClicked(object sender, RoutedEventArgs e) { this.TogglePopUp(); } private void DropDownButton_MouseLeave(object sender, MouseEventArgs e) { this.disablePopupReopen = false; } private void TogglePopUp() { if (this.IsDropDownOpen) { this.SetCurrentValue(IsDropDownOpenProperty, BooleanBoxes.FalseBox); } else { if (this.disablePopupReopen) { this.disablePopupReopen = false; } else { this.SetSelectedDateTime(); this.SetCurrentValue(IsDropDownOpenProperty, BooleanBoxes.TrueBox); } } } private void SetAmPmVisibility() { if (this.ampmSwitcher != null) { if (!this.PickerVisibility.HasFlag(TimePartVisibility.Hour)) { this.ampmSwitcher.Visibility = Visibility.Collapsed; } else { this.ampmSwitcher.Visibility = this.IsMilitaryTime ? Visibility.Visible : Visibility.Collapsed; } } } private void SetHandVisibility(TimePartVisibility visibility) { SetVisibility(this.hourHand, this.minuteHand, this.secondHand, visibility); } private void SetHourPartValues(TimeSpan timeOfDay) { if (this.deactivateRangeBaseEvent) { return; } this.deactivateRangeBaseEvent = true; try { if (this.hourInput != null) { if (this.IsMilitaryTime) { if (this.ampmSwitcher is not null) { this.ampmSwitcher.SelectedValue = timeOfDay.Hours < 12 ? this.SpecificCultureInfo.DateTimeFormat.AMDesignator : this.SpecificCultureInfo.DateTimeFormat.PMDesignator; if (timeOfDay.Hours == 0 || timeOfDay.Hours == 12) { this.hourInput.SelectedValue = 12; } else { this.hourInput.SelectedValue = timeOfDay.Hours % 12; } } } else { this.hourInput.SelectedValue = timeOfDay.Hours; } } if (this.minuteInput != null) { this.minuteInput.SelectedValue = timeOfDay.Minutes; } if (this.secondInput != null) { this.secondInput.SelectedValue = timeOfDay.Seconds; } } finally { this.deactivateRangeBaseEvent = false; } } private void SetPickerVisibility(TimePartVisibility visibility) { SetVisibility(this.hourInput, this.minuteInput, this.secondInput, visibility); this.SetAmPmVisibility(); } private void UnsubscribeTimePickerEvents(params Selector?[] selectors) { foreach (var selector in selectors) { if (selector is null) { continue; } selector.PreviewKeyDown -= this.TimePickerPreviewKeyDown; selector.SelectionChanged -= this.TimePickerSelectionChanged; } } private void SubscribeTimePickerEvents(params Selector?[] selectors) { foreach (var selector in selectors) { if (selector is null) { continue; } selector.PreviewKeyDown += this.TimePickerPreviewKeyDown; selector.SelectionChanged += this.TimePickerSelectionChanged; } } private bool ProcessKey(KeyEventArgs e) { switch (e.Key) { case Key.System: { switch (e.SystemKey) { case Key.Down: { if ((Keyboard.Modifiers & ModifierKeys.Alt) == ModifierKeys.Alt) { this.TogglePopUp(); return true; } break; } } break; } case Key.Enter: { this.SetSelectedDateTime(); return true; } } return false; } protected abstract void SetSelectedDateTime(); private void TextBox_LostFocus(object sender, RoutedEventArgs e) { if (this.textInputChanged) { this.textInputChanged = false; this.SetSelectedDateTime(); } } private void TextBox_KeyDown(object sender, KeyEventArgs e) { e.Handled = this.ProcessKey(e) || e.Handled; } private void TextBox_TextChanged(object sender, TextChangedEventArgs e) { if (!this.deactivateTextChangedEvent) { this.textInputChanged = true; } } } }
// 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 ShuffleByte() { var test = new SimpleBinaryOpTest__ShuffleByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__ShuffleByte { 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(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); 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<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, 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<Byte> _fld1; public Vector128<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__ShuffleByte testClass) { var result = Ssse3.Shuffle(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__ShuffleByte testClass) { fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = Ssse3.Shuffle( Sse2.LoadVector128((Byte*)(pFld1)), Sse2.LoadVector128((Byte*)(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<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector128<Byte> _clsVar1; private static Vector128<Byte> _clsVar2; private Vector128<Byte> _fld1; private Vector128<Byte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__ShuffleByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); } public SimpleBinaryOpTest__ShuffleByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize); } public bool IsSupported => Ssse3.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Ssse3.Shuffle( Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_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 = Ssse3.Shuffle( Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Byte*)(_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 = Ssse3.Shuffle( Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Byte*)(_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(Ssse3).GetMethod(nameof(Ssse3.Shuffle), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Ssse3).GetMethod(nameof(Ssse3.Shuffle), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Ssse3).GetMethod(nameof(Ssse3.Shuffle), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Ssse3.Shuffle( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Byte>* pClsVar1 = &_clsVar1) fixed (Vector128<Byte>* pClsVar2 = &_clsVar2) { var result = Ssse3.Shuffle( Sse2.LoadVector128((Byte*)(pClsVar1)), Sse2.LoadVector128((Byte*)(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<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr); var result = Ssse3.Shuffle(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((Byte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)); var result = Ssse3.Shuffle(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((Byte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)); var result = Ssse3.Shuffle(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__ShuffleByte(); var result = Ssse3.Shuffle(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__ShuffleByte(); fixed (Vector128<Byte>* pFld1 = &test._fld1) fixed (Vector128<Byte>* pFld2 = &test._fld2) { var result = Ssse3.Shuffle( Sse2.LoadVector128((Byte*)(pFld1)), Sse2.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Ssse3.Shuffle(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = Ssse3.Shuffle( Sse2.LoadVector128((Byte*)(pFld1)), Sse2.LoadVector128((Byte*)(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 = Ssse3.Shuffle(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 = Ssse3.Shuffle( Sse2.LoadVector128((Byte*)(&test._fld1)), Sse2.LoadVector128((Byte*)(&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<Byte> op1, Vector128<Byte> op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != ((right[0] > 127) ? 0 : left[right[0] & 0x0F])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((right[i] > 127) ? 0 : left[right[i] & 0x0F])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Ssse3)}.{nameof(Ssse3.Shuffle)}<Byte>(Vector128<Byte>, Vector128<Byte>): {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; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Wintellect.PowerCollections; class Event : IComparable { public DateTime date; public String title; public String location; public Event(DateTime date, String title, String location) { this.date = date; this.title = title; this.location = location; } public int CompareTo(object obj) { Event other = obj as Event; int byDate = this.date.CompareTo(other.date); int byTitle = this.title.CompareTo(other.title); int byLocation = this.location.CompareTo(other.location); if (byDate == 0) { if (byTitle == 0) { return byLocation; } else { return byTitle; } } else { return byDate; } } public override string ToString() { var toString = new StringBuilder(); toString.Append(date.ToString("yyyy-MM-ddTHH:mm:ss")); toString.Append(" | " + title); if (location != null && location != "") { toString.Append(" | " + location); } return toString.ToString(); } } class Events { static StringBuilder output = new StringBuilder(); static class Messages { public static void EventAdded() { output.Append("Event added\n"); } public static void EventDeleted(int x) { if (x == 0) { NoEventsFound(); } else { output.AppendFormat("{0} events deleted\n", x); } } public static void NoEventsFound() { output.Append("No events found\n"); } public static void PrintEvent(Event eventToPrint) { if (eventToPrint != null) { output.Append(eventToPrint + "\n"); } } } class EventHolder { MultiDictionary<string, Event> byTitle = new MultiDictionary<string, Event>(true); OrderedBag<Event> byDate = new OrderedBag<Event>(); public void AddEvent(DateTime date, string title, string location) { Event newEvent = new Event(date, title, location); byTitle.Add(title.ToLower(), newEvent); byDate.Add(newEvent); Messages.EventAdded(); } public void DeleteEvents(string titleToDelete) { string title = titleToDelete.ToLower(); int removed = 0; foreach (var eventToRemove in byTitle[title]) { removed++; byDate.Remove(eventToRemove); } byTitle.Remove(title); Messages.EventDeleted(removed); } public void ListEvents(DateTime date, int count) { OrderedBag<Event>.View eventsToShow = byDate.RangeFrom(new Event(date, "", ""), true); int showed = 0; foreach (var eventToShow in eventsToShow) { if (showed == count) break; Messages.PrintEvent(eventToShow); showed++; } if (showed == 0) { Messages.NoEventsFound(); } } } static EventHolder events = new EventHolder(); static void Main(string[] args) { while (ExecuteNextCommand()) { } Console.WriteLine(output); } private static bool ExecuteNextCommand() { string command = Console.ReadLine(); if (command[0] == 'A') { AddEvent(command); return true; } if (command[0] == 'D') { DeleteEvents(command); return true; } if (command[0] == 'L') { ListEvents(command); return true; } if (command[0] == 'E') { return false; } return false; } private static void ListEvents(string command) { int pipeIndex = command.IndexOf('|'); DateTime date = GetDate(command, "ListEvents"); string countString = command.Substring(pipeIndex + 1); int count = int.Parse(countString); events.ListEvents(date, count); } private static void DeleteEvents(string command) { string title = command.Substring("DeleteEvents".Length + 1); events.DeleteEvents(title); } private static void AddEvent(string command) { DateTime date; string title; string location; GetParameters(command, "AddEvent", out date, out title, out location); events.AddEvent(date, title, location); } private static void GetParameters(string commandForExecution, string commandType, out DateTime dateAndTime, out string eventTitle, out string eventLocation) { dateAndTime = GetDate(commandForExecution, commandType); int firstPipeIndex = commandForExecution.IndexOf('|'); int lastPipeIndex = commandForExecution.LastIndexOf('|'); if (firstPipeIndex == lastPipeIndex) { eventTitle = commandForExecution.Substring(firstPipeIndex + 1).Trim(); eventLocation = ""; } else { eventTitle = commandForExecution.Substring(firstPipeIndex + 1, lastPipeIndex - firstPipeIndex - 1).Trim(); eventLocation = commandForExecution.Substring(lastPipeIndex + 1).Trim(); } } private static DateTime GetDate(string command, string commandType) { DateTime date = DateTime.Parse(command.Substring(commandType.Length + 1, 20)); return date; } }
// Copyright 2021 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! using gagvc = Google.Ads.GoogleAds.V8.Common; using gagve = Google.Ads.GoogleAds.V8.Enums; using gagvr = Google.Ads.GoogleAds.V8.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using gr = Google.Rpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V8.Services; namespace Google.Ads.GoogleAds.Tests.V8.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedAdGroupBidModifierServiceClientTest { [Category("Autogenerated")][Test] public void GetAdGroupBidModifierRequestObject() { moq::Mock<AdGroupBidModifierService.AdGroupBidModifierServiceClient> mockGrpcClient = new moq::Mock<AdGroupBidModifierService.AdGroupBidModifierServiceClient>(moq::MockBehavior.Strict); GetAdGroupBidModifierRequest request = new GetAdGroupBidModifierRequest { ResourceNameAsAdGroupBidModifierName = gagvr::AdGroupBidModifierName.FromCustomerAdGroupCriterion("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]"), }; gagvr::AdGroupBidModifier expectedResponse = new gagvr::AdGroupBidModifier { ResourceNameAsAdGroupBidModifierName = gagvr::AdGroupBidModifierName.FromCustomerAdGroupCriterion("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]"), HotelDateSelectionType = new gagvc::HotelDateSelectionTypeInfo(), HotelAdvanceBookingWindow = new gagvc::HotelAdvanceBookingWindowInfo(), HotelLengthOfStay = new gagvc::HotelLengthOfStayInfo(), HotelCheckInDay = new gagvc::HotelCheckInDayInfo(), BidModifierSource = gagve::BidModifierSourceEnum.Types.BidModifierSource.AdGroup, Device = new gagvc::DeviceInfo(), PreferredContent = new gagvc::PreferredContentInfo(), AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), CriterionId = 8584655242409302840L, BidModifier = 1.6595195068951933E+17, BaseAdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), HotelCheckInDateRange = new gagvc::HotelCheckInDateRangeInfo(), }; mockGrpcClient.Setup(x => x.GetAdGroupBidModifier(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AdGroupBidModifierServiceClient client = new AdGroupBidModifierServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupBidModifier response = client.GetAdGroupBidModifier(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAdGroupBidModifierRequestObjectAsync() { moq::Mock<AdGroupBidModifierService.AdGroupBidModifierServiceClient> mockGrpcClient = new moq::Mock<AdGroupBidModifierService.AdGroupBidModifierServiceClient>(moq::MockBehavior.Strict); GetAdGroupBidModifierRequest request = new GetAdGroupBidModifierRequest { ResourceNameAsAdGroupBidModifierName = gagvr::AdGroupBidModifierName.FromCustomerAdGroupCriterion("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]"), }; gagvr::AdGroupBidModifier expectedResponse = new gagvr::AdGroupBidModifier { ResourceNameAsAdGroupBidModifierName = gagvr::AdGroupBidModifierName.FromCustomerAdGroupCriterion("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]"), HotelDateSelectionType = new gagvc::HotelDateSelectionTypeInfo(), HotelAdvanceBookingWindow = new gagvc::HotelAdvanceBookingWindowInfo(), HotelLengthOfStay = new gagvc::HotelLengthOfStayInfo(), HotelCheckInDay = new gagvc::HotelCheckInDayInfo(), BidModifierSource = gagve::BidModifierSourceEnum.Types.BidModifierSource.AdGroup, Device = new gagvc::DeviceInfo(), PreferredContent = new gagvc::PreferredContentInfo(), AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), CriterionId = 8584655242409302840L, BidModifier = 1.6595195068951933E+17, BaseAdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), HotelCheckInDateRange = new gagvc::HotelCheckInDateRangeInfo(), }; mockGrpcClient.Setup(x => x.GetAdGroupBidModifierAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AdGroupBidModifier>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AdGroupBidModifierServiceClient client = new AdGroupBidModifierServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupBidModifier responseCallSettings = await client.GetAdGroupBidModifierAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::AdGroupBidModifier responseCancellationToken = await client.GetAdGroupBidModifierAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetAdGroupBidModifier() { moq::Mock<AdGroupBidModifierService.AdGroupBidModifierServiceClient> mockGrpcClient = new moq::Mock<AdGroupBidModifierService.AdGroupBidModifierServiceClient>(moq::MockBehavior.Strict); GetAdGroupBidModifierRequest request = new GetAdGroupBidModifierRequest { ResourceNameAsAdGroupBidModifierName = gagvr::AdGroupBidModifierName.FromCustomerAdGroupCriterion("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]"), }; gagvr::AdGroupBidModifier expectedResponse = new gagvr::AdGroupBidModifier { ResourceNameAsAdGroupBidModifierName = gagvr::AdGroupBidModifierName.FromCustomerAdGroupCriterion("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]"), HotelDateSelectionType = new gagvc::HotelDateSelectionTypeInfo(), HotelAdvanceBookingWindow = new gagvc::HotelAdvanceBookingWindowInfo(), HotelLengthOfStay = new gagvc::HotelLengthOfStayInfo(), HotelCheckInDay = new gagvc::HotelCheckInDayInfo(), BidModifierSource = gagve::BidModifierSourceEnum.Types.BidModifierSource.AdGroup, Device = new gagvc::DeviceInfo(), PreferredContent = new gagvc::PreferredContentInfo(), AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), CriterionId = 8584655242409302840L, BidModifier = 1.6595195068951933E+17, BaseAdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), HotelCheckInDateRange = new gagvc::HotelCheckInDateRangeInfo(), }; mockGrpcClient.Setup(x => x.GetAdGroupBidModifier(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AdGroupBidModifierServiceClient client = new AdGroupBidModifierServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupBidModifier response = client.GetAdGroupBidModifier(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAdGroupBidModifierAsync() { moq::Mock<AdGroupBidModifierService.AdGroupBidModifierServiceClient> mockGrpcClient = new moq::Mock<AdGroupBidModifierService.AdGroupBidModifierServiceClient>(moq::MockBehavior.Strict); GetAdGroupBidModifierRequest request = new GetAdGroupBidModifierRequest { ResourceNameAsAdGroupBidModifierName = gagvr::AdGroupBidModifierName.FromCustomerAdGroupCriterion("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]"), }; gagvr::AdGroupBidModifier expectedResponse = new gagvr::AdGroupBidModifier { ResourceNameAsAdGroupBidModifierName = gagvr::AdGroupBidModifierName.FromCustomerAdGroupCriterion("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]"), HotelDateSelectionType = new gagvc::HotelDateSelectionTypeInfo(), HotelAdvanceBookingWindow = new gagvc::HotelAdvanceBookingWindowInfo(), HotelLengthOfStay = new gagvc::HotelLengthOfStayInfo(), HotelCheckInDay = new gagvc::HotelCheckInDayInfo(), BidModifierSource = gagve::BidModifierSourceEnum.Types.BidModifierSource.AdGroup, Device = new gagvc::DeviceInfo(), PreferredContent = new gagvc::PreferredContentInfo(), AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), CriterionId = 8584655242409302840L, BidModifier = 1.6595195068951933E+17, BaseAdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), HotelCheckInDateRange = new gagvc::HotelCheckInDateRangeInfo(), }; mockGrpcClient.Setup(x => x.GetAdGroupBidModifierAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AdGroupBidModifier>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AdGroupBidModifierServiceClient client = new AdGroupBidModifierServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupBidModifier responseCallSettings = await client.GetAdGroupBidModifierAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::AdGroupBidModifier responseCancellationToken = await client.GetAdGroupBidModifierAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetAdGroupBidModifierResourceNames() { moq::Mock<AdGroupBidModifierService.AdGroupBidModifierServiceClient> mockGrpcClient = new moq::Mock<AdGroupBidModifierService.AdGroupBidModifierServiceClient>(moq::MockBehavior.Strict); GetAdGroupBidModifierRequest request = new GetAdGroupBidModifierRequest { ResourceNameAsAdGroupBidModifierName = gagvr::AdGroupBidModifierName.FromCustomerAdGroupCriterion("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]"), }; gagvr::AdGroupBidModifier expectedResponse = new gagvr::AdGroupBidModifier { ResourceNameAsAdGroupBidModifierName = gagvr::AdGroupBidModifierName.FromCustomerAdGroupCriterion("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]"), HotelDateSelectionType = new gagvc::HotelDateSelectionTypeInfo(), HotelAdvanceBookingWindow = new gagvc::HotelAdvanceBookingWindowInfo(), HotelLengthOfStay = new gagvc::HotelLengthOfStayInfo(), HotelCheckInDay = new gagvc::HotelCheckInDayInfo(), BidModifierSource = gagve::BidModifierSourceEnum.Types.BidModifierSource.AdGroup, Device = new gagvc::DeviceInfo(), PreferredContent = new gagvc::PreferredContentInfo(), AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), CriterionId = 8584655242409302840L, BidModifier = 1.6595195068951933E+17, BaseAdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), HotelCheckInDateRange = new gagvc::HotelCheckInDateRangeInfo(), }; mockGrpcClient.Setup(x => x.GetAdGroupBidModifier(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AdGroupBidModifierServiceClient client = new AdGroupBidModifierServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupBidModifier response = client.GetAdGroupBidModifier(request.ResourceNameAsAdGroupBidModifierName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAdGroupBidModifierResourceNamesAsync() { moq::Mock<AdGroupBidModifierService.AdGroupBidModifierServiceClient> mockGrpcClient = new moq::Mock<AdGroupBidModifierService.AdGroupBidModifierServiceClient>(moq::MockBehavior.Strict); GetAdGroupBidModifierRequest request = new GetAdGroupBidModifierRequest { ResourceNameAsAdGroupBidModifierName = gagvr::AdGroupBidModifierName.FromCustomerAdGroupCriterion("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]"), }; gagvr::AdGroupBidModifier expectedResponse = new gagvr::AdGroupBidModifier { ResourceNameAsAdGroupBidModifierName = gagvr::AdGroupBidModifierName.FromCustomerAdGroupCriterion("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]"), HotelDateSelectionType = new gagvc::HotelDateSelectionTypeInfo(), HotelAdvanceBookingWindow = new gagvc::HotelAdvanceBookingWindowInfo(), HotelLengthOfStay = new gagvc::HotelLengthOfStayInfo(), HotelCheckInDay = new gagvc::HotelCheckInDayInfo(), BidModifierSource = gagve::BidModifierSourceEnum.Types.BidModifierSource.AdGroup, Device = new gagvc::DeviceInfo(), PreferredContent = new gagvc::PreferredContentInfo(), AdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), CriterionId = 8584655242409302840L, BidModifier = 1.6595195068951933E+17, BaseAdGroupAsAdGroupName = gagvr::AdGroupName.FromCustomerAdGroup("[CUSTOMER_ID]", "[AD_GROUP_ID]"), HotelCheckInDateRange = new gagvc::HotelCheckInDateRangeInfo(), }; mockGrpcClient.Setup(x => x.GetAdGroupBidModifierAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AdGroupBidModifier>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AdGroupBidModifierServiceClient client = new AdGroupBidModifierServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupBidModifier responseCallSettings = await client.GetAdGroupBidModifierAsync(request.ResourceNameAsAdGroupBidModifierName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::AdGroupBidModifier responseCancellationToken = await client.GetAdGroupBidModifierAsync(request.ResourceNameAsAdGroupBidModifierName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateAdGroupBidModifiersRequestObject() { moq::Mock<AdGroupBidModifierService.AdGroupBidModifierServiceClient> mockGrpcClient = new moq::Mock<AdGroupBidModifierService.AdGroupBidModifierServiceClient>(moq::MockBehavior.Strict); MutateAdGroupBidModifiersRequest request = new MutateAdGroupBidModifiersRequest { CustomerId = "customer_id3b3724cb", Operations = { new AdGroupBidModifierOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateAdGroupBidModifiersResponse expectedResponse = new MutateAdGroupBidModifiersResponse { Results = { new MutateAdGroupBidModifierResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateAdGroupBidModifiers(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AdGroupBidModifierServiceClient client = new AdGroupBidModifierServiceClientImpl(mockGrpcClient.Object, null); MutateAdGroupBidModifiersResponse response = client.MutateAdGroupBidModifiers(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateAdGroupBidModifiersRequestObjectAsync() { moq::Mock<AdGroupBidModifierService.AdGroupBidModifierServiceClient> mockGrpcClient = new moq::Mock<AdGroupBidModifierService.AdGroupBidModifierServiceClient>(moq::MockBehavior.Strict); MutateAdGroupBidModifiersRequest request = new MutateAdGroupBidModifiersRequest { CustomerId = "customer_id3b3724cb", Operations = { new AdGroupBidModifierOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateAdGroupBidModifiersResponse expectedResponse = new MutateAdGroupBidModifiersResponse { Results = { new MutateAdGroupBidModifierResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateAdGroupBidModifiersAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateAdGroupBidModifiersResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AdGroupBidModifierServiceClient client = new AdGroupBidModifierServiceClientImpl(mockGrpcClient.Object, null); MutateAdGroupBidModifiersResponse responseCallSettings = await client.MutateAdGroupBidModifiersAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateAdGroupBidModifiersResponse responseCancellationToken = await client.MutateAdGroupBidModifiersAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateAdGroupBidModifiers() { moq::Mock<AdGroupBidModifierService.AdGroupBidModifierServiceClient> mockGrpcClient = new moq::Mock<AdGroupBidModifierService.AdGroupBidModifierServiceClient>(moq::MockBehavior.Strict); MutateAdGroupBidModifiersRequest request = new MutateAdGroupBidModifiersRequest { CustomerId = "customer_id3b3724cb", Operations = { new AdGroupBidModifierOperation(), }, }; MutateAdGroupBidModifiersResponse expectedResponse = new MutateAdGroupBidModifiersResponse { Results = { new MutateAdGroupBidModifierResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateAdGroupBidModifiers(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AdGroupBidModifierServiceClient client = new AdGroupBidModifierServiceClientImpl(mockGrpcClient.Object, null); MutateAdGroupBidModifiersResponse response = client.MutateAdGroupBidModifiers(request.CustomerId, request.Operations); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateAdGroupBidModifiersAsync() { moq::Mock<AdGroupBidModifierService.AdGroupBidModifierServiceClient> mockGrpcClient = new moq::Mock<AdGroupBidModifierService.AdGroupBidModifierServiceClient>(moq::MockBehavior.Strict); MutateAdGroupBidModifiersRequest request = new MutateAdGroupBidModifiersRequest { CustomerId = "customer_id3b3724cb", Operations = { new AdGroupBidModifierOperation(), }, }; MutateAdGroupBidModifiersResponse expectedResponse = new MutateAdGroupBidModifiersResponse { Results = { new MutateAdGroupBidModifierResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateAdGroupBidModifiersAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateAdGroupBidModifiersResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AdGroupBidModifierServiceClient client = new AdGroupBidModifierServiceClientImpl(mockGrpcClient.Object, null); MutateAdGroupBidModifiersResponse responseCallSettings = await client.MutateAdGroupBidModifiersAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateAdGroupBidModifiersResponse responseCancellationToken = await client.MutateAdGroupBidModifiersAsync(request.CustomerId, request.Operations, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.WindowsAzure.Management.Compute.Models; namespace Microsoft.WindowsAzure.Management.Compute { /// <summary> /// The Service Management API includes operations for managing the hosted /// services beneath your subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460812.aspx for /// more information) /// </summary> public partial interface IHostedServiceOperations { /// <summary> /// The Add Extension operation adds an available extension to your /// cloud service. In Azure, a process can run as an extension of a /// cloud service. For example, Remote Desktop Access or the Azure /// Diagnostics Agent can run as extensions to the cloud service. You /// can find the available extension by using the List Available /// Extensions operation. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn169558.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// The name of the cloud service. /// </param> /// <param name='parameters'> /// Parameters supplied to the Add Extension operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> Task<OperationStatusResponse> AddExtensionAsync(string serviceName, HostedServiceAddExtensionParameters parameters, CancellationToken cancellationToken); /// <summary> /// The Begin Adding Extension operation adds an available extension to /// your cloud service. In Azure, a process can run as an extension of /// a cloud service. For example, Remote Desktop Access or the Azure /// Diagnostics Agent can run as extensions to the cloud service. You /// can find the available extension by using the List Available /// Extensions operation. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn169558.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// The name of the cloud service. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Adding Extension operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<AzureOperationResponse> BeginAddingExtensionAsync(string serviceName, HostedServiceAddExtensionParameters parameters, CancellationToken cancellationToken); /// <summary> /// The DeleteAll Hosted Service operation deletes the specified cloud /// service as well as operating system disk, attached data disks, and /// the source blobs for the disks from storage from Microsoft Azure. /// (see /// 'http://msdn.microsoft.com/en-us/library/windowsazure/gg441305.aspx' /// for more information) /// </summary> /// <param name='serviceName'> /// The name of the cloud service. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<AzureOperationResponse> BeginDeletingAllAsync(string serviceName, CancellationToken cancellationToken); /// <summary> /// The Begin Deleting Extension operation deletes the specified /// extension from a cloud service. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn169560.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// The name of the cloud service. /// </param> /// <param name='extensionId'> /// The identifier that was assigned to the extension when it was added /// to the cloud service /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<AzureOperationResponse> BeginDeletingExtensionAsync(string serviceName, string extensionId, CancellationToken cancellationToken); /// <summary> /// The Check Hosted Service Name Availability operation checks for the /// availability of the specified cloud service name. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154116.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// The cloud service name that you would like to use. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Check Hosted Service Name Availability operation response. /// </returns> Task<HostedServiceCheckNameAvailabilityResponse> CheckNameAvailabilityAsync(string serviceName, CancellationToken cancellationToken); /// <summary> /// The Create Hosted Service operation creates a new cloud service in /// Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/gg441304.aspx /// for more information) /// </summary> /// <param name='parameters'> /// Parameters supplied to the Create Hosted Service operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<AzureOperationResponse> CreateAsync(HostedServiceCreateParameters parameters, CancellationToken cancellationToken); /// <summary> /// The Delete Hosted Service operation deletes the specified cloud /// service from Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/gg441305.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// The name of the cloud service. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<AzureOperationResponse> DeleteAsync(string serviceName, CancellationToken cancellationToken); /// <summary> /// The DeleteAll Hosted Service operation deletes the specified cloud /// service as well as operating system disk, attached data disks, and /// the source blobs for the disks from storage from Microsoft Azure. /// (see /// 'http://msdn.microsoft.com/en-us/library/windowsazure/gg441305.aspx' /// for more information) /// </summary> /// <param name='serviceName'> /// The name of the cloud service. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> Task<OperationStatusResponse> DeleteAllAsync(string serviceName, CancellationToken cancellationToken); /// <summary> /// The Delete Extension operation deletes the specified extension from /// a cloud service. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn169560.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// The name of the cloud service. /// </param> /// <param name='extensionId'> /// The identifier that was assigned to the extension when it was added /// to the cloud service /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> Task<OperationStatusResponse> DeleteExtensionAsync(string serviceName, string extensionId, CancellationToken cancellationToken); /// <summary> /// The Get Hosted Service Properties operation retrieves system /// properties for the specified cloud service. These properties /// include the service name and service type; and the name of the /// affinity group to which the service belongs, or its location if it /// is not part of an affinity group. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460806.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// The name of the cloud service. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get Hosted Service operation response. /// </returns> Task<HostedServiceGetResponse> GetAsync(string serviceName, CancellationToken cancellationToken); /// <summary> /// The Get Detailed Hosted Service Properties operation retrieves /// system properties for the specified cloud service. These /// properties include the service name and service type; the name of /// the affinity group to which the service belongs, or its location /// if it is not part of an affinity group; and information on the /// deployments of the service. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460806.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// The name of the cloud service. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The detailed Get Hosted Service operation response. /// </returns> Task<HostedServiceGetDetailedResponse> GetDetailedAsync(string serviceName, CancellationToken cancellationToken); /// <summary> /// The Get Extension operation retrieves information about a specified /// extension that was added to a cloud service. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn169557.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// The name of the cloud service. /// </param> /// <param name='extensionId'> /// The identifier that was assigned to the extension when it was added /// to the cloud service /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get Extension operation response. /// </returns> Task<HostedServiceGetExtensionResponse> GetExtensionAsync(string serviceName, string extensionId, CancellationToken cancellationToken); /// <summary> /// The List Hosted Services operation lists the cloud services /// available under the current subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460781.aspx /// for more information) /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Hosted Service operation response. /// </returns> Task<HostedServiceListResponse> ListAsync(CancellationToken cancellationToken); /// <summary> /// The List Available Extensions operation lists the extensions that /// are available to add to your cloud service. In Windows Azure, a /// process can run as an extension of a cloud service. For example, /// Remote Desktop Access or the Azure Diagnostics Agent can run as /// extensions to the cloud service. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn169559.aspx /// for more information) /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Available Extensions operation response. /// </returns> Task<HostedServiceListAvailableExtensionsResponse> ListAvailableExtensionsAsync(CancellationToken cancellationToken); /// <summary> /// The List Extensions operation lists all of the extensions that were /// added to a cloud service. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn169561.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// The name of the cloud service. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Extensions operation response. /// </returns> Task<HostedServiceListExtensionsResponse> ListExtensionsAsync(string serviceName, CancellationToken cancellationToken); /// <summary> /// The List Extension Versions operation lists the versions of an /// extension that are available to add to a cloud service. In Azure, /// a process can run as an extension of a cloud service. For example, /// Remote Desktop Access or the Azure Diagnostics Agent can run as /// extensions to the cloud service. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn495437.aspx /// for more information) /// </summary> /// <param name='providerNamespace'> /// The provider namespace. /// </param> /// <param name='extensionType'> /// The extension type name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Available Extensions operation response. /// </returns> Task<HostedServiceListAvailableExtensionsResponse> ListExtensionVersionsAsync(string providerNamespace, string extensionType, CancellationToken cancellationToken); /// <summary> /// The Update Hosted Service operation can update the label or /// description of a cloud service in Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/gg441303.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// The name of the cloud service. /// </param> /// <param name='parameters'> /// Parameters supplied to the Update Hosted Service operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<AzureOperationResponse> UpdateAsync(string serviceName, HostedServiceUpdateParameters parameters, CancellationToken cancellationToken); } }
using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Nest { public class ScoreFunctionJsonConverter : JsonConverter { public override bool CanRead => true; public override bool CanWrite => true; public override bool CanConvert(Type objectType) => true; public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var function = value as IScoreFunction; if (function == null) return; writer.WriteStartObject(); { if (function.Filter != null) { writer.WritePropertyName("filter"); serializer.Serialize(writer, function.Filter); } var write = WriteDecay(writer, function as IDecayFunction, serializer) || WriteFieldValueFactor(writer, function as IFieldValueFactorFunction, serializer) || WriteRandomScore(writer, function as IRandomScoreFunction, serializer) || WriteScriptScore(writer, function as IScriptScoreFunction, serializer) || WriteWeightFunction(writer, function as IWeightFunction, serializer); if (!write) throw new Exception($"Can not write function score json for {function.GetType().Name}"); if (function.Weight.HasValue) { writer.WritePropertyName("weight"); serializer.Serialize(writer, function.Weight.Value); } } writer.WriteEndObject(); } //rely on weight getting written later private bool WriteWeightFunction(JsonWriter writer, IWeightFunction value, JsonSerializer serializer) => value != null; private bool WriteScriptScore(JsonWriter writer, IScriptScoreFunction value, JsonSerializer serializer) { if (value == null) return false; writer.WritePropertyName("script_score"); writer.WriteStartObject(); { writer.WriteProperty(serializer, "script", value.Script); } writer.WriteEndObject(); return true; } private bool WriteRandomScore(JsonWriter writer, IRandomScoreFunction value, JsonSerializer serializer) { if (value == null) return false; writer.WritePropertyName("random_score"); writer.WriteStartObject(); { writer.WriteProperty(serializer, "seed", value.Seed); } writer.WriteEndObject(); return true; } private bool WriteFieldValueFactor(JsonWriter writer, IFieldValueFactorFunction value, JsonSerializer serializer) { if (value == null) return false; writer.WritePropertyName("field_value_factor"); writer.WriteStartObject(); { writer.WriteProperty(serializer, "field", value.Field); writer.WriteProperty(serializer, "factor", value.Factor); writer.WriteProperty(serializer, "missing", value.Missing); writer.WriteProperty(serializer, "modifier", value.Modifier); } writer.WriteEndObject(); return true; } private bool WriteDecay(JsonWriter writer, IDecayFunction decay, JsonSerializer serializer) { if (decay == null) return false; writer.WritePropertyName(decay.DecayType); writer.WriteStartObject(); { writer.WritePropertyName(serializer.GetConnectionSettings().Inferrer.Field(decay.Field)); writer.WriteStartObject(); { var write = WriteNumericDecay(writer, decay as IDecayFunction<double?, double?>, serializer) || WriteDateDecay(writer, decay as IDecayFunction<DateMath, Time>, serializer) || WriteGeoDecay(writer, decay as IDecayFunction<GeoLocation, Distance>, serializer); if (!write) throw new Exception($"Can not write decay function json for {decay.GetType().Name}"); if (decay.Decay.HasValue) { writer.WritePropertyName("decay"); serializer.Serialize(writer, decay.Decay.Value); } } writer.WriteEndObject(); if (decay.MultiValueMode.HasValue) { writer.WritePropertyName("multi_value_mode"); serializer.Serialize(writer, decay.MultiValueMode.Value); } } writer.WriteEndObject(); return true; } private bool WriteNumericDecay(JsonWriter writer, IDecayFunction<double?, double?> value, JsonSerializer serializer) { if (value == null) return false; writer.WritePropertyName("origin"); serializer.Serialize(writer, value.Origin); writer.WritePropertyName("scale"); serializer.Serialize(writer, value.Scale); if (value.Offset != null) { writer.WritePropertyName("offset"); serializer.Serialize(writer, value.Offset); } return true; } private bool WriteDateDecay(JsonWriter writer, IDecayFunction<DateMath, Time> value, JsonSerializer serializer) { if (value == null || value.Field.IsConditionless()) return false; writer.WritePropertyName("origin"); serializer.Serialize(writer, value.Origin); writer.WritePropertyName("scale"); serializer.Serialize(writer, value.Scale); if (value.Offset != null) { writer.WritePropertyName("offset"); serializer.Serialize(writer, value.Offset); } return true; } private bool WriteGeoDecay(JsonWriter writer, IDecayFunction<GeoLocation, Distance> value, JsonSerializer serializer) { if (value == null || value.Field.IsConditionless()) return false; writer.WritePropertyName("origin"); serializer.Serialize(writer, value.Origin); writer.WritePropertyName("scale"); serializer.Serialize(writer, value.Scale); if (value.Offset != null) { writer.WritePropertyName("offset"); serializer.Serialize(writer, value.Offset); } return true; } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var jo = JObject.Load(reader); QueryContainer filter = jo.Property("filter")?.Value.ToObject<QueryContainer>(serializer); double? weight = jo.Property("weight")?.Value.ToObject<double?>();; IScoreFunction function = null; foreach (var prop in jo.Properties()) { switch(prop.Name) { case "exp": case "gauss": case "linear": var properties = prop.Value.Value<JObject>().Properties().ToList(); var fieldProp = properties.First(p => p.Name != "multi_value_mode"); var field = fieldProp.Name; var f = this.ReadDecayFunction(prop.Name, fieldProp.Value.Value<JObject>(), serializer); f.Field = field; var mv = properties.FirstOrDefault(p => p.Name == "multi_value_mode")?.Value; if (mv != null) f.MultiValueMode = serializer.Deserialize<MultiValueMode>(mv.CreateReader()); function = f; break; case "random_score": function = FromJson.ReadAs<RandomScoreFunction>(prop.Value.Value<JObject>().CreateReader(), null, null, serializer); break; case "field_value_factor": function = FromJson.ReadAs<FieldValueFactorFunction>(prop.Value.Value<JObject>().CreateReader(), null, null, serializer); break; case "script_score": function = FromJson.ReadAs<ScriptScoreFunction>(prop.Value.Value<JObject>().CreateReader(), null, null, serializer); break; } } if (function == null && weight.HasValue) function = new WeightFunction { Weight = weight }; else if (function == null) return null; //throw new Exception("error deserializing function score function"); function.Weight = weight; function.Filter = filter; return function; } private static IDictionary<string, Type> DecayTypeMapping = new Dictionary<string, Type> { { "exp_numeric", typeof(ExponentialDecayFunction) }, { "exp_date", typeof(ExponentialDateDecayFunction) }, { "exp_geo", typeof(ExponentialGeoDecayFunction) }, { "gauss_numeric", typeof(GaussDecayFunction) }, { "gauss_date", typeof(GaussDateDecayFunction) }, { "gauss_geo", typeof(GaussGeoDecayFunction) }, { "linear_numeric", typeof(LinearDecayFunction) }, { "linear_date", typeof(LinearDateDecayFunction) }, { "linear_geo", typeof(LinearGeoDecayFunction) }, }; private IDecayFunction ReadDecayFunction(string type, JObject o, JsonSerializer serializer) { var origin = o.Property("origin")?.Value.Type; if (origin == null) return null; var subType = "numeric"; switch(origin) { case JTokenType.String: subType = "date"; break; case JTokenType.Object: subType = "geo"; break; } var t = DecayTypeMapping[$"{type}_{subType}"]; return FromJson.Read(o.CreateReader(), t, null, serializer) as IDecayFunction; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Text.RegularExpressions; using log4net; using Nini.Config; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.OptionalModules.Avatar.Chat { // An instance of this class exists for every active region internal class RegionState { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly OpenMetaverse.Vector3 CenterOfRegion = new OpenMetaverse.Vector3(((int)Constants.RegionSize * 0.5f), ((int)Constants.RegionSize * 0.5f), 20); private const int DEBUG_CHANNEL = 2147483647; private static int _idk_ = 0; // Runtime variables; these values are assigned when the // IrcState is created and remain constant thereafter. internal string Region = String.Empty; internal string Host = String.Empty; internal string LocX = String.Empty; internal string LocY = String.Empty; internal string MA1 = String.Empty; internal string MA2 = String.Empty; internal string IDK = String.Empty; // System values - used only be the IRC classes themselves internal ChannelState cs = null; // associated IRC configuration internal Scene scene = null; // associated scene internal IConfig config = null; // configuration file reference internal bool enabled = true; // This list is used to keep track of who is here, and by // implication, who is not. internal List<IClientAPI> clients = new List<IClientAPI>(); // Setup runtime variable values public RegionState(Scene p_scene, IConfig p_config) { scene = p_scene; config = p_config; Region = scene.RegionInfo.RegionName; Host = scene.RegionInfo.ExternalHostName; LocX = Convert.ToString(scene.RegionInfo.RegionLocX); LocY = Convert.ToString(scene.RegionInfo.RegionLocY); MA1 = scene.RegionInfo.MasterAvatarFirstName; MA2 = scene.RegionInfo.MasterAvatarLastName; IDK = Convert.ToString(_idk_++); // OpenChannel conditionally establishes a connection to the // IRC server. The request will either succeed, or it will // throw an exception. ChannelState.OpenChannel(this, config); // Connect channel to world events scene.EventManager.OnChatFromWorld += OnSimChat; scene.EventManager.OnChatFromClient += OnSimChat; scene.EventManager.OnMakeRootAgent += OnMakeRootAgent; scene.EventManager.OnMakeChildAgent += OnMakeChildAgent; m_log.InfoFormat("[IRC-Region {0}] Initialization complete", Region); } // Auto cleanup when abandoned ~RegionState() { if (cs != null) cs.RemoveRegion(this); } // Called by PostInitialize after all regions have been created public void Open() { cs.Open(this); enabled = true; } // Called by IRCBridgeModule.Close immediately prior to unload // of the module for this region. This happens when the region // is being removed or the server is terminating. The IRC // BridgeModule will remove the region from the region list // when control returns. public void Close() { enabled = false; cs.Close(this); } // The agent has disconnected, cleanup associated resources private void OnClientLoggedOut(IClientAPI client) { try { if (clients.Contains(client)) { if (enabled && (cs.irc.Enabled) && (cs.irc.Connected) && (cs.ClientReporting)) { m_log.InfoFormat("[IRC-Region {0}]: {1} has left", Region, client.Name); //Check if this person is excluded from IRC if (!cs.ExcludeList.Contains(client.Name.ToLower())) { cs.irc.PrivMsg(cs.NoticeMessageFormat, cs.irc.Nick, Region, String.Format("{0} has left", client.Name)); } } client.OnLogout -= OnClientLoggedOut; client.OnConnectionClosed -= OnClientLoggedOut; clients.Remove(client); } } catch (Exception ex) { m_log.ErrorFormat("[IRC-Region {0}]: ClientLoggedOut exception: {1}", Region, ex.Message); m_log.Debug(ex); } } // This event indicates that the agent has left the building. We should treat that the same // as if the agent has logged out (we don't want cross-region noise - or do we?) private void OnMakeChildAgent(ScenePresence presence) { IClientAPI client = presence.ControllingClient; try { if (clients.Contains(client)) { if (enabled && (cs.irc.Enabled) && (cs.irc.Connected) && (cs.ClientReporting)) { string clientName = String.Format("{0} {1}", presence.Firstname, presence.Lastname); m_log.DebugFormat("[IRC-Region {0}] {1} has left", Region, clientName); cs.irc.PrivMsg(cs.NoticeMessageFormat, cs.irc.Nick, Region, String.Format("{0} has left", clientName)); } client.OnLogout -= OnClientLoggedOut; client.OnConnectionClosed -= OnClientLoggedOut; clients.Remove(client); } } catch (Exception ex) { m_log.ErrorFormat("[IRC-Region {0}]: MakeChildAgent exception: {1}", Region, ex.Message); m_log.Debug(ex); } } // An agent has entered the region (from another region). Add the client to the locally // known clients list private void OnMakeRootAgent(ScenePresence presence) { IClientAPI client = presence.ControllingClient; try { if (!clients.Contains(client)) { client.OnLogout += OnClientLoggedOut; client.OnConnectionClosed += OnClientLoggedOut; clients.Add(client); if (enabled && (cs.irc.Enabled) && (cs.irc.Connected) && (cs.ClientReporting)) { string clientName = String.Format("{0} {1}", presence.Firstname, presence.Lastname); m_log.DebugFormat("[IRC-Region {0}] {1} has arrived", Region, clientName); //Check if this person is excluded from IRC if (!cs.ExcludeList.Contains(clientName.ToLower())) { cs.irc.PrivMsg(cs.NoticeMessageFormat, cs.irc.Nick, Region, String.Format("{0} has arrived", clientName)); } } } } catch (Exception ex) { m_log.ErrorFormat("[IRC-Region {0}]: MakeRootAgent exception: {1}", Region, ex.Message); m_log.Debug(ex); } } // This handler detects chat events int he virtual world. public void OnSimChat(Object sender, OSChatMessage msg) { // early return if this comes from the IRC forwarder if (cs.irc.Equals(sender)) return; // early return if nothing to forward if (msg.Message.Length == 0) return; // check for commands coming from avatars or in-world // object (if commands are enabled) if (cs.CommandsEnabled && msg.Channel == cs.CommandChannel) { m_log.DebugFormat("[IRC-Region {0}] command on channel {1}: {2}", Region, msg.Channel, msg.Message); string[] messages = msg.Message.Split(' '); string command = messages[0].ToLower(); try { switch (command) { // These commands potentially require a change in the // underlying ChannelState. case "server": cs.Close(this); cs = cs.UpdateServer(this, messages[1]); cs.Open(this); break; case "port": cs.Close(this); cs = cs.UpdatePort(this, messages[1]); cs.Open(this); break; case "channel": cs.Close(this); cs = cs.UpdateChannel(this, messages[1]); cs.Open(this); break; case "nick": cs.Close(this); cs = cs.UpdateNickname(this, messages[1]); cs.Open(this); break; // These may also (but are less likely) to require a // change in ChannelState. case "client-reporting": cs = cs.UpdateClientReporting(this, messages[1]); break; case "in-channel": cs = cs.UpdateRelayIn(this, messages[1]); break; case "out-channel": cs = cs.UpdateRelayOut(this, messages[1]); break; // These are all taken to be temporary changes in state // so the underlying connector remains intact. But note // that with regions sharing a connector, there could // be interference. case "close": enabled = false; cs.Close(this); break; case "connect": enabled = true; cs.Open(this); break; case "reconnect": enabled = true; cs.Close(this); cs.Open(this); break; // This one is harmless as far as we can judge from here. // If it is not, then the complaints will eventually make // that evident. default: m_log.DebugFormat("[IRC-Region {0}] Forwarding unrecognized command to IRC : {1}", Region, msg.Message); cs.irc.Send(msg.Message); break; } } catch (Exception ex) { m_log.WarnFormat("[IRC-Region {0}] error processing in-world command channel input: {1}", Region, ex.Message); m_log.Debug(ex); } return; } // The command channel remains enabled, even if we have otherwise disabled the IRC // interface. if (!enabled) return; // drop messages unless they are on a valid in-world // channel as configured in the ChannelState if (!cs.ValidInWorldChannels.Contains(msg.Channel)) { m_log.DebugFormat("[IRC-Region {0}] dropping message {1} on channel {2}", Region, msg, msg.Channel); return; } ScenePresence avatar = null; string fromName = msg.From; if (msg.Sender != null) { avatar = scene.GetScenePresence(msg.Sender.AgentId); if (avatar != null) fromName = avatar.Name; } if (!cs.irc.Connected) { m_log.WarnFormat("[IRC-Region {0}] IRCConnector not connected: dropping message from {1}", Region, fromName); return; } m_log.DebugFormat("[IRC-Region {0}] heard on channel {1} : {2}", Region, msg.Channel, msg.Message); if (null != avatar && cs.RelayChat && (msg.Channel == 0 || msg.Channel == DEBUG_CHANNEL)) { string txt = msg.Message; if (txt.StartsWith("/me ")) txt = String.Format("{0} {1}", fromName, msg.Message.Substring(4)); cs.irc.PrivMsg(cs.PrivateMessageFormat, fromName, Region, txt); return; } if (null == avatar && cs.RelayPrivateChannels && null != cs.AccessPassword && msg.Channel == cs.RelayChannelOut) { Match m = cs.AccessPasswordRegex.Match(msg.Message); if (null != m) { m_log.DebugFormat("[IRC] relaying message from {0}: {1}", m.Groups["avatar"].ToString(), m.Groups["message"].ToString()); cs.irc.PrivMsg(cs.PrivateMessageFormat, m.Groups["avatar"].ToString(), scene.RegionInfo.RegionName, m.Groups["message"].ToString()); } } } // This method gives the region an opportunity to interfere with // message delivery. For now we just enforce the enable/disable // flag. internal void OSChat(Object irc, OSChatMessage msg) { if (enabled) { // m_log.DebugFormat("[IRC-OSCHAT] Region {0} being sent message", region.Region); msg.Scene = scene; scene.EventManager.TriggerOnChatBroadcast(irc, msg); } } // This supports any local message traffic that might be needed in // support of command processing. At present there is none. internal void LocalChat(string msg) { if (enabled) { OSChatMessage osm = new OSChatMessage(); osm.From = "IRC Agent"; osm.Message = msg; osm.Type = ChatTypeEnum.Region; osm.Position = CenterOfRegion; osm.Sender = null; osm.SenderUUID = OpenMetaverse.UUID.Zero; // Hmph! Still? osm.Channel = 0; OSChat(this, osm); } } } }
/* * 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 System.Collections.Generic; using System.Collections; using System.Runtime.Serialization; namespace Apache.Geode.Client.UnitTests { using NUnit.Framework; /// <summary> /// Interface class for wrappers of geode cacheable types. /// </summary> /// <remarks> /// This interface has various useful functions like setting value randomly, /// and finding checksum. /// </remarks> public abstract class CacheableWrapper { #region Protected members protected IGeodeSerializable m_cacheableObject = null; protected uint m_typeId; #endregion public virtual IGeodeSerializable Cacheable { get { return m_cacheableObject; } } public uint TypeId { get { return m_typeId; } set { m_typeId = value; } } public abstract void InitRandomValue(int maxSize); public abstract uint GetChecksum(IGeodeSerializable cacheableObject); public virtual uint GetChecksum() { return GetChecksum(m_cacheableObject); } } /// <summary> /// Interface class for wrappers of geode cacheable key types. /// </summary> /// <remarks> /// This interface has various useful functions like setting value randomly, /// and finding checksum, initializing key etc. /// </remarks> public abstract class CacheableKeyWrapper : CacheableWrapper { public override IGeodeSerializable Cacheable { get { return m_cacheableObject; } } public virtual ICacheableKey CacheableKey { get { return (ICacheableKey)m_cacheableObject; } } public abstract int MaxKeys { get; } public abstract void InitKey(int keyIndex, int maxSize); } public delegate CacheableWrapper CacheableWrapperDelegate(); public delegate CacheableKeyWrapper CacheableKeyWrapperDelegate(); /// <summary> /// Factory class to create <c>CacheableWrapper</c> objects. /// </summary> public static class CacheableWrapperFactory { #region Private members private static Dictionary<UInt32, CacheableKeyWrapperDelegate> m_registeredKeyTypeIdMap = new Dictionary<UInt32, CacheableKeyWrapperDelegate>(); private static Dictionary<UInt32, Delegate> m_registeredValueTypeIdMap = new Dictionary<UInt32, Delegate>(); private static Dictionary<UInt32, Type> m_typeIdNameMap = new Dictionary<UInt32, Type>(); #endregion #region Public methods public static CacheableWrapper CreateInstance(UInt32 typeId) { Delegate wrapperDelegate; lock (((ICollection)m_registeredValueTypeIdMap).SyncRoot) { if (m_registeredValueTypeIdMap.TryGetValue(typeId, out wrapperDelegate)) { CacheableWrapper wrapper = (CacheableWrapper)wrapperDelegate.DynamicInvoke(null); wrapper.TypeId = typeId; return wrapper; } } return null; } public static CacheableKeyWrapper CreateKeyInstance(UInt32 typeId) { CacheableKeyWrapperDelegate wrapperDelegate; lock (((ICollection)m_registeredKeyTypeIdMap).SyncRoot) { if (m_registeredKeyTypeIdMap.TryGetValue(typeId, out wrapperDelegate)) { CacheableKeyWrapper wrapper = wrapperDelegate(); wrapper.TypeId = typeId; return wrapper; } } return null; } public static void RegisterType(UInt32 typeId, Type type, CacheableWrapperDelegate wrapperDelegate) { m_registeredValueTypeIdMap[typeId] = wrapperDelegate; m_typeIdNameMap[typeId] = type; } public static void RegisterKeyType(UInt32 typeId, Type type, CacheableKeyWrapperDelegate wrapperDelegate) { m_registeredKeyTypeIdMap[typeId] = wrapperDelegate; m_registeredValueTypeIdMap[typeId] = wrapperDelegate; m_typeIdNameMap[typeId] = type; } public static void ClearStatics() { m_registeredKeyTypeIdMap.Clear(); m_registeredValueTypeIdMap.Clear(); m_typeIdNameMap.Clear(); } public static Type GetTypeForId(UInt32 typeId) { Type type; lock (((ICollection)m_typeIdNameMap).SyncRoot) { if (m_typeIdNameMap.TryGetValue(typeId, out type)) { return type; } } return null; } public static ICollection<UInt32> GetRegisteredKeyTypeIds() { return m_registeredKeyTypeIdMap.Keys; } public static ICollection<UInt32> GetRegisteredValueTypeIds() { return m_registeredValueTypeIdMap.Keys; } #endregion } }
// <copyright file=EnsensoManager.cs // <copyright> // Copyright (c) 2016, University of Stuttgart // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the Software), // to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // </copyright> // <license>MIT License</license> // <main contributors> // Markus Funk, Thomas Kosch, Sven Mayer // </main contributors> // <co-contributors> // Paul Brombosch, Mai El-Komy, Juana Heusler, // Matthias Hoppe, Robert Konrad, Alexander Martin // </co-contributors> // <patent information> // We are aware that this software implements patterns and ideas, // which might be protected by patents in your country. // Example patents in Germany are: // Patent reference number: DE 103 20 557.8 // Patent reference number: DE 10 2013 220 107.9 // Please make sure when using this software not to violate any existing patents in your country. // </patent information> // <date> 11/2/2016 12:25:56 PM</date> using System; using Ensenso; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; using Emgu.CV; using Emgu.CV.Structure; using System.Threading; using System.IO; using System.Text.RegularExpressions; namespace HciLab.Kinect { public class EnsensoManager { // constants private const int WIDTH = 640; private const int HEIGHT = 480; // TODO: Move that to settings private const string ENSENSOSETTINGS = "ensensosettings.json"; private static EnsensoManager m_Instance; private static bool m_InitFailed = false; private NxLibItem m_EnsensoCamera; private Bitmap m_Bitmap; private bool m_IsEnsensoCapturing; private Thread m_BackgroundThread; private EnsensoManager() { } public static EnsensoManager Instance { get { if (m_InitFailed) return null; if (m_Instance == null) { try { m_Instance = new EnsensoManager(); } catch { m_InitFailed = true; System.Console.WriteLine("Ensenso not initialized."); return null; } } return m_Instance; } } private void backgroundWorkerDoWork() { Thread.Sleep(1500); NxLibCommand capture = new NxLibCommand(NxLib.cmdCapture); NxLibCommand computeDisparityMap = new NxLibCommand(NxLib.cmdComputeDisparityMap); try { while (m_IsEnsensoCapturing) { capture.Execute(); // compute disparity computeDisparityMap.Execute(); int minDisp = m_EnsensoCamera[NxLib.itmParameters][NxLib.itmDisparityMap][NxLib.itmStereoMatching][NxLib.itmMinimumDisparity].AsInt(); int numDisp = m_EnsensoCamera[NxLib.itmParameters][NxLib.itmDisparityMap][NxLib.itmStereoMatching][NxLib.itmNumberOfDisparities].AsInt(); double timestamp; int nboc; short[] binaryData; int width, height, channels, bpe; bool isFloat; m_EnsensoCamera[NxLib.itmImages][NxLib.itmDisparityMap].GetBinaryDataInfo(out width, out height, out channels, out bpe, out isFloat, out timestamp); m_EnsensoCamera[NxLib.itmImages][NxLib.itmDisparityMap].GetBinaryData(out binaryData, out nboc, out timestamp); int disparityScale = 16; int scaledMinDisp = disparityScale * minDisp; int scaledNumDisp = disparityScale * numDisp; m_Bitmap = new Bitmap(width, height, PixelFormat.Format8bppIndexed); ColorPalette ncp = m_Bitmap.Palette; for (int i = 0; i < 256; i++) ncp.Entries[i] = Color.FromArgb(255, i, i, i); m_Bitmap.Palette = ncp; BitmapData bmpData = m_Bitmap.LockBits(new Rectangle(0, 0, m_Bitmap.Width, m_Bitmap.Height), ImageLockMode.WriteOnly, m_Bitmap.PixelFormat); int numBytes = bmpData.Height * bmpData.Stride; var data = new byte[numBytes]; for (int i = 0; i < bmpData.Height; i++) { for (int j = 0; j < bmpData.Width; j++) { int d = binaryData[i * bmpData.Width + j]; int o = i * bmpData.Stride + j; if (d < scaledMinDisp) { data[o] = (byte)255; } else if (d > scaledMinDisp + scaledNumDisp) { data[o] = (byte)0; } else { data[o] = (byte)(255.0 - ((d - scaledMinDisp) * (255.0 / scaledNumDisp)) + 0.5); } } } Marshal.Copy(data, 0, bmpData.Scan0, numBytes); m_Bitmap.UnlockBits(bmpData); Image<Bgra, Byte> colorFrame = new Image<Bgra, Byte>(m_Bitmap); Image<Gray, Int32> xFrame = new Image<Gray, float>(m_Bitmap).Convert<Gray, Int32>(); Image<Gray, Byte> grayImage = (new Image<Gray, float>(m_Bitmap)).Convert<Gray, Byte>(); //grayImage = grayImage.SmoothMedian(15); colorFrame = grayImage.Convert<Bgra, Byte>(); // event driven update CameraManager.Instance.SetImages(colorFrame, colorFrame, xFrame, xFrame); } } catch (NxLibException exception) { Console.WriteLine("A NxLibException occured: " + exception.GetErrorText()); Console.WriteLine(exception.StackTrace); Console.WriteLine("Error code: " + exception.GetErrorCode()); NxLibItem captureResult = capture.Result()[NxLib.itmErrorText]; Console.WriteLine(captureResult.AsString()); } catch (Exception exception) { Console.WriteLine("An exception in the EnsensoManager occured: " + exception.Message); } } public void initEnsensoCapturing() { //Init NxLib int result; NxLib.Initialize(out result, true); NxLib.CheckReturnCode(result); //do stuff NxLibItem root = new NxLibItem(); NxLibItem cameras = root[NxLib.itmCameras][NxLib.itmBySerialNo]; for (int i = 0; i < cameras.Count(); i++) { NxLibItem camera = cameras[i]; if (camera.Exists() && (camera[NxLib.itmType].Compare(NxLib.valStereo) == 0) && (camera[NxLib.itmStatus].Compare(NxLib.valAvailable) == 0)) { m_EnsensoCamera = cameras[camera[NxLib.itmSerialNumber].AsString()]; NxLibCommand open = new NxLibCommand(NxLib.cmdOpen); open.Parameters()[NxLib.itmCameras].Set(m_EnsensoCamera[NxLib.itmSerialNumber].AsString()); open.Execute(); // read parameters from JSON if (File.Exists(ENSENSOSETTINGS)) { String jsonSettings = File.ReadAllText(ENSENSOSETTINGS); jsonSettings = Regex.Replace(jsonSettings, @"\t|\n|\r", ""); m_EnsensoCamera[NxLib.itmParameters].SetJson(jsonSettings, true); } // setup thread this.m_IsEnsensoCapturing = true; m_BackgroundThread = new Thread(new ThreadStart(backgroundWorkerDoWork)); m_BackgroundThread.Start(); break; } } } public void stopEnsensoCapturing() { m_IsEnsensoCapturing = false; Thread.Sleep(1000); NxLibCommand close = new NxLibCommand(NxLib.cmdClose); try { close.Execute(); } catch (NxLibException exception) { Console.WriteLine("Exception occurred during closing Ensenso N10: " + exception.GetErrorText()); Console.WriteLine(exception.StackTrace); Console.WriteLine("Error code: " + exception.GetErrorCode()); } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: money/cards/transactions/card_authorization_response.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace HOLMS.Types.Money.Cards.Transactions { /// <summary>Holder for reflection information generated from money/cards/transactions/card_authorization_response.proto</summary> public static partial class CardAuthorizationResponseReflection { #region Descriptor /// <summary>File descriptor for money/cards/transactions/card_authorization_response.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static CardAuthorizationResponseReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cjptb25leS9jYXJkcy90cmFuc2FjdGlvbnMvY2FyZF9hdXRob3JpemF0aW9u", "X3Jlc3BvbnNlLnByb3RvEiRob2xtcy50eXBlcy5tb25leS5jYXJkcy50cmFu", "c2FjdGlvbnMaOm1vbmV5L2NhcmRzL3RyYW5zYWN0aW9ucy9wYXltZW50X2Nh", "cmRfc2FsZV9pbmRpY2F0b3IucHJvdG8aQ21vbmV5L2NhcmRzL3RyYW5zYWN0", "aW9ucy9wYXltZW50X2NhcmRfYXV0aG9yaXphdGlvbl9pbmRpY2F0b3IucHJv", "dG8ioAIKGUNhcmRBdXRob3JpemF0aW9uUmVzcG9uc2USVQoIcmVzcG9uc2UY", "ASABKA4yQy5ob2xtcy50eXBlcy5tb25leS5jYXJkcy50cmFuc2FjdGlvbnMu", "Q2FyZEF1dGhvcml6YXRpb25SZXNwb25zZUNvZGUSTAoEc2FsZRgCIAEoCzI+", "LmhvbG1zLnR5cGVzLm1vbmV5LmNhcmRzLnRyYW5zYWN0aW9ucy5QYXltZW50", "Q2FyZFNhbGVJbmRpY2F0b3ISXgoNYXV0aG9yaXphdGlvbhgDIAEoCzJHLmhv", "bG1zLnR5cGVzLm1vbmV5LmNhcmRzLnRyYW5zYWN0aW9ucy5QYXltZW50Q2Fy", "ZEF1dGhvcml6YXRpb25JbmRpY2F0b3IqigIKHUNhcmRBdXRob3JpemF0aW9u", "UmVzcG9uc2VDb2RlEhkKFUFVVEhPUklaQVRJT05fU1VDQ0VTUxAAEh8KG0FV", "VEhPUklaQVRJT05fQ0FSRF9ERUNMSU5FRBABEi0KKUFVVEhPUklaQVRJT05f", "VFJBTlNJRU5UX09QRVJBVElPTkFMX0VSUk9SEAISLQopQVVUSE9SSVpBVElP", "Tl9QRVJNQU5FTlRfT1BFUkFUSU9OQUxfRVJST1IQAxIpCiVBVVRIT1JJWkFU", "SU9OX05PX1RFUk1JTkFMU19DT05GSUdVUkVEEAQSJAogQVVUSE9SSVpBVElP", "Tl9BTU9VTlRfTk9UX0FMTE9XRUQQBUJBWhhtb25leS9jYXJkcy90cmFuc2Fj", "dGlvbnOqAiRIT0xNUy5UeXBlcy5Nb25leS5DYXJkcy5UcmFuc2FjdGlvbnNi", "BnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleIndicatorReflection.Descriptor, global::HOLMS.Types.Money.Cards.Transactions.PaymentCardAuthorizationIndicatorReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(new[] {typeof(global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponseCode), }, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse), global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponse.Parser, new[]{ "Response", "Sale", "Authorization" }, null, null, null) })); } #endregion } #region Enums public enum CardAuthorizationResponseCode { [pbr::OriginalName("AUTHORIZATION_SUCCESS")] AuthorizationSuccess = 0, [pbr::OriginalName("AUTHORIZATION_CARD_DECLINED")] AuthorizationCardDeclined = 1, [pbr::OriginalName("AUTHORIZATION_TRANSIENT_OPERATIONAL_ERROR")] AuthorizationTransientOperationalError = 2, [pbr::OriginalName("AUTHORIZATION_PERMANENT_OPERATIONAL_ERROR")] AuthorizationPermanentOperationalError = 3, [pbr::OriginalName("AUTHORIZATION_NO_TERMINALS_CONFIGURED")] AuthorizationNoTerminalsConfigured = 4, [pbr::OriginalName("AUTHORIZATION_AMOUNT_NOT_ALLOWED")] AuthorizationAmountNotAllowed = 5, } #endregion #region Messages public sealed partial class CardAuthorizationResponse : pb::IMessage<CardAuthorizationResponse> { private static readonly pb::MessageParser<CardAuthorizationResponse> _parser = new pb::MessageParser<CardAuthorizationResponse>(() => new CardAuthorizationResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<CardAuthorizationResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponseReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CardAuthorizationResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CardAuthorizationResponse(CardAuthorizationResponse other) : this() { response_ = other.response_; Sale = other.sale_ != null ? other.Sale.Clone() : null; Authorization = other.authorization_ != null ? other.Authorization.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CardAuthorizationResponse Clone() { return new CardAuthorizationResponse(this); } /// <summary>Field number for the "response" field.</summary> public const int ResponseFieldNumber = 1; private global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponseCode response_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponseCode Response { get { return response_; } set { response_ = value; } } /// <summary>Field number for the "sale" field.</summary> public const int SaleFieldNumber = 2; private global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleIndicator sale_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleIndicator Sale { get { return sale_; } set { sale_ = value; } } /// <summary>Field number for the "authorization" field.</summary> public const int AuthorizationFieldNumber = 3; private global::HOLMS.Types.Money.Cards.Transactions.PaymentCardAuthorizationIndicator authorization_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Money.Cards.Transactions.PaymentCardAuthorizationIndicator Authorization { get { return authorization_; } set { authorization_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as CardAuthorizationResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(CardAuthorizationResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Response != other.Response) return false; if (!object.Equals(Sale, other.Sale)) return false; if (!object.Equals(Authorization, other.Authorization)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Response != 0) hash ^= Response.GetHashCode(); if (sale_ != null) hash ^= Sale.GetHashCode(); if (authorization_ != null) hash ^= Authorization.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Response != 0) { output.WriteRawTag(8); output.WriteEnum((int) Response); } if (sale_ != null) { output.WriteRawTag(18); output.WriteMessage(Sale); } if (authorization_ != null) { output.WriteRawTag(26); output.WriteMessage(Authorization); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Response != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Response); } if (sale_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Sale); } if (authorization_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Authorization); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(CardAuthorizationResponse other) { if (other == null) { return; } if (other.Response != 0) { Response = other.Response; } if (other.sale_ != null) { if (sale_ == null) { sale_ = new global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleIndicator(); } Sale.MergeFrom(other.Sale); } if (other.authorization_ != null) { if (authorization_ == null) { authorization_ = new global::HOLMS.Types.Money.Cards.Transactions.PaymentCardAuthorizationIndicator(); } Authorization.MergeFrom(other.Authorization); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { response_ = (global::HOLMS.Types.Money.Cards.Transactions.CardAuthorizationResponseCode) input.ReadEnum(); break; } case 18: { if (sale_ == null) { sale_ = new global::HOLMS.Types.Money.Cards.Transactions.PaymentCardSaleIndicator(); } input.ReadMessage(sale_); break; } case 26: { if (authorization_ == null) { authorization_ = new global::HOLMS.Types.Money.Cards.Transactions.PaymentCardAuthorizationIndicator(); } input.ReadMessage(authorization_); break; } } } } } #endregion } #endregion Designer generated code
// 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.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { public class CSharpCommandLineParser : CommandLineParser { public static CSharpCommandLineParser Default { get; } = new CSharpCommandLineParser(); internal static CSharpCommandLineParser Interactive { get; } = new CSharpCommandLineParser(isInteractive: true); internal CSharpCommandLineParser(bool isInteractive = false) : base(CSharp.MessageProvider.Instance, isInteractive) { } internal override string RegularFileExtension { get { return ".cs"; } } internal override string ScriptFileExtension { get { return ".csx"; } } internal sealed override CommandLineArguments CommonParse(IEnumerable<string> args, string baseDirectory, string sdkDirectory, string additionalReferenceDirectories) { return Parse(args, baseDirectory, sdkDirectory, additionalReferenceDirectories); } /// <summary> /// Parses a command line. /// </summary> /// <param name="args">A collection of strings representing the command line arguments.</param> /// <param name="baseDirectory">The base directory used for qualifying file locations.</param> /// <param name="sdkDirectory">The directory to search for mscorlib.</param> /// <param name="additionalReferenceDirectories">A string representing additional reference paths.</param> /// <returns>a commandlinearguments object representing the parsed command line.</returns> public new CSharpCommandLineArguments Parse(IEnumerable<string> args, string baseDirectory, string sdkDirectory, string additionalReferenceDirectories = null) { List<Diagnostic> diagnostics = new List<Diagnostic>(); List<string> flattenedArgs = new List<string>(); List<string> scriptArgs = IsInteractive ? new List<string>() : null; FlattenArgs(args, diagnostics, flattenedArgs, scriptArgs, baseDirectory); string appConfigPath = null; bool displayLogo = true; bool displayHelp = false; bool optimize = false; bool checkOverflow = false; bool allowUnsafe = false; bool concurrentBuild = true; bool emitPdb = false; string pdbPath = null; bool noStdLib = false; string outputDirectory = baseDirectory; string outputFileName = null; string documentationPath = null; string errorLogPath = null; bool parseDocumentationComments = false; //Don't just null check documentationFileName because we want to do this even if the file name is invalid. bool utf8output = false; OutputKind outputKind = OutputKind.ConsoleApplication; SubsystemVersion subsystemVersion = SubsystemVersion.None; LanguageVersion languageVersion = CSharpParseOptions.Default.LanguageVersion; string mainTypeName = null; string win32ManifestFile = null; string win32ResourceFile = null; string win32IconFile = null; bool noWin32Manifest = false; Platform platform = Platform.AnyCpu; ulong baseAddress = 0; int fileAlignment = 0; bool? delaySignSetting = null; string keyFileSetting = null; string keyContainerSetting = null; List<ResourceDescription> managedResources = new List<ResourceDescription>(); List<CommandLineSourceFile> sourceFiles = new List<CommandLineSourceFile>(); List<CommandLineSourceFile> additionalFiles = new List<CommandLineSourceFile>(); bool sourceFilesSpecified = false; bool resourcesOrModulesSpecified = false; Encoding codepage = null; var checksumAlgorithm = SourceHashAlgorithm.Sha1; var defines = ArrayBuilder<string>.GetInstance(); List<CommandLineReference> metadataReferences = new List<CommandLineReference>(); List<CommandLineAnalyzerReference> analyzers = new List<CommandLineAnalyzerReference>(); List<string> libPaths = new List<string>(); List<string> keyFileSearchPaths = new List<string>(); List<string> usings = new List<string>(); var generalDiagnosticOption = ReportDiagnostic.Default; var diagnosticOptions = new Dictionary<string, ReportDiagnostic>(); var noWarns = new Dictionary<string, ReportDiagnostic>(); var warnAsErrors = new Dictionary<string, ReportDiagnostic>(); int warningLevel = 4; bool highEntropyVA = false; bool printFullPaths = false; string moduleAssemblyName = null; string moduleName = null; List<string> features = new List<string>(); string runtimeMetadataVersion = null; bool errorEndLocation = false; bool reportAnalyzer = false; CultureInfo preferredUILang = null; string touchedFilesPath = null; var sqmSessionGuid = Guid.Empty; // Process ruleset files first so that diagnostic severity settings specified on the command line via // /nowarn and /warnaserror can override diagnostic severity settings specified in the ruleset file. if (!IsInteractive) { foreach (string arg in flattenedArgs) { string name, value; if (TryParseOption(arg, out name, out value) && (name == "ruleset")) { var unquoted = RemoveAllQuotes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); } else { generalDiagnosticOption = GetDiagnosticOptionsFromRulesetFile(diagnosticOptions, diagnostics, unquoted, baseDirectory); } } } } foreach (string arg in flattenedArgs) { Debug.Assert(!arg.StartsWith("@", StringComparison.Ordinal)); string name, value; if (!TryParseOption(arg, out name, out value)) { sourceFiles.AddRange(ParseFileArgument(arg, baseDirectory, diagnostics)); sourceFilesSpecified = true; continue; } switch (name) { case "?": case "help": displayHelp = true; continue; case "r": case "reference": metadataReferences.AddRange(ParseAssemblyReferences(arg, value, diagnostics, embedInteropTypes: false)); continue; case "a": case "analyzer": analyzers.AddRange(ParseAnalyzers(arg, value, diagnostics)); continue; case "d": case "define": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg); continue; } IEnumerable<Diagnostic> defineDiagnostics; defines.AddRange(ParseConditionalCompilationSymbols(value, out defineDiagnostics)); diagnostics.AddRange(defineDiagnostics); continue; case "codepage": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } var encoding = TryParseEncodingName(value); if (encoding == null) { AddDiagnostic(diagnostics, ErrorCode.FTL_BadCodepage, value); continue; } codepage = encoding; continue; case "checksumalgorithm": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } var newChecksumAlgorithm = TryParseHashAlgorithmName(value); if (newChecksumAlgorithm == SourceHashAlgorithm.None) { AddDiagnostic(diagnostics, ErrorCode.FTL_BadChecksumAlgorithm, value); continue; } checksumAlgorithm = newChecksumAlgorithm; continue; case "checked": case "checked+": if (value != null) { break; } checkOverflow = true; continue; case "checked-": if (value != null) break; checkOverflow = false; continue; case "features": if (value == null) { features.Clear(); } else { features.Add(value); } continue; case "noconfig": // It is already handled (see CommonCommandLineCompiler.cs). continue; case "sqmsessionguid": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_MissingGuidForOption, "<text>", name); } else { if (!Guid.TryParse(value, out sqmSessionGuid)) { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFormatForGuidForOption, value, name); } } continue; case "preferreduilang": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg); continue; } try { preferredUILang = new CultureInfo(value); if (CorLightup.Desktop.IsUserCustomCulture(preferredUILang) ?? false) { // Do not use user custom cultures. preferredUILang = null; } } catch (CultureNotFoundException) { } if (preferredUILang == null) { AddDiagnostic(diagnostics, ErrorCode.WRN_BadUILang, value); } continue; #if DEBUG case "attachdebugger": Debugger.Launch(); continue; #endif } if (IsInteractive) { switch (name) { // interactive: case "rp": case "referencepath": // TODO: should it really go to libPaths? ParseAndResolveReferencePaths(name, value, baseDirectory, libPaths, MessageID.IDS_REFERENCEPATH_OPTION, diagnostics); continue; case "u": case "using": usings.AddRange(ParseUsings(arg, value, diagnostics)); continue; } } else { switch (name) { case "out": if (string.IsNullOrWhiteSpace(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { ParseOutputFile(value, diagnostics, baseDirectory, out outputFileName, out outputDirectory); } continue; case "t": case "target": if (value == null) { break; // force 'unrecognized option' } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidTarget); } else { outputKind = ParseTarget(value, diagnostics); } continue; case "moduleassemblyname": value = value != null ? value.Unquote() : null; if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg); } else if (!MetadataHelpers.IsValidAssemblyOrModuleName(value)) { // Dev11 C# doesn't check the name (VB does) AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidAssemblyName, "<text>", arg); } else { moduleAssemblyName = value; } continue; case "modulename": var unquotedModuleName = RemoveAllQuotes(value); if (string.IsNullOrEmpty(unquotedModuleName)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "modulename"); continue; } else { moduleName = unquotedModuleName; } continue; case "platform": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<string>", arg); } else { platform = ParsePlatform(value, diagnostics); } continue; case "recurse": if (value == null) { break; // force 'unrecognized option' } else if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { int before = sourceFiles.Count; sourceFiles.AddRange(ParseRecurseArgument(value, baseDirectory, diagnostics)); if (sourceFiles.Count > before) { sourceFilesSpecified = true; } } continue; case "doc": parseDocumentationComments = true; if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); continue; } string unquoted = RemoveAllQuotes(value); if (string.IsNullOrEmpty(unquoted)) { // CONSIDER: This diagnostic exactly matches dev11, but it would be simpler (and more consistent with /out) // if we just let the next case handle /doc:"". AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/doc:"); // Different argument. } else { documentationPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory); } continue; case "addmodule": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/addmodule:"); } else if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { // NOTE(tomat): Dev10 used to report CS1541: ERR_CantIncludeDirectory if the path was a directory. // Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory. // An error will be reported by the assembly manager anyways. metadataReferences.AddRange(ParseSeparatedPaths(value).Select(path => new CommandLineReference(path, MetadataReferenceProperties.Module))); resourcesOrModulesSpecified = true; } continue; case "l": case "link": metadataReferences.AddRange(ParseAssemblyReferences(arg, value, diagnostics, embedInteropTypes: true)); continue; case "win32res": win32ResourceFile = GetWin32Setting(arg, value, diagnostics); continue; case "win32icon": win32IconFile = GetWin32Setting(arg, value, diagnostics); continue; case "win32manifest": win32ManifestFile = GetWin32Setting(arg, value, diagnostics); noWin32Manifest = false; continue; case "nowin32manifest": noWin32Manifest = true; win32ManifestFile = null; continue; case "res": case "resource": if (value == null) { break; // Dev11 reports inrecognized option } var embeddedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: true); if (embeddedResource != null) { managedResources.Add(embeddedResource); resourcesOrModulesSpecified = true; } continue; case "linkres": case "linkresource": if (value == null) { break; // Dev11 reports inrecognized option } var linkedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: false); if (linkedResource != null) { managedResources.Add(linkedResource); resourcesOrModulesSpecified = true; } continue; case "debug": emitPdb = true; // unused, parsed for backward compat only if (value != null) { if (value.IsEmpty()) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), name); } else if (!string.Equals(value, "full", StringComparison.OrdinalIgnoreCase) && !string.Equals(value, "pdbonly", StringComparison.OrdinalIgnoreCase)) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadDebugType, value); } } continue; case "debug+": //guard against "debug+:xx" if (value != null) break; emitPdb = true; continue; case "debug-": if (value != null) break; emitPdb = false; continue; case "o": case "optimize": case "o+": case "optimize+": if (value != null) break; optimize = true; continue; case "o-": case "optimize-": if (value != null) break; optimize = false; continue; case "p": case "parallel": case "p+": case "parallel+": if (value != null) break; concurrentBuild = true; continue; case "p-": case "parallel-": if (value != null) break; concurrentBuild = false; continue; case "warnaserror": case "warnaserror+": if (value == null) { generalDiagnosticOption = ReportDiagnostic.Error; // Reset specific warnaserror options (since last /warnaserror flag on the command line always wins), // and bump warnings to errors. warnAsErrors.Clear(); foreach (var key in diagnosticOptions.Keys) { if (diagnosticOptions[key] == ReportDiagnostic.Warn) { warnAsErrors[key] = ReportDiagnostic.Error; } } continue; } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddWarnings(warnAsErrors, ReportDiagnostic.Error, ParseWarnings(value)); } continue; case "warnaserror-": if (value == null) { generalDiagnosticOption = ReportDiagnostic.Default; // Clear specific warnaserror options (since last /warnaserror flag on the command line always wins). warnAsErrors.Clear(); continue; } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { foreach (var id in ParseWarnings(value)) { ReportDiagnostic ruleSetValue; if (diagnosticOptions.TryGetValue(id, out ruleSetValue)) { warnAsErrors[id] = ruleSetValue; } else { warnAsErrors[id] = ReportDiagnostic.Default; } } } continue; case "w": case "warn": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); continue; } int newWarningLevel; if (string.IsNullOrEmpty(value) || !int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out newWarningLevel)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else if (newWarningLevel < 0 || newWarningLevel > 4) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadWarningLevel, name); } else { warningLevel = newWarningLevel; } continue; case "nowarn": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); continue; } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddWarnings(noWarns, ReportDiagnostic.Suppress, ParseWarnings(value)); } continue; case "unsafe": case "unsafe+": if (value != null) break; allowUnsafe = true; continue; case "unsafe-": if (value != null) break; allowUnsafe = false; continue; case "langversion": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/langversion:"); } else if (!TryParseLanguageVersion(value, CSharpParseOptions.Default.LanguageVersion, out languageVersion)) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadCompatMode, value); } continue; case "delaysign": case "delaysign+": if (value != null) { break; } delaySignSetting = true; continue; case "delaysign-": if (value != null) { break; } delaySignSetting = false; continue; case "keyfile": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, "keyfile"); } else { keyFileSetting = RemoveAllQuotes(value); } // NOTE: Dev11/VB also clears "keycontainer", see also: // // MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by // MSDN: custom attribute) in the same compilation, the compiler will first try the key container. // MSDN: If that succeeds, then the assembly is signed with the information in the key container. // MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile. // MSDN: If that succeeds, the assembly is signed with the information in the key file and the key // MSDN: information will be installed in the key container (similar to sn -i) so that on the next // MSDN: compilation, the key container will be valid. continue; case "keycontainer": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "keycontainer"); } else { keyContainerSetting = value; } // NOTE: Dev11/VB also clears "keyfile", see also: // // MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by // MSDN: custom attribute) in the same compilation, the compiler will first try the key container. // MSDN: If that succeeds, then the assembly is signed with the information in the key container. // MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile. // MSDN: If that succeeds, the assembly is signed with the information in the key file and the key // MSDN: information will be installed in the key container (similar to sn -i) so that on the next // MSDN: compilation, the key container will be valid. continue; case "highentropyva": case "highentropyva+": if (value != null) break; highEntropyVA = true; continue; case "highentropyva-": if (value != null) break; highEntropyVA = false; continue; case "nologo": displayLogo = false; continue; case "baseaddress": ulong newBaseAddress; if (string.IsNullOrEmpty(value) || !TryParseUInt64(value, out newBaseAddress)) { if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddDiagnostic(diagnostics, ErrorCode.ERR_BadBaseNumber, value); } } else { baseAddress = newBaseAddress; } continue; case "subsystemversion": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "subsystemversion"); continue; } // It seems VS 2012 just silently corrects invalid values and suppresses the error message SubsystemVersion version = SubsystemVersion.None; if (SubsystemVersion.TryParse(value, out version)) { subsystemVersion = version; } else { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidSubsystemVersion, value); } continue; case "touchedfiles": unquoted = RemoveAllQuotes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "touchedfiles"); continue; } else { touchedFilesPath = unquoted; } continue; case "bugreport": UnimplementedSwitch(diagnostics, name); continue; case "utf8output": if (value != null) break; utf8output = true; continue; case "m": case "main": // Remove any quotes for consistent behaviour as MSBuild can return quoted or // unquoted main. unquoted = RemoveAllQuotes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } mainTypeName = unquoted; continue; case "fullpaths": if (value != null) break; printFullPaths = true; continue; case "filealign": ushort newAlignment; if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else if (!TryParseUInt16(value, out newAlignment)) { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFileAlignment, value); } else if (!CompilationOptions.IsValidFileAlignment(newAlignment)) { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFileAlignment, value); } else { fileAlignment = newAlignment; } continue; case "pdb": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { pdbPath = ParsePdbPath(value, diagnostics, baseDirectory); } continue; case "errorendlocation": errorEndLocation = true; continue; case "reportanalyzer": reportAnalyzer = true; continue; case "nostdlib": case "nostdlib+": if (value != null) break; noStdLib = true; continue; case "lib": ParseAndResolveReferencePaths(name, value, baseDirectory, libPaths, MessageID.IDS_LIB_OPTION, diagnostics); continue; case "nostdlib-": if (value != null) break; noStdLib = false; continue; case "errorreport": continue; case "errorlog": unquoted = RemoveAllQuotes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, ":<file>", RemoveAllQuotes(arg)); } else { errorLogPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory); } continue; case "appconfig": unquoted = RemoveAllQuotes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, ":<text>", RemoveAllQuotes(arg)); } else { appConfigPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory); } continue; case "runtimemetadataversion": unquoted = RemoveAllQuotes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } runtimeMetadataVersion = unquoted; continue; case "ruleset": // The ruleset arg has already been processed in a separate pass above. continue; case "additionalfile": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<file list>", name); continue; } additionalFiles.AddRange(ParseAdditionalFileArgument(value, baseDirectory, diagnostics)); continue; } } AddDiagnostic(diagnostics, ErrorCode.ERR_BadSwitch, arg); } foreach (var o in warnAsErrors) { diagnosticOptions[o.Key] = o.Value; } // Specific nowarn options always override specific warnaserror options. foreach (var o in noWarns) { diagnosticOptions[o.Key] = o.Value; } if (!IsInteractive && !sourceFilesSpecified && (outputKind.IsNetModule() || !resourcesOrModulesSpecified)) { AddDiagnostic(diagnostics, diagnosticOptions, ErrorCode.WRN_NoSources); } if (!noStdLib) { metadataReferences.Insert(0, new CommandLineReference(Path.Combine(sdkDirectory, "mscorlib.dll"), MetadataReferenceProperties.Assembly)); } if (!platform.Requires64Bit()) { if (baseAddress > uint.MaxValue - 0x8000) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadBaseNumber, string.Format("0x{0:X}", baseAddress)); baseAddress = 0; } } // add additional reference paths if specified if (!string.IsNullOrWhiteSpace(additionalReferenceDirectories)) { ParseAndResolveReferencePaths(null, additionalReferenceDirectories, baseDirectory, libPaths, MessageID.IDS_LIB_ENV, diagnostics); } ImmutableArray<string> referencePaths = BuildSearchPaths(sdkDirectory, libPaths); ValidateWin32Settings(win32ResourceFile, win32IconFile, win32ManifestFile, outputKind, diagnostics); // Dev11 searches for the key file in the current directory and assembly output directory. // We always look to base directory and then examine the search paths. keyFileSearchPaths.Add(baseDirectory); if (baseDirectory != outputDirectory) { keyFileSearchPaths.Add(outputDirectory); } if (!emitPdb) { if (pdbPath != null) { // Can't give a PDB file name and turn off debug information AddDiagnostic(diagnostics, ErrorCode.ERR_MissingDebugSwitch); } } string compilationName; GetCompilationAndModuleNames(diagnostics, outputKind, sourceFiles, sourceFilesSpecified, moduleAssemblyName, ref outputFileName, ref moduleName, out compilationName); var parseOptions = new CSharpParseOptions ( languageVersion: languageVersion, preprocessorSymbols: defines.ToImmutableAndFree(), documentationMode: parseDocumentationComments ? DocumentationMode.Diagnose : DocumentationMode.None, kind: SourceCodeKind.Regular, features: ParseFeatures(features) ); var scriptParseOptions = parseOptions.WithKind(SourceCodeKind.Script); var options = new CSharpCompilationOptions ( outputKind: outputKind, moduleName: moduleName, mainTypeName: mainTypeName, scriptClassName: WellKnownMemberNames.DefaultScriptClassName, usings: usings, optimizationLevel: optimize ? OptimizationLevel.Release : OptimizationLevel.Debug, checkOverflow: checkOverflow, allowUnsafe: allowUnsafe, concurrentBuild: concurrentBuild, cryptoKeyContainer: keyContainerSetting, cryptoKeyFile: keyFileSetting, delaySign: delaySignSetting, platform: platform, generalDiagnosticOption: generalDiagnosticOption, warningLevel: warningLevel, specificDiagnosticOptions: diagnosticOptions ); var emitOptions = new EmitOptions ( metadataOnly: false, debugInformationFormat: DebugInformationFormat.Pdb, pdbFilePath: null, // to be determined later outputNameOverride: null, // to be determined later baseAddress: baseAddress, highEntropyVirtualAddressSpace: highEntropyVA, fileAlignment: fileAlignment, subsystemVersion: subsystemVersion, runtimeMetadataVersion: runtimeMetadataVersion ); // add option incompatibility errors if any diagnostics.AddRange(options.Errors); return new CSharpCommandLineArguments { IsInteractive = IsInteractive, BaseDirectory = baseDirectory, Errors = diagnostics.AsImmutable(), Utf8Output = utf8output, CompilationName = compilationName, OutputFileName = outputFileName, PdbPath = pdbPath, EmitPdb = emitPdb, OutputDirectory = outputDirectory, DocumentationPath = documentationPath, ErrorLogPath = errorLogPath, AppConfigPath = appConfigPath, SourceFiles = sourceFiles.AsImmutable(), Encoding = codepage, ChecksumAlgorithm = checksumAlgorithm, MetadataReferences = metadataReferences.AsImmutable(), AnalyzerReferences = analyzers.AsImmutable(), AdditionalFiles = additionalFiles.AsImmutable(), ReferencePaths = referencePaths, KeyFileSearchPaths = keyFileSearchPaths.AsImmutable(), Win32ResourceFile = win32ResourceFile, Win32Icon = win32IconFile, Win32Manifest = win32ManifestFile, NoWin32Manifest = noWin32Manifest, DisplayLogo = displayLogo, DisplayHelp = displayHelp, ManifestResources = managedResources.AsImmutable(), CompilationOptions = options, ParseOptions = IsInteractive ? scriptParseOptions : parseOptions, EmitOptions = emitOptions, ScriptArguments = scriptArgs.AsImmutableOrEmpty(), TouchedFilesPath = touchedFilesPath, PrintFullPaths = printFullPaths, ShouldIncludeErrorEndLocation = errorEndLocation, PreferredUILang = preferredUILang, SqmSessionGuid = sqmSessionGuid, ReportAnalyzer = reportAnalyzer }; } private static void ParseAndResolveReferencePaths(string switchName, string switchValue, string baseDirectory, List<string> builder, MessageID origin, List<Diagnostic> diagnostics) { if (string.IsNullOrEmpty(switchValue)) { Debug.Assert(!string.IsNullOrEmpty(switchName)); AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_PathList.Localize(), switchName); return; } foreach (string path in ParseSeparatedPaths(switchValue)) { string resolvedPath = FileUtilities.ResolveRelativePath(path, baseDirectory); if (resolvedPath == null) { AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, path, origin.Localize(), MessageID.IDS_DirectoryHasInvalidPath.Localize()); } else if (!PortableShim.Directory.Exists(resolvedPath)) { AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, path, origin.Localize(), MessageID.IDS_DirectoryDoesNotExist.Localize()); } else { builder.Add(resolvedPath); } } } private static string GetWin32Setting(string arg, string value, List<Diagnostic> diagnostics) { if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { string noQuotes = RemoveAllQuotes(value); if (string.IsNullOrWhiteSpace(noQuotes)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { return noQuotes; } } return null; } private void GetCompilationAndModuleNames( List<Diagnostic> diagnostics, OutputKind outputKind, List<CommandLineSourceFile> sourceFiles, bool sourceFilesSpecified, string moduleAssemblyName, ref string outputFileName, ref string moduleName, out string compilationName) { string simpleName; if (outputFileName == null) { // In C#, if the output file name isn't specified explicitly, then executables take their // names from the files containing their entrypoints and libraries derive their names from // their first input files. if (!IsInteractive && !sourceFilesSpecified) { AddDiagnostic(diagnostics, ErrorCode.ERR_OutputNeedsName); simpleName = null; } else if (outputKind.IsApplication()) { simpleName = null; } else { simpleName = PathUtilities.RemoveExtension(PathUtilities.GetFileName(sourceFiles.FirstOrDefault().Path)); outputFileName = simpleName + outputKind.GetDefaultExtension(); if (simpleName.Length == 0 && !outputKind.IsNetModule()) { AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, outputFileName); outputFileName = simpleName = null; } } } else { simpleName = PathUtilities.RemoveExtension(outputFileName); if (simpleName.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, outputFileName); outputFileName = simpleName = null; } } if (outputKind.IsNetModule()) { Debug.Assert(!IsInteractive); compilationName = moduleAssemblyName; } else { if (moduleAssemblyName != null) { AddDiagnostic(diagnostics, ErrorCode.ERR_AssemblyNameOnNonModule); } compilationName = simpleName; } if (moduleName == null) { moduleName = outputFileName; } } private static ImmutableArray<string> BuildSearchPaths(string sdkDirectory, List<string> libPaths) { var builder = ArrayBuilder<string>.GetInstance(); // Match how Dev11 builds the list of search paths // see PCWSTR LangCompiler::GetSearchPath() // current folder first -- base directory is searched by default // SDK path is specified or current runtime directory builder.Add(sdkDirectory); // libpath builder.AddRange(libPaths); return builder.ToImmutableAndFree(); } public static IEnumerable<string> ParseConditionalCompilationSymbols(string value, out IEnumerable<Diagnostic> diagnostics) { Diagnostic myDiagnostic = null; value = value.TrimEnd(null); // Allow a trailing semicolon or comma in the options if (!value.IsEmpty() && (value.Last() == ';' || value.Last() == ',')) { value = value.Substring(0, value.Length - 1); } string[] values = value.Split(new char[] { ';', ',' } /*, StringSplitOptions.RemoveEmptyEntries*/); var defines = new ArrayBuilder<string>(values.Length); foreach (string id in values) { string trimmedId = id.Trim(); if (SyntaxFacts.IsValidIdentifier(trimmedId)) { defines.Add(trimmedId); } else if (myDiagnostic == null) { myDiagnostic = Diagnostic.Create(CSharp.MessageProvider.Instance, (int)ErrorCode.WRN_DefineIdentifierRequired, trimmedId); } } diagnostics = myDiagnostic == null ? SpecializedCollections.EmptyEnumerable<Diagnostic>() : SpecializedCollections.SingletonEnumerable(myDiagnostic); return defines.AsEnumerable(); } private static Platform ParsePlatform(string value, IList<Diagnostic> diagnostics) { switch (value.ToLowerInvariant()) { case "x86": return Platform.X86; case "x64": return Platform.X64; case "itanium": return Platform.Itanium; case "anycpu": return Platform.AnyCpu; case "anycpu32bitpreferred": return Platform.AnyCpu32BitPreferred; case "arm": return Platform.Arm; default: AddDiagnostic(diagnostics, ErrorCode.ERR_BadPlatformType, value); return Platform.AnyCpu; } } private static OutputKind ParseTarget(string value, IList<Diagnostic> diagnostics) { switch (value.ToLowerInvariant()) { case "exe": return OutputKind.ConsoleApplication; case "winexe": return OutputKind.WindowsApplication; case "library": return OutputKind.DynamicallyLinkedLibrary; case "module": return OutputKind.NetModule; case "appcontainerexe": return OutputKind.WindowsRuntimeApplication; case "winmdobj": return OutputKind.WindowsRuntimeMetadata; default: AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidTarget); return OutputKind.ConsoleApplication; } } private static IEnumerable<string> ParseUsings(string arg, string value, IList<Diagnostic> diagnostics) { if (value.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Namespace1.Localize(), arg); yield break; } foreach (var u in value.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { yield return u; } } private IEnumerable<CommandLineAnalyzerReference> ParseAnalyzers(string arg, string value, List<Diagnostic> diagnostics) { if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); yield break; } else if (value.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); yield break; } List<string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList(); foreach (string path in paths) { yield return new CommandLineAnalyzerReference(path); } } private IEnumerable<CommandLineReference> ParseAssemblyReferences(string arg, string value, IList<Diagnostic> diagnostics, bool embedInteropTypes) { if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); yield break; } else if (value.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); yield break; } // /r:"reference" // /r:alias=reference // /r:alias="reference" // /r:reference;reference // /r:"path;containing;semicolons" // /r:"unterminated_quotes // /r:"quotes"in"the"middle // /r:alias=reference;reference ... error 2034 // /r:nonidf=reference ... error 1679 int eqlOrQuote = value.IndexOfAny(new[] { '"', '=' }); string alias; if (eqlOrQuote >= 0 && value[eqlOrQuote] == '=') { alias = value.Substring(0, eqlOrQuote); value = value.Substring(eqlOrQuote + 1); if (!SyntaxFacts.IsValidIdentifier(alias)) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadExternIdentifier, alias); yield break; } } else { alias = null; } List<string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList(); if (alias != null) { if (paths.Count > 1) { AddDiagnostic(diagnostics, ErrorCode.ERR_OneAliasPerReference, value); yield break; } if (paths.Count == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_AliasMissingFile, alias); yield break; } } foreach (string path in paths) { // NOTE(tomat): Dev10 used to report CS1541: ERR_CantIncludeDirectory if the path was a directory. // Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory. var aliases = (alias != null) ? ImmutableArray.Create(alias) : ImmutableArray<string>.Empty; var properties = new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases, embedInteropTypes); yield return new CommandLineReference(path, properties); } } private static void ValidateWin32Settings(string win32ResourceFile, string win32IconResourceFile, string win32ManifestFile, OutputKind outputKind, IList<Diagnostic> diagnostics) { if (win32ResourceFile != null) { if (win32IconResourceFile != null) { AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndIcon); } if (win32ManifestFile != null) { AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndManifest); } } if (outputKind.IsNetModule() && win32ManifestFile != null) { AddDiagnostic(diagnostics, ErrorCode.WRN_CantHaveManifestForModule); } } internal static ResourceDescription ParseResourceDescription( string arg, string resourceDescriptor, string baseDirectory, IList<Diagnostic> diagnostics, bool embedded) { string filePath; string fullPath; string fileName; string resourceName; string accessibility; ParseResourceDescription( resourceDescriptor, baseDirectory, false, out filePath, out fullPath, out fileName, out resourceName, out accessibility); bool isPublic; if (accessibility == null) { // If no accessibility is given, we default to "public". // NOTE: Dev10 distinguishes between null and empty/whitespace-only. isPublic = true; } else if (string.Equals(accessibility, "public", StringComparison.OrdinalIgnoreCase)) { isPublic = true; } else if (string.Equals(accessibility, "private", StringComparison.OrdinalIgnoreCase)) { isPublic = false; } else { AddDiagnostic(diagnostics, ErrorCode.ERR_BadResourceVis, accessibility); return null; } if (string.IsNullOrEmpty(filePath)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); return null; } if (fullPath == null || string.IsNullOrWhiteSpace(fileName) || fileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) { AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, filePath); return null; } Func<Stream> dataProvider = () => { // Use FileShare.ReadWrite because the file could be opened by the current process. // For example, it is an XML doc file produced by the build. return PortableShim.FileStream.Create(fullPath, PortableShim.FileMode.Open, PortableShim.FileAccess.Read, PortableShim.FileShare.ReadWrite); }; return new ResourceDescription(resourceName, fileName, dataProvider, isPublic, embedded, checkArgs: false); } private static bool TryParseLanguageVersion(string str, LanguageVersion defaultVersion, out LanguageVersion version) { if (str == null) { version = defaultVersion; return true; } switch (str.ToLowerInvariant()) { case "iso-1": version = LanguageVersion.CSharp1; return true; case "iso-2": version = LanguageVersion.CSharp2; return true; case "default": version = defaultVersion; return true; default: int versionNumber; if (int.TryParse(str, NumberStyles.None, CultureInfo.InvariantCulture, out versionNumber) && ((LanguageVersion)versionNumber).IsValid()) { version = (LanguageVersion)versionNumber; return true; } version = defaultVersion; return false; } } private static IEnumerable<string> ParseWarnings(string value) { value = value.Unquote(); string[] values = value.Split(new char[] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries); foreach (string id in values) { ushort number; if (ushort.TryParse(id, NumberStyles.Integer, CultureInfo.InvariantCulture, out number) && ErrorFacts.IsWarning((ErrorCode)number)) { // The id refers to a compiler warning. yield return CSharp.MessageProvider.Instance.GetIdForErrorCode(number); } else { // Previous versions of the compiler used to report a warning (CS1691) // whenever an unrecognized warning code was supplied in /nowarn or // /warnaserror. We no longer generate a warning in such cases. // Instead we assume that the unrecognized id refers to a custom diagnostic. yield return id; } } } private static void AddWarnings(Dictionary<string, ReportDiagnostic> d, ReportDiagnostic kind, IEnumerable<string> items) { foreach (var id in items) { ReportDiagnostic existing; if (d.TryGetValue(id, out existing)) { // Rewrite the existing value with the latest one unless it is for /nowarn. if (existing != ReportDiagnostic.Suppress) d[id] = kind; } else { d.Add(id, kind); } } } private static void UnimplementedSwitch(IList<Diagnostic> diagnostics, string switchName) { AddDiagnostic(diagnostics, ErrorCode.WRN_UnimplementedCommandLineSwitch, "/" + switchName); } private static void UnimplementedSwitchValue(IList<Diagnostic> diagnostics, string switchName, string value) { AddDiagnostic(diagnostics, ErrorCode.WRN_UnimplementedCommandLineSwitch, "/" + switchName + ":" + value); } internal override void GenerateErrorForNoFilesFoundInRecurse(string path, IList<Diagnostic> diagnostics) { // no error in csc.exe } private static void AddDiagnostic(IList<Diagnostic> diagnostics, ErrorCode errorCode) { diagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)errorCode)); } private static void AddDiagnostic(IList<Diagnostic> diagnostics, ErrorCode errorCode, params object[] arguments) { diagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)errorCode, arguments)); } /// <summary> /// Diagnostic for the errorCode added if the warningOptions does not mention suppressed for the errorCode. /// </summary> private static void AddDiagnostic(IList<Diagnostic> diagnostics, Dictionary<string, ReportDiagnostic> warningOptions, ErrorCode errorCode, params object[] arguments) { int code = (int)errorCode; ReportDiagnostic value; warningOptions.TryGetValue(CSharp.MessageProvider.Instance.GetIdForErrorCode(code), out value); if (value != ReportDiagnostic.Suppress) { AddDiagnostic(diagnostics, errorCode, arguments); } } } }
// // Copyright (c) 2004-2017 Jaroslaw Kowalski <[email protected]>, 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. // namespace NLog.UnitTests.LayoutRenderers { using System; using System.Globalization; using Xunit; public class MessageTests : NLogTestBase { [Fact] public void MessageWithoutPaddingTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("a"); AssertDebugLastMessage("debug", "a"); logger.Debug("a{0}", 1); AssertDebugLastMessage("debug", "a1"); logger.Debug("a{0}{1}", 1, "2"); AssertDebugLastMessage("debug", "a12"); logger.Debug(CultureInfo.InvariantCulture, "a{0}", new DateTime(2005, 1, 1)); AssertDebugLastMessage("debug", "a01/01/2005 00:00:00"); } [Fact] public void MessageRightPaddingTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message:padding=3}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("a"); AssertDebugLastMessage("debug", " a"); logger.Debug("a{0}", 1); AssertDebugLastMessage("debug", " a1"); logger.Debug("a{0}{1}", 1, "2"); AssertDebugLastMessage("debug", "a12"); logger.Debug(CultureInfo.InvariantCulture, "a{0}", new DateTime(2005, 1, 1)); AssertDebugLastMessage("debug", "a01/01/2005 00:00:00"); } [Fact] public void MessageFixedLengthRightPaddingLeftAlignmentTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message:padding=3:fixedlength=true}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("a"); AssertDebugLastMessage("debug", " a"); logger.Debug("a{0}", 1); AssertDebugLastMessage("debug", " a1"); logger.Debug("a{0}{1}", 1, "2"); AssertDebugLastMessage("debug", "a12"); logger.Debug(CultureInfo.InvariantCulture, "a{0}", new DateTime(2005, 1, 1)); AssertDebugLastMessage("debug", "a01"); } [Fact] public void MessageFixedLengthRightPaddingRightAlignmentTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message:padding=3:fixedlength=true:alignmentOnTruncation=right}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("a"); AssertDebugLastMessage("debug", " a"); logger.Debug("a{0}", 1); AssertDebugLastMessage("debug", " a1"); logger.Debug("a{0}{1}", 1, "2"); AssertDebugLastMessage("debug", "a12"); logger.Debug(CultureInfo.InvariantCulture, "a{0}", new DateTime(2005, 1, 1)); AssertDebugLastMessage("debug", ":00"); } [Fact] public void MessageLeftPaddingTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message:padding=-3:padcharacter=x}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("a"); AssertDebugLastMessage("debug", "axx"); logger.Debug("a{0}", 1); AssertDebugLastMessage("debug", "a1x"); logger.Debug("a{0}{1}", 1, "2"); AssertDebugLastMessage("debug", "a12"); logger.Debug(CultureInfo.InvariantCulture, "a{0}", new DateTime(2005, 1, 1)); AssertDebugLastMessage("debug", "a01/01/2005 00:00:00"); } [Fact] public void MessageFixedLengthLeftPaddingLeftAlignmentTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message:padding=-3:padcharacter=x:fixedlength=true}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("a"); AssertDebugLastMessage("debug", "axx"); logger.Debug("a{0}", 1); AssertDebugLastMessage("debug", "a1x"); logger.Debug("a{0}{1}", 1, "2"); AssertDebugLastMessage("debug", "a12"); logger.Debug(CultureInfo.InvariantCulture, "a{0}", new DateTime(2005, 1, 1)); AssertDebugLastMessage("debug", "a01"); } [Fact] public void MessageFixedLengthLeftPaddingRightAlignmentTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message:padding=-3:padcharacter=x:fixedlength=true:alignmentOnTruncation=right}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("a"); AssertDebugLastMessage("debug", "axx"); logger.Debug("a{0}", 1); AssertDebugLastMessage("debug", "a1x"); logger.Debug("a{0}{1}", 1, "2"); AssertDebugLastMessage("debug", "a12"); logger.Debug(CultureInfo.InvariantCulture, "a{0}", new DateTime(2005, 1, 1)); AssertDebugLastMessage("debug", ":00"); } [Fact] public void MessageWithExceptionTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog exceptionLoggingOldStyle='true'> <targets><target name='debug' type='Debug' layout='${message:withException=true}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("a"); AssertDebugLastMessage("debug", "a"); var ex = new InvalidOperationException("Exception message."); string newline = Environment.NewLine; #pragma warning disable 0618 // Obsolete method requires testing until completely removed. logger.DebugException("Foo", ex); AssertDebugLastMessage("debug", "Foo" + newline + ex.ToString()); #pragma warning restore 0618 logger.Debug(ex, "Foo"); AssertDebugLastMessage("debug", "Foo" + newline + ex.ToString()); logger.Debug( "Foo", ex); AssertDebugLastMessage("debug", "Foo" + newline + ex.ToString()); } [Fact] public void MessageWithExceptionAndCustomSeparatorTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message:withException=true:exceptionSeparator=,}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("a"); AssertDebugLastMessage("debug", "a"); var ex = new InvalidOperationException("Exception message."); #pragma warning disable 0618 // Obsolete method requires testing until completely removed. logger.DebugException("Foo", ex); AssertDebugLastMessage("debug", "Foo," + ex.ToString()); #pragma warning restore 0618 logger.Debug(ex, "Foo"); AssertDebugLastMessage("debug", "Foo," + ex.ToString()); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; using HttpTwo.Internal; namespace HttpTwo { public class Http2ConnectionSettings { public Http2ConnectionSettings(string url, X509CertificateCollection certificates = null) : this(new Uri(url), certificates) { } public Http2ConnectionSettings(Uri uri, X509CertificateCollection certificates = null) : this(uri.Host, (uint)uri.Port, uri.Scheme == Uri.UriSchemeHttps, certificates) { } public Http2ConnectionSettings(string host, uint port = 80, bool useTls = false, X509CertificateCollection certificates = null) { Host = host; Port = port; UseTls = useTls; Certificates = certificates; } public string Host { get; private set; } public uint Port { get; private set; } public bool UseTls { get; private set; } public X509CertificateCollection Certificates { get; private set; } public TimeSpan ConnectionTimeout { get; set; } = TimeSpan.FromSeconds(60); public bool DisablePushPromise { get; set; } = false; } public class Http2Connection { public const string ConnectionPreface = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"; static Http2Connection() { ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true; } public Http2Connection(Http2ConnectionSettings connectionSettings, IStreamManager streamManager, IFlowControlManager flowControlManager) { this.flowControlManager = flowControlManager; this.streamManager = streamManager; ConnectionSettings = connectionSettings; Settings = new Http2Settings(); queue = new FrameQueue(flowControlManager); } public Http2Settings Settings { get; private set; } public Http2ConnectionSettings ConnectionSettings { get; private set; } IFlowControlManager flowControlManager; readonly IStreamManager streamManager; readonly FrameQueue queue; TcpClient tcp; Stream clientStream; SslStream sslStream; long receivedDataCount = 0; public uint ReceivedDataCount => (uint)Interlocked.Read(ref receivedDataCount); public async Task Connect() { if (IsConnected()) return; tcp = new TcpClient { // Disable Nagle for HTTP/2 NoDelay = true }; await tcp.ConnectAsync(ConnectionSettings.Host, (int)ConnectionSettings.Port).ConfigureAwait(false); if (ConnectionSettings.UseTls) { sslStream = new SslStream(tcp.GetStream(), false, (sender, certificate, chain, sslPolicyErrors) => true); #if NETCOREAPP2_1 // .NET Core 2.1 introduces SslClientAuthenticationOptions // which allows us to set the SslApplicationProtocol (ALPN) which // for HTTP/2 is required, and should be set to h2 for direct to TLS connections // (h2c should be set for upgraded connections) var authOptions = new SslClientAuthenticationOptions { ApplicationProtocols = new List<SslApplicationProtocol> { SslApplicationProtocol.Http2 }, // ALPN h2 EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12, TargetHost = ConnectionSettings.Host, ClientCertificates = ConnectionSettings.Certificates ?? new X509CertificateCollection() }; await sslStream.AuthenticateAsClientAsync( authOptions, new CancellationToken(false)) .ConfigureAwait(false); #else // Fall back to no ALPN support for frameworks which don't support it await sslStream.AuthenticateAsClientAsync( ConnectionSettings.Host, ConnectionSettings.Certificates ?? new X509CertificateCollection(), System.Security.Authentication.SslProtocols.Tls12, false).ConfigureAwait(false); #endif clientStream = sslStream; } else { clientStream = tcp.GetStream(); } // Ensure we have a size for the stream '0' flowControlManager.GetWindowSize(0); // Send out preface data var prefaceData = System.Text.Encoding.ASCII.GetBytes(ConnectionPreface); await clientStream.WriteAsync (prefaceData, 0, prefaceData.Length).ConfigureAwait (false); await clientStream.FlushAsync ().ConfigureAwait (false); // Start reading the stream on another thread var readTask = Task.Factory.StartNew (() => { try { Read (); } catch (Exception ex) { Log.Debug ("Read error: " + ex); Disconnect (); } }, TaskCreationOptions.LongRunning); readTask.ContinueWith (t => { // TODO: Handle the error Disconnect (); }, TaskContinuationOptions.OnlyOnFaulted).Forget (); // Start a thread to handle writing queued frames to the stream var writeTask = Task.Factory.StartNew (Write, TaskCreationOptions.LongRunning); writeTask.ContinueWith (t => { // TODO: Handle the error Disconnect (); }, TaskContinuationOptions.OnlyOnFaulted).Forget (); // Send initial blank settings frame var s = new SettingsFrame (); if (ConnectionSettings.DisablePushPromise) s.EnablePush = false; await QueueFrame (s).ConfigureAwait (false); } public void Disconnect () { // complete the blocking collection queue.Complete (); // We want to clean up the connection here so let's just try to close/dispose // everything // Analysis disable EmptyGeneralCatchClause try { clientStream.Close (); } catch { } try { clientStream.Dispose (); } catch { } if (ConnectionSettings.UseTls && sslStream != null) { try { sslStream.Close (); } catch { } try { sslStream.Dispose (); } catch { } } try { tcp.Client.Shutdown (SocketShutdown.Both); } catch { } try { tcp.Client.Dispose (); } catch { } try { tcp.Close (); } catch { } // Analysis restore EmptyGeneralCatchClause tcp = null; sslStream = null; clientStream = null; } bool IsConnected () { if (tcp == null || clientStream == null || tcp.Client == null) return false; if (!tcp.Connected || !tcp.Client.Connected) return false; if (!tcp.Client.Poll (1000, SelectMode.SelectRead) || !tcp.Client.Poll (1000, SelectMode.SelectWrite)) return false; return true; } readonly SemaphoreSlim lockWrite = new SemaphoreSlim (1); public async Task QueueFrame(IFrame frame) => await queue.Enqueue(frame).ConfigureAwait(false); public async Task FreeUpWindowSpace () { var sizeToFree = Interlocked.Exchange (ref receivedDataCount, 0); if (sizeToFree <= 0) return; await QueueFrame (new WindowUpdateFrame { StreamIdentifier = 0, WindowSizeIncrement = (uint)sizeToFree }).ConfigureAwait (false); } readonly List<byte> buffer = new List<byte> (); async void Read() { int rx; var b = new byte[4096]; while (true) { try { rx = await clientStream.ReadAsync(b, 0, b.Length).ConfigureAwait (false); } catch { rx = -1; } if (rx > 0) { // Add all the bytes read into our buffer list for (var i = 0; i < rx; i++) buffer.Add (b [i]); while (true) { // We need at least 9 bytes to process the frame // 9 octets is the frame header length if (buffer.Count < 9) break; // Find out the frame length // which is a 24 bit uint, so we need to convert this as c# uint is 32 bit var flen = new byte[4]; flen [0] = 0x0; flen [1] = buffer.ElementAt (0); flen [2] = buffer.ElementAt (1); flen [3] = buffer.ElementAt (2); var frameLength = BitConverter.ToUInt32 (flen.EnsureBigEndian (), 0); // If we are expecting a payload that's bigger than what's in our buffer // we should keep reading from the stream if (buffer.Count - 9 < frameLength) break; // If we made it this far, the buffer has all the data we need, let's get it out to process var data = buffer.GetRange (0, (int)frameLength + 9).ToArray (); // remove the processed info from the buffer buffer.RemoveRange (0, (int)frameLength + 9); // Get the Frame Type so we can instantiate the right subclass var frameType = data [3]; // 4th byte in frame header is TYPE // we need to turn the stream id into a uint var frameStreamIdData = new byte[4]; Array.Copy (data, 5, frameStreamIdData, 0, 4); var frameStreamId = Util.ConvertFromUInt31 (frameStreamIdData.EnsureBigEndian ()); // Create a new typed instance of our abstract Frame var frame = Frame.Create ((FrameType)frameType); try { // Call the specific subclass implementation to parse frame.Parse (data); } catch (Exception ex) { Log.Error ("Parsing Frame Failed: {0}", ex); throw ex; } Log.Debug ("<- {0}", frame); // If it's a settings frame, we should note the values and // return the frame with the Ack flag set if (frame.Type == FrameType.Settings) { var settingsFrame = frame as SettingsFrame; // Update our instance of settings with the new data Settings.UpdateFromFrame (settingsFrame, flowControlManager); // See if this was an ack, if not, return an empty // ack'd settings frame if (!settingsFrame.Ack) await QueueFrame (new SettingsFrame { Ack = true }).ConfigureAwait (false); } else if (frame.Type == FrameType.Ping) { var pingFrame = frame as PingFrame; // See if we need to respond to the ping request (if it's not-ack'd) if (!pingFrame.Ack) { // Ack and respond pingFrame.Ack = true; await QueueFrame (pingFrame).ConfigureAwait (false); } } else if (frame.Type == FrameType.Data) { // Increment our received data counter Interlocked.Add (ref receivedDataCount, frame.PayloadLength); } // Some other frame type, just pass it along to the stream var stream = await streamManager.Get(frameStreamId).ConfigureAwait (false); stream.ProcessReceivedFrames(frame); } } else { // Stream was closed, break out of reading loop break; } } // Cleanup Disconnect(); } async Task Write () { foreach (var frame in queue.GetConsumingEnumerable ()) { if (frame == null) { Log.Info ("Null frame dequeued"); continue; } Log.Debug ("-> {0}", frame); var data = frame.ToBytes ().ToArray (); await lockWrite.WaitAsync ().ConfigureAwait (false); try { await clientStream.WriteAsync(data, 0, data.Length).ConfigureAwait (false); await clientStream.FlushAsync().ConfigureAwait (false); var stream = await streamManager.Get (frame.StreamIdentifier).ConfigureAwait (false); stream.ProcessSentFrame (frame); } catch (Exception ex) { Log.Warn ("Error writing frame: {0}, {1}", frame.StreamIdentifier, ex); } finally { lockWrite.Release(); } } } } }
// HtmlAgilityPack V1.0 - Simon Mourier <simon underscore mourier at hotmail dot com> // Marius: Added pragma warning to disable obsolete warnings #region using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Security; using System.Security.Permissions; using System.Text; using System.Xml; using System.Xml.Serialization; using System.Xml.Xsl; using Microsoft.Win32; #endregion namespace Marius.Html.Hap { /// <summary> /// A utility class to get HTML document from HTTP. /// </summary> public class HtmlWeb { #region Delegates /// <summary> /// Represents the method that will handle the PostResponse event. /// </summary> public delegate void PostResponseHandler(HttpWebRequest request, HttpWebResponse response); /// <summary> /// Represents the method that will handle the PreHandleDocument event. /// </summary> public delegate void PreHandleDocumentHandler(HtmlDocument document); /// <summary> /// Represents the method that will handle the PreRequest event. /// </summary> public delegate bool PreRequestHandler(HttpWebRequest request); #endregion #region Fields private bool _autoDetectEncoding = true; private bool _cacheOnly; private string _cachePath; private bool _fromCache; private int _requestDuration; private Uri _responseUri; private HttpStatusCode _statusCode = HttpStatusCode.OK; private int _streamBufferSize = 1024; private bool _useCookies; private bool _usingCache; private string _userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:x.x.x) Gecko/20041107 Firefox/x.x"; /// <summary> /// Occurs after an HTTP request has been executed. /// </summary> public PostResponseHandler PostResponse; /// <summary> /// Occurs before an HTML document is handled. /// </summary> public PreHandleDocumentHandler PreHandleDocument; /// <summary> /// Occurs before an HTTP request is executed. /// </summary> public PreRequestHandler PreRequest; #endregion #region Static Members private static Dictionary<string, string> _mimeTypes; internal static Dictionary<string, string> MimeTypes { get { if (_mimeTypes != null) return _mimeTypes; //agentsmith spellcheck disable _mimeTypes = new Dictionary<string, string>(); _mimeTypes.Add(".3dm", "x-world/x-3dmf"); _mimeTypes.Add(".3dmf", "x-world/x-3dmf"); _mimeTypes.Add(".a", "application/octet-stream"); _mimeTypes.Add(".aab", "application/x-authorware-bin"); _mimeTypes.Add(".aam", "application/x-authorware-map"); _mimeTypes.Add(".aas", "application/x-authorware-seg"); _mimeTypes.Add(".abc", "text/vnd.abc"); _mimeTypes.Add(".acgi", "text/html"); _mimeTypes.Add(".afl", "video/animaflex"); _mimeTypes.Add(".ai", "application/postscript"); _mimeTypes.Add(".aif", "audio/aiff"); _mimeTypes.Add(".aif", "audio/x-aiff"); _mimeTypes.Add(".aifc", "audio/aiff"); _mimeTypes.Add(".aifc", "audio/x-aiff"); _mimeTypes.Add(".aiff", "audio/aiff"); _mimeTypes.Add(".aiff", "audio/x-aiff"); _mimeTypes.Add(".aim", "application/x-aim"); _mimeTypes.Add(".aip", "text/x-audiosoft-intra"); _mimeTypes.Add(".ani", "application/x-navi-animation"); _mimeTypes.Add(".aos", "application/x-nokia-9000-communicator-add-on-software"); _mimeTypes.Add(".aps", "application/mime"); _mimeTypes.Add(".arc", "application/octet-stream"); _mimeTypes.Add(".arj", "application/arj"); _mimeTypes.Add(".arj", "application/octet-stream"); _mimeTypes.Add(".art", "image/x-jg"); _mimeTypes.Add(".asf", "video/x-ms-asf"); _mimeTypes.Add(".asm", "text/x-asm"); _mimeTypes.Add(".asp", "text/asp"); _mimeTypes.Add(".asx", "application/x-mplayer2"); _mimeTypes.Add(".asx", "video/x-ms-asf"); _mimeTypes.Add(".asx", "video/x-ms-asf-plugin"); _mimeTypes.Add(".au", "audio/basic"); _mimeTypes.Add(".au", "audio/x-au"); _mimeTypes.Add(".avi", "application/x-troff-msvideo"); _mimeTypes.Add(".avi", "video/avi"); _mimeTypes.Add(".avi", "video/msvideo"); _mimeTypes.Add(".avi", "video/x-msvideo"); _mimeTypes.Add(".avs", "video/avs-video"); _mimeTypes.Add(".bcpio", "application/x-bcpio"); _mimeTypes.Add(".bin", "application/mac-binary"); _mimeTypes.Add(".bin", "application/macbinary"); _mimeTypes.Add(".bin", "application/octet-stream"); _mimeTypes.Add(".bin", "application/x-binary"); _mimeTypes.Add(".bin", "application/x-macbinary"); _mimeTypes.Add(".bm", "image/bmp"); _mimeTypes.Add(".bmp", "image/bmp"); _mimeTypes.Add(".bmp", "image/x-windows-bmp"); _mimeTypes.Add(".boo", "application/book"); _mimeTypes.Add(".book", "application/book"); _mimeTypes.Add(".boz", "application/x-bzip2"); _mimeTypes.Add(".bsh", "application/x-bsh"); _mimeTypes.Add(".bz", "application/x-bzip"); _mimeTypes.Add(".bz2", "application/x-bzip2"); _mimeTypes.Add(".c", "text/plain"); _mimeTypes.Add(".c", "text/x-c"); _mimeTypes.Add(".c++", "text/plain"); _mimeTypes.Add(".cat", "application/vnd.ms-pki.seccat"); _mimeTypes.Add(".cc", "text/plain"); _mimeTypes.Add(".cc", "text/x-c"); _mimeTypes.Add(".ccad", "application/clariscad"); _mimeTypes.Add(".cco", "application/x-cocoa"); _mimeTypes.Add(".cdf", "application/cdf"); _mimeTypes.Add(".cdf", "application/x-cdf"); _mimeTypes.Add(".cdf", "application/x-netcdf"); _mimeTypes.Add(".cer", "application/pkix-cert"); _mimeTypes.Add(".cer", "application/x-x509-ca-cert"); _mimeTypes.Add(".cha", "application/x-chat"); _mimeTypes.Add(".chat", "application/x-chat"); _mimeTypes.Add(".class", "application/java"); _mimeTypes.Add(".class", "application/java-byte-code"); _mimeTypes.Add(".class", "application/x-java-class"); _mimeTypes.Add(".com", "application/octet-stream"); _mimeTypes.Add(".com", "text/plain"); _mimeTypes.Add(".conf", "text/plain"); _mimeTypes.Add(".cpio", "application/x-cpio"); _mimeTypes.Add(".cpp", "text/x-c"); _mimeTypes.Add(".cpt", "application/mac-compactpro"); _mimeTypes.Add(".cpt", "application/x-compactpro"); _mimeTypes.Add(".cpt", "application/x-cpt"); _mimeTypes.Add(".crl", "application/pkcs-crl"); _mimeTypes.Add(".crl", "application/pkix-crl"); _mimeTypes.Add(".crt", "application/pkix-cert"); _mimeTypes.Add(".crt", "application/x-x509-ca-cert"); _mimeTypes.Add(".crt", "application/x-x509-user-cert"); _mimeTypes.Add(".csh", "application/x-csh"); _mimeTypes.Add(".csh", "text/x-script.csh"); _mimeTypes.Add(".css", "application/x-pointplus"); _mimeTypes.Add(".css", "text/css"); _mimeTypes.Add(".cxx", "text/plain"); _mimeTypes.Add(".dcr", "application/x-director"); _mimeTypes.Add(".deepv", "application/x-deepv"); _mimeTypes.Add(".def", "text/plain"); _mimeTypes.Add(".der", "application/x-x509-ca-cert"); _mimeTypes.Add(".dif", "video/x-dv"); _mimeTypes.Add(".dir", "application/x-director"); _mimeTypes.Add(".dl", "video/dl"); _mimeTypes.Add(".dl", "video/x-dl"); _mimeTypes.Add(".doc", "application/msword"); _mimeTypes.Add(".dot", "application/msword"); _mimeTypes.Add(".dp", "application/commonground"); _mimeTypes.Add(".drw", "application/drafting"); _mimeTypes.Add(".dump", "application/octet-stream"); _mimeTypes.Add(".dv", "video/x-dv"); _mimeTypes.Add(".dvi", "application/x-dvi"); _mimeTypes.Add(".dwf", "model/vnd.dwf"); _mimeTypes.Add(".dwg", "application/acad"); _mimeTypes.Add(".dwg", "image/vnd.dwg"); _mimeTypes.Add(".dwg", "image/x-dwg"); _mimeTypes.Add(".dxf", "application/dxf"); _mimeTypes.Add(".dxf", "image/vnd.dwg"); _mimeTypes.Add(".dxf", "image/x-dwg"); _mimeTypes.Add(".dxr", "application/x-director"); _mimeTypes.Add(".el", "text/x-script.elisp"); _mimeTypes.Add(".elc", "application/x-bytecode.elisp"); _mimeTypes.Add(".elc", "application/x-elc"); _mimeTypes.Add(".env", "application/x-envoy"); _mimeTypes.Add(".eps", "application/postscript"); _mimeTypes.Add(".es", "application/x-esrehber"); _mimeTypes.Add(".etx", "text/x-setext"); _mimeTypes.Add(".evy", "application/envoy"); _mimeTypes.Add(".evy", "application/x-envoy"); _mimeTypes.Add(".exe", "application/octet-stream"); _mimeTypes.Add(".f", "text/plain"); _mimeTypes.Add(".f", "text/x-fortran"); _mimeTypes.Add(".f77", "text/x-fortran"); _mimeTypes.Add(".f90", "text/plain"); _mimeTypes.Add(".f90", "text/x-fortran"); _mimeTypes.Add(".fdf", "application/vnd.fdf"); _mimeTypes.Add(".fif", "application/fractals"); _mimeTypes.Add(".fif", "image/fif"); _mimeTypes.Add(".fli", "video/fli"); _mimeTypes.Add(".fli", "video/x-fli"); _mimeTypes.Add(".flo", "image/florian"); _mimeTypes.Add(".flx", "text/vnd.fmi.flexstor"); _mimeTypes.Add(".fmf", "video/x-atomic3d-feature"); _mimeTypes.Add(".for", "text/plain"); _mimeTypes.Add(".for", "text/x-fortran"); _mimeTypes.Add(".fpx", "image/vnd.fpx"); _mimeTypes.Add(".fpx", "image/vnd.net-fpx"); _mimeTypes.Add(".frl", "application/freeloader"); _mimeTypes.Add(".funk", "audio/make"); _mimeTypes.Add(".g", "text/plain"); _mimeTypes.Add(".g3", "image/g3fax"); _mimeTypes.Add(".gif", "image/gif"); _mimeTypes.Add(".gl", "video/gl"); _mimeTypes.Add(".gl", "video/x-gl"); _mimeTypes.Add(".gsd", "audio/x-gsm"); _mimeTypes.Add(".gsm", "audio/x-gsm"); _mimeTypes.Add(".gsp", "application/x-gsp"); _mimeTypes.Add(".gss", "application/x-gss"); _mimeTypes.Add(".gtar", "application/x-gtar"); _mimeTypes.Add(".gz", "application/x-compressed"); _mimeTypes.Add(".gz", "application/x-gzip"); _mimeTypes.Add(".gzip", "application/x-gzip"); _mimeTypes.Add(".gzip", "multipart/x-gzip"); _mimeTypes.Add(".h", "text/plain"); _mimeTypes.Add(".h", "text/x-h"); _mimeTypes.Add(".hdf", "application/x-hdf"); _mimeTypes.Add(".help", "application/x-helpfile"); _mimeTypes.Add(".hgl", "application/vnd.hp-hpgl"); _mimeTypes.Add(".hh", "text/plain"); _mimeTypes.Add(".hh", "text/x-h"); _mimeTypes.Add(".hlb", "text/x-script"); _mimeTypes.Add(".hlp", "application/hlp"); _mimeTypes.Add(".hlp", "application/x-helpfile"); _mimeTypes.Add(".hlp", "application/x-winhelp"); _mimeTypes.Add(".hpg", "application/vnd.hp-hpgl"); _mimeTypes.Add(".hpgl", "application/vnd.hp-hpgl"); _mimeTypes.Add(".hqx", "application/binhex"); _mimeTypes.Add(".hqx", "application/binhex4"); _mimeTypes.Add(".hqx", "application/mac-binhex"); _mimeTypes.Add(".hqx", "application/mac-binhex40"); _mimeTypes.Add(".hqx", "application/x-binhex40"); _mimeTypes.Add(".hqx", "application/x-mac-binhex40"); _mimeTypes.Add(".hta", "application/hta"); _mimeTypes.Add(".htc", "text/x-component"); _mimeTypes.Add(".htm", "text/html"); _mimeTypes.Add(".html", "text/html"); _mimeTypes.Add(".htmls", "text/html"); _mimeTypes.Add(".htt", "text/webviewhtml"); _mimeTypes.Add(".htx", "text/html"); _mimeTypes.Add(".ice", "x-conference/x-cooltalk"); _mimeTypes.Add(".ico", "image/x-icon"); _mimeTypes.Add(".idc", "text/plain"); _mimeTypes.Add(".ief", "image/ief"); _mimeTypes.Add(".iefs", "image/ief"); _mimeTypes.Add(".iges", "application/iges"); _mimeTypes.Add(".iges", "model/iges"); _mimeTypes.Add(".igs", "application/iges"); _mimeTypes.Add(".igs", "model/iges"); _mimeTypes.Add(".ima", "application/x-ima"); _mimeTypes.Add(".imap", "application/x-httpd-imap"); _mimeTypes.Add(".inf", "application/inf"); _mimeTypes.Add(".ins", "application/x-internett-signup"); _mimeTypes.Add(".ip", "application/x-ip2"); _mimeTypes.Add(".isu", "video/x-isvideo"); _mimeTypes.Add(".it", "audio/it"); _mimeTypes.Add(".iv", "application/x-inventor"); _mimeTypes.Add(".ivr", "i-world/i-vrml"); _mimeTypes.Add(".ivy", "application/x-livescreen"); _mimeTypes.Add(".jam", "audio/x-jam"); _mimeTypes.Add(".jav", "text/plain"); _mimeTypes.Add(".jav", "text/x-java-source"); _mimeTypes.Add(".java", "text/plain"); _mimeTypes.Add(".java", "text/x-java-source"); _mimeTypes.Add(".jcm", "application/x-java-commerce"); _mimeTypes.Add(".jfif", "image/jpeg"); _mimeTypes.Add(".jfif", "image/pjpeg"); _mimeTypes.Add(".jfif-tbnl", "image/jpeg"); _mimeTypes.Add(".jpe", "image/jpeg"); _mimeTypes.Add(".jpe", "image/pjpeg"); _mimeTypes.Add(".jpeg", "image/jpeg"); _mimeTypes.Add(".jpeg", "image/pjpeg"); _mimeTypes.Add(".jpg", "image/jpeg"); _mimeTypes.Add(".jpg", "image/pjpeg"); _mimeTypes.Add(".jps", "image/x-jps"); _mimeTypes.Add(".js", "application/x-javascript"); _mimeTypes.Add(".js", "application/javascript"); _mimeTypes.Add(".js", "application/ecmascript"); _mimeTypes.Add(".js", "text/javascript"); _mimeTypes.Add(".js", "text/ecmascript"); _mimeTypes.Add(".jut", "image/jutvision"); _mimeTypes.Add(".kar", "audio/midi"); _mimeTypes.Add(".kar", "music/x-karaoke"); _mimeTypes.Add(".ksh", "application/x-ksh"); _mimeTypes.Add(".ksh", "text/x-script.ksh"); _mimeTypes.Add(".la", "audio/nspaudio"); _mimeTypes.Add(".la", "audio/x-nspaudio"); _mimeTypes.Add(".lam", "audio/x-liveaudio"); _mimeTypes.Add(".latex", "application/x-latex"); _mimeTypes.Add(".lha", "application/lha"); _mimeTypes.Add(".lha", "application/octet-stream"); _mimeTypes.Add(".lha", "application/x-lha"); _mimeTypes.Add(".lhx", "application/octet-stream"); _mimeTypes.Add(".list", "text/plain"); _mimeTypes.Add(".lma", "audio/nspaudio"); _mimeTypes.Add(".lma", "audio/x-nspaudio"); _mimeTypes.Add(".log", "text/plain"); _mimeTypes.Add(".lsp", "application/x-lisp"); _mimeTypes.Add(".lsp", "text/x-script.lisp"); _mimeTypes.Add(".lst", "text/plain"); _mimeTypes.Add(".lsx", "text/x-la-asf"); _mimeTypes.Add(".ltx", "application/x-latex"); _mimeTypes.Add(".lzh", "application/octet-stream"); _mimeTypes.Add(".lzh", "application/x-lzh"); _mimeTypes.Add(".lzx", "application/lzx"); _mimeTypes.Add(".lzx", "application/octet-stream"); _mimeTypes.Add(".lzx", "application/x-lzx"); _mimeTypes.Add(".m", "text/plain"); _mimeTypes.Add(".m", "text/x-m"); _mimeTypes.Add(".m1v", "video/mpeg"); _mimeTypes.Add(".m2a", "audio/mpeg"); _mimeTypes.Add(".m2v", "video/mpeg"); _mimeTypes.Add(".m3u", "audio/x-mpequrl"); _mimeTypes.Add(".man", "application/x-troff-man"); _mimeTypes.Add(".map", "application/x-navimap"); _mimeTypes.Add(".mar", "text/plain"); _mimeTypes.Add(".mbd", "application/mbedlet"); _mimeTypes.Add(".mc$", "application/x-magic-cap-package-1.0"); _mimeTypes.Add(".mcd", "application/mcad"); _mimeTypes.Add(".mcd", "application/x-mathcad"); _mimeTypes.Add(".mcf", "image/vasa"); _mimeTypes.Add(".mcf", "text/mcf"); _mimeTypes.Add(".mcp", "application/netmc"); _mimeTypes.Add(".me", "application/x-troff-me"); _mimeTypes.Add(".mht", "message/rfc822"); _mimeTypes.Add(".mhtml", "message/rfc822"); _mimeTypes.Add(".mid", "application/x-midi"); _mimeTypes.Add(".mid", "audio/midi"); _mimeTypes.Add(".mid", "audio/x-mid"); _mimeTypes.Add(".mid", "audio/x-midi"); _mimeTypes.Add(".mid", "music/crescendo"); _mimeTypes.Add(".mid", "x-music/x-midi"); _mimeTypes.Add(".midi", "application/x-midi"); _mimeTypes.Add(".midi", "audio/midi"); _mimeTypes.Add(".midi", "audio/x-mid"); _mimeTypes.Add(".midi", "audio/x-midi"); _mimeTypes.Add(".midi", "music/crescendo"); _mimeTypes.Add(".midi", "x-music/x-midi"); _mimeTypes.Add(".mif", "application/x-frame"); _mimeTypes.Add(".mif", "application/x-mif"); _mimeTypes.Add(".mime", "message/rfc822"); _mimeTypes.Add(".mime", "www/mime"); _mimeTypes.Add(".mjf", "audio/x-vnd.audioexplosion.mjuicemediafile"); _mimeTypes.Add(".mjpg", "video/x-motion-jpeg"); _mimeTypes.Add(".mm", "application/base64"); _mimeTypes.Add(".mm", "application/x-meme"); _mimeTypes.Add(".mme", "application/base64"); _mimeTypes.Add(".mod", "audio/mod"); _mimeTypes.Add(".mod", "audio/x-mod"); _mimeTypes.Add(".moov", "video/quicktime"); _mimeTypes.Add(".mov", "video/quicktime"); _mimeTypes.Add(".movie", "video/x-sgi-movie"); _mimeTypes.Add(".mp2", "audio/mpeg"); _mimeTypes.Add(".mp2", "audio/x-mpeg"); _mimeTypes.Add(".mp2", "video/mpeg"); _mimeTypes.Add(".mp2", "video/x-mpeg"); _mimeTypes.Add(".mp2", "video/x-mpeq2a"); _mimeTypes.Add(".mp3", "audio/mpeg3"); _mimeTypes.Add(".mp3", "audio/x-mpeg-3"); _mimeTypes.Add(".mp3", "video/mpeg"); _mimeTypes.Add(".mp3", "video/x-mpeg"); _mimeTypes.Add(".mpa", "audio/mpeg"); _mimeTypes.Add(".mpa", "video/mpeg"); _mimeTypes.Add(".mpc", "application/x-project"); _mimeTypes.Add(".mpe", "video/mpeg"); _mimeTypes.Add(".mpeg", "video/mpeg"); _mimeTypes.Add(".mpg", "audio/mpeg"); _mimeTypes.Add(".mpg", "video/mpeg"); _mimeTypes.Add(".mpga", "audio/mpeg"); _mimeTypes.Add(".mpp", "application/vnd.ms-project"); _mimeTypes.Add(".mpt", "application/x-project"); _mimeTypes.Add(".mpv", "application/x-project"); _mimeTypes.Add(".mpx", "application/x-project"); _mimeTypes.Add(".mrc", "application/marc"); _mimeTypes.Add(".ms", "application/x-troff-ms"); _mimeTypes.Add(".mv", "video/x-sgi-movie"); _mimeTypes.Add(".my", "audio/make"); _mimeTypes.Add(".mzz", "application/x-vnd.audioexplosion.mzz"); _mimeTypes.Add(".nap", "image/naplps"); _mimeTypes.Add(".naplps", "image/naplps"); _mimeTypes.Add(".nc", "application/x-netcdf"); _mimeTypes.Add(".ncm", "application/vnd.nokia.configuration-message"); _mimeTypes.Add(".nif", "image/x-niff"); _mimeTypes.Add(".niff", "image/x-niff"); _mimeTypes.Add(".nix", "application/x-mix-transfer"); _mimeTypes.Add(".nsc", "application/x-conference"); _mimeTypes.Add(".nvd", "application/x-navidoc"); _mimeTypes.Add(".o", "application/octet-stream"); _mimeTypes.Add(".oda", "application/oda"); _mimeTypes.Add(".omc", "application/x-omc"); _mimeTypes.Add(".omcd", "application/x-omcdatamaker"); _mimeTypes.Add(".omcr", "application/x-omcregerator"); _mimeTypes.Add(".p", "text/x-pascal"); _mimeTypes.Add(".p10", "application/pkcs10"); _mimeTypes.Add(".p10", "application/x-pkcs10"); _mimeTypes.Add(".p12", "application/pkcs-12"); _mimeTypes.Add(".p12", "application/x-pkcs12"); _mimeTypes.Add(".p7a", "application/x-pkcs7-signature"); _mimeTypes.Add(".p7c", "application/pkcs7-mime"); _mimeTypes.Add(".p7c", "application/x-pkcs7-mime"); _mimeTypes.Add(".p7m", "application/pkcs7-mime"); _mimeTypes.Add(".p7m", "application/x-pkcs7-mime"); _mimeTypes.Add(".p7r", "application/x-pkcs7-certreqresp"); _mimeTypes.Add(".p7s", "application/pkcs7-signature"); _mimeTypes.Add(".part", "application/pro_eng"); _mimeTypes.Add(".pas", "text/pascal"); _mimeTypes.Add(".pbm", "image/x-portable-bitmap"); _mimeTypes.Add(".pcl", "application/vnd.hp-pcl"); _mimeTypes.Add(".pcl", "application/x-pcl"); _mimeTypes.Add(".pct", "image/x-pict"); _mimeTypes.Add(".pcx", "image/x-pcx"); _mimeTypes.Add(".pdb", "chemical/x-pdb"); _mimeTypes.Add(".pdf", "application/pdf"); _mimeTypes.Add(".pfunk", "audio/make"); _mimeTypes.Add(".pfunk", "audio/make.my.funk"); _mimeTypes.Add(".pgm", "image/x-portable-graymap"); _mimeTypes.Add(".pgm", "image/x-portable-greymap"); _mimeTypes.Add(".pic", "image/pict"); _mimeTypes.Add(".pict", "image/pict"); _mimeTypes.Add(".pkg", "application/x-newton-compatible-pkg"); _mimeTypes.Add(".pko", "application/vnd.ms-pki.pko"); _mimeTypes.Add(".pl", "text/plain"); _mimeTypes.Add(".pl", "text/x-script.perl"); _mimeTypes.Add(".plx", "application/x-pixclscript"); _mimeTypes.Add(".pm", "image/x-xpixmap"); _mimeTypes.Add(".pm", "text/x-script.perl-module"); _mimeTypes.Add(".pm4", "application/x-pagemaker"); _mimeTypes.Add(".pm5", "application/x-pagemaker"); _mimeTypes.Add(".png", "image/png"); _mimeTypes.Add(".pnm", "application/x-portable-anymap"); _mimeTypes.Add(".pnm", "image/x-portable-anymap"); _mimeTypes.Add(".pot", "application/mspowerpoint"); _mimeTypes.Add(".pot", "application/vnd.ms-powerpoint"); _mimeTypes.Add(".pov", "model/x-pov"); _mimeTypes.Add(".ppa", "application/vnd.ms-powerpoint"); _mimeTypes.Add(".ppm", "image/x-portable-pixmap"); _mimeTypes.Add(".pps", "application/mspowerpoint"); _mimeTypes.Add(".pps", "application/vnd.ms-powerpoint"); _mimeTypes.Add(".ppt", "application/mspowerpoint"); _mimeTypes.Add(".ppt", "application/powerpoint"); _mimeTypes.Add(".ppt", "application/vnd.ms-powerpoint"); _mimeTypes.Add(".ppt", "application/x-mspowerpoint"); _mimeTypes.Add(".ppz", "application/mspowerpoint"); _mimeTypes.Add(".pre", "application/x-freelance"); _mimeTypes.Add(".prt", "application/pro_eng"); _mimeTypes.Add(".ps", "application/postscript"); _mimeTypes.Add(".psd", "application/octet-stream"); _mimeTypes.Add(".pvu", "paleovu/x-pv"); _mimeTypes.Add(".pwz", "application/vnd.ms-powerpoint"); _mimeTypes.Add(".py", "text/x-script.phyton"); _mimeTypes.Add(".pyc", "applicaiton/x-bytecode.python"); _mimeTypes.Add(".qcp", "audio/vnd.qcelp"); _mimeTypes.Add(".qd3", "x-world/x-3dmf"); _mimeTypes.Add(".qd3d", "x-world/x-3dmf"); _mimeTypes.Add(".qif", "image/x-quicktime"); _mimeTypes.Add(".qt", "video/quicktime"); _mimeTypes.Add(".qtc", "video/x-qtc"); _mimeTypes.Add(".qti", "image/x-quicktime"); _mimeTypes.Add(".qtif", "image/x-quicktime"); _mimeTypes.Add(".ra", "audio/x-pn-realaudio"); _mimeTypes.Add(".ra", "audio/x-pn-realaudio-plugin"); _mimeTypes.Add(".ra", "audio/x-realaudio"); _mimeTypes.Add(".ram", "audio/x-pn-realaudio"); _mimeTypes.Add(".ras", "application/x-cmu-raster"); _mimeTypes.Add(".ras", "image/cmu-raster"); _mimeTypes.Add(".ras", "image/x-cmu-raster"); _mimeTypes.Add(".rast", "image/cmu-raster"); _mimeTypes.Add(".rexx", "text/x-script.rexx"); _mimeTypes.Add(".rf", "image/vnd.rn-realflash"); _mimeTypes.Add(".rgb", "image/x-rgb"); _mimeTypes.Add(".rm", "application/vnd.rn-realmedia"); _mimeTypes.Add(".rm", "audio/x-pn-realaudio"); _mimeTypes.Add(".rmi", "audio/mid"); _mimeTypes.Add(".rmm", "audio/x-pn-realaudio"); _mimeTypes.Add(".rmp", "audio/x-pn-realaudio"); _mimeTypes.Add(".rmp", "audio/x-pn-realaudio-plugin"); _mimeTypes.Add(".rng", "application/ringing-tones"); _mimeTypes.Add(".rng", "application/vnd.nokia.ringing-tone"); _mimeTypes.Add(".rnx", "application/vnd.rn-realplayer"); _mimeTypes.Add(".roff", "application/x-troff"); _mimeTypes.Add(".rp", "image/vnd.rn-realpix"); _mimeTypes.Add(".rpm", "audio/x-pn-realaudio-plugin"); _mimeTypes.Add(".rt", "text/richtext"); _mimeTypes.Add(".rt", "text/vnd.rn-realtext"); _mimeTypes.Add(".rtf", "application/rtf"); _mimeTypes.Add(".rtf", "application/x-rtf"); _mimeTypes.Add(".rtf", "text/richtext"); _mimeTypes.Add(".rtx", "application/rtf"); _mimeTypes.Add(".rtx", "text/richtext"); _mimeTypes.Add(".rv", "video/vnd.rn-realvideo"); _mimeTypes.Add(".s", "text/x-asm"); _mimeTypes.Add(".s3m", "audio/s3m"); _mimeTypes.Add(".saveme", "application/octet-stream"); _mimeTypes.Add(".sbk", "application/x-tbook"); _mimeTypes.Add(".scm", "application/x-lotusscreencam"); _mimeTypes.Add(".scm", "text/x-script.guile"); _mimeTypes.Add(".scm", "text/x-script.scheme"); _mimeTypes.Add(".scm", "video/x-scm"); _mimeTypes.Add(".sdml", "text/plain"); _mimeTypes.Add(".sdp", "application/sdp"); _mimeTypes.Add(".sdp", "application/x-sdp"); _mimeTypes.Add(".sdr", "application/sounder"); _mimeTypes.Add(".sea", "application/sea"); _mimeTypes.Add(".sea", "application/x-sea"); _mimeTypes.Add(".set", "application/set"); _mimeTypes.Add(".sgm", "text/sgml"); _mimeTypes.Add(".sgm", "text/x-sgml"); _mimeTypes.Add(".sgml", "text/sgml"); _mimeTypes.Add(".sgml", "text/x-sgml"); _mimeTypes.Add(".sh", "application/x-bsh"); _mimeTypes.Add(".sh", "application/x-sh"); _mimeTypes.Add(".sh", "application/x-shar"); _mimeTypes.Add(".sh", "text/x-script.sh"); _mimeTypes.Add(".shar", "application/x-bsh"); _mimeTypes.Add(".shar", "application/x-shar"); _mimeTypes.Add(".shtml", "text/html"); _mimeTypes.Add(".shtml", "text/x-server-parsed-html"); _mimeTypes.Add(".sid", "audio/x-psid"); _mimeTypes.Add(".sit", "application/x-sit"); _mimeTypes.Add(".sit", "application/x-stuffit"); _mimeTypes.Add(".skd", "application/x-koan"); _mimeTypes.Add(".skm", "application/x-koan"); _mimeTypes.Add(".skp", "application/x-koan"); _mimeTypes.Add(".skt", "application/x-koan"); _mimeTypes.Add(".sl", "application/x-seelogo"); _mimeTypes.Add(".smi", "application/smil"); _mimeTypes.Add(".smil", "application/smil"); _mimeTypes.Add(".snd", "audio/basic"); _mimeTypes.Add(".snd", "audio/x-adpcm"); _mimeTypes.Add(".sol", "application/solids"); _mimeTypes.Add(".spc", "application/x-pkcs7-certificates"); _mimeTypes.Add(".spc", "text/x-speech"); _mimeTypes.Add(".spl", "application/futuresplash"); _mimeTypes.Add(".spr", "application/x-sprite"); _mimeTypes.Add(".sprite", "application/x-sprite"); _mimeTypes.Add(".src", "application/x-wais-source"); _mimeTypes.Add(".ssi", "text/x-server-parsed-html"); _mimeTypes.Add(".ssm", "application/streamingmedia"); _mimeTypes.Add(".sst", "application/vnd.ms-pki.certstore"); _mimeTypes.Add(".step", "application/step"); _mimeTypes.Add(".stl", "application/sla"); _mimeTypes.Add(".stl", "application/vnd.ms-pki.stl"); _mimeTypes.Add(".stl", "application/x-navistyle"); _mimeTypes.Add(".stp", "application/step"); _mimeTypes.Add(".sv4cpio", "application/x-sv4cpio"); _mimeTypes.Add(".sv4crc", "application/x-sv4crc"); _mimeTypes.Add(".svf", "image/vnd.dwg"); _mimeTypes.Add(".svf", "image/x-dwg"); _mimeTypes.Add(".svr", "application/x-world"); _mimeTypes.Add(".svr", "x-world/x-svr"); _mimeTypes.Add(".swf", "application/x-shockwave-flash"); _mimeTypes.Add(".t", "application/x-troff"); _mimeTypes.Add(".talk", "text/x-speech"); _mimeTypes.Add(".tar", "application/x-tar"); _mimeTypes.Add(".tbk", "application/toolbook"); _mimeTypes.Add(".tbk", "application/x-tbook"); _mimeTypes.Add(".tcl", "application/x-tcl"); _mimeTypes.Add(".tcl", "text/x-script.tcl"); _mimeTypes.Add(".tcsh", "text/x-script.tcsh"); _mimeTypes.Add(".tex", "application/x-tex"); _mimeTypes.Add(".texi", "application/x-texinfo"); _mimeTypes.Add(".texinfo", "application/x-texinfo"); _mimeTypes.Add(".text", "application/plain"); _mimeTypes.Add(".text", "text/plain"); _mimeTypes.Add(".tgz", "application/gnutar"); _mimeTypes.Add(".tgz", "application/x-compressed"); _mimeTypes.Add(".tif", "image/tiff"); _mimeTypes.Add(".tif", "image/x-tiff"); _mimeTypes.Add(".tiff", "image/tiff"); _mimeTypes.Add(".tiff", "image/x-tiff"); _mimeTypes.Add(".tr", "application/x-troff"); _mimeTypes.Add(".tsi", "audio/tsp-audio"); _mimeTypes.Add(".tsp", "application/dsptype"); _mimeTypes.Add(".tsp", "audio/tsplayer"); _mimeTypes.Add(".tsv", "text/tab-separated-values"); _mimeTypes.Add(".turbot", "image/florian"); _mimeTypes.Add(".txt", "text/plain"); _mimeTypes.Add(".uil", "text/x-uil"); _mimeTypes.Add(".uni", "text/uri-list"); _mimeTypes.Add(".unis", "text/uri-list"); _mimeTypes.Add(".unv", "application/i-deas"); _mimeTypes.Add(".uri", "text/uri-list"); _mimeTypes.Add(".uris", "text/uri-list"); _mimeTypes.Add(".ustar", "application/x-ustar"); _mimeTypes.Add(".ustar", "multipart/x-ustar"); _mimeTypes.Add(".uu", "application/octet-stream"); _mimeTypes.Add(".uu", "text/x-uuencode"); _mimeTypes.Add(".uue", "text/x-uuencode"); _mimeTypes.Add(".vcd", "application/x-cdlink"); _mimeTypes.Add(".vcs", "text/x-vcalendar"); _mimeTypes.Add(".vda", "application/vda"); _mimeTypes.Add(".vdo", "video/vdo"); _mimeTypes.Add(".vew", "application/groupwise"); _mimeTypes.Add(".viv", "video/vivo"); _mimeTypes.Add(".viv", "video/vnd.vivo"); _mimeTypes.Add(".vivo", "video/vivo"); _mimeTypes.Add(".vivo", "video/vnd.vivo"); _mimeTypes.Add(".vmd", "application/vocaltec-media-desc"); _mimeTypes.Add(".vmf", "application/vocaltec-media-file"); _mimeTypes.Add(".voc", "audio/voc"); _mimeTypes.Add(".voc", "audio/x-voc"); _mimeTypes.Add(".vos", "video/vosaic"); _mimeTypes.Add(".vox", "audio/voxware"); _mimeTypes.Add(".vqe", "audio/x-twinvq-plugin"); _mimeTypes.Add(".vqf", "audio/x-twinvq"); _mimeTypes.Add(".vql", "audio/x-twinvq-plugin"); _mimeTypes.Add(".vrml", "application/x-vrml"); _mimeTypes.Add(".vrml", "model/vrml"); _mimeTypes.Add(".vrml", "x-world/x-vrml"); _mimeTypes.Add(".vrt", "x-world/x-vrt"); _mimeTypes.Add(".vsd", "application/x-visio"); _mimeTypes.Add(".vst", "application/x-visio"); _mimeTypes.Add(".vsw", "application/x-visio"); _mimeTypes.Add(".w60", "application/wordperfect6.0"); _mimeTypes.Add(".w61", "application/wordperfect6.1"); _mimeTypes.Add(".w6w", "application/msword"); _mimeTypes.Add(".wav", "audio/wav"); _mimeTypes.Add(".wav", "audio/x-wav"); _mimeTypes.Add(".wb1", "application/x-qpro"); _mimeTypes.Add(".wbmp", "image/vnd.wap.wbmp"); _mimeTypes.Add(".web", "application/vnd.xara"); _mimeTypes.Add(".wiz", "application/msword"); _mimeTypes.Add(".wk1", "application/x-123"); _mimeTypes.Add(".wmf", "windows/metafile"); _mimeTypes.Add(".wml", "text/vnd.wap.wml"); _mimeTypes.Add(".wmlc", "application/vnd.wap.wmlc"); _mimeTypes.Add(".wmls", "text/vnd.wap.wmlscript"); _mimeTypes.Add(".wmlsc", "application/vnd.wap.wmlscriptc"); _mimeTypes.Add(".word", "application/msword"); _mimeTypes.Add(".wp", "application/wordperfect"); _mimeTypes.Add(".wp5", "application/wordperfect"); _mimeTypes.Add(".wp5", "application/wordperfect6.0"); _mimeTypes.Add(".wp6", "application/wordperfect"); _mimeTypes.Add(".wpd", "application/wordperfect"); _mimeTypes.Add(".wpd", "application/x-wpwin"); _mimeTypes.Add(".wq1", "application/x-lotus"); _mimeTypes.Add(".wri", "application/mswrite"); _mimeTypes.Add(".wri", "application/x-wri"); _mimeTypes.Add(".wrl", "application/x-world"); _mimeTypes.Add(".wrl", "model/vrml"); _mimeTypes.Add(".wrl", "x-world/x-vrml"); _mimeTypes.Add(".wrz", "model/vrml"); _mimeTypes.Add(".wrz", "x-world/x-vrml"); _mimeTypes.Add(".wsc", "text/scriplet"); _mimeTypes.Add(".wsrc", "application/x-wais-source"); _mimeTypes.Add(".wtk", "application/x-wintalk"); _mimeTypes.Add(".xbm", "image/x-xbitmap"); _mimeTypes.Add(".xbm", "image/x-xbm"); _mimeTypes.Add(".xbm", "image/xbm"); _mimeTypes.Add(".xdr", "video/x-amt-demorun"); _mimeTypes.Add(".xgz", "xgl/drawing"); _mimeTypes.Add(".xif", "image/vnd.xiff"); _mimeTypes.Add(".xl", "application/excel"); _mimeTypes.Add(".xla", "application/excel"); _mimeTypes.Add(".xla", "application/x-excel"); _mimeTypes.Add(".xla", "application/x-msexcel"); _mimeTypes.Add(".xlb", "application/excel"); _mimeTypes.Add(".xlb", "application/vnd.ms-excel"); _mimeTypes.Add(".xlb", "application/x-excel"); _mimeTypes.Add(".xlc", "application/excel"); _mimeTypes.Add(".xlc", "application/vnd.ms-excel"); _mimeTypes.Add(".xlc", "application/x-excel"); _mimeTypes.Add(".xld", "application/excel"); _mimeTypes.Add(".xld", "application/x-excel"); _mimeTypes.Add(".xlk", "application/excel"); _mimeTypes.Add(".xlk", "application/x-excel"); _mimeTypes.Add(".xll", "application/excel"); _mimeTypes.Add(".xll", "application/vnd.ms-excel"); _mimeTypes.Add(".xll", "application/x-excel"); _mimeTypes.Add(".xlm", "application/excel"); _mimeTypes.Add(".xlm", "application/vnd.ms-excel"); _mimeTypes.Add(".xlm", "application/x-excel"); _mimeTypes.Add(".xls", "application/excel"); _mimeTypes.Add(".xls", "application/vnd.ms-excel"); _mimeTypes.Add(".xls", "application/x-excel"); _mimeTypes.Add(".xls", "application/x-msexcel"); _mimeTypes.Add(".xlt", "application/excel"); _mimeTypes.Add(".xlt", "application/x-excel"); _mimeTypes.Add(".xlv", "application/excel"); _mimeTypes.Add(".xlv", "application/x-excel"); _mimeTypes.Add(".xlw", "application/excel"); _mimeTypes.Add(".xlw", "application/vnd.ms-excel"); _mimeTypes.Add(".xlw", "application/x-excel"); _mimeTypes.Add(".xlw", "application/x-msexcel"); _mimeTypes.Add(".xm", "audio/xm"); _mimeTypes.Add(".xml", "application/xml"); _mimeTypes.Add(".xml", "text/xml"); _mimeTypes.Add(".xmz", "xgl/movie"); _mimeTypes.Add(".xpix", "application/x-vnd.ls-xpix"); _mimeTypes.Add(".xpm", "image/x-xpixmap"); _mimeTypes.Add(".xpm", "image/xpm"); _mimeTypes.Add(".x-png", "image/png"); _mimeTypes.Add(".xsr", "video/x-amt-showrun"); _mimeTypes.Add(".xwd", "image/x-xwd"); _mimeTypes.Add(".xwd", "image/x-xwindowdump"); _mimeTypes.Add(".xyz", "chemical/x-pdb"); _mimeTypes.Add(".z", "application/x-compress"); _mimeTypes.Add(".z", "application/x-compressed"); _mimeTypes.Add(".zip", "application/x-compressed"); _mimeTypes.Add(".zip", "application/x-zip-compressed"); _mimeTypes.Add(".zip", "application/zip"); _mimeTypes.Add(".zip", "multipart/x-zip"); _mimeTypes.Add(".zoo", "application/octet-stream"); _mimeTypes.Add(".zsh", "text/x-script.zsh"); //agentsmith spellcheck enable return _mimeTypes; } } #endregion #region Properties /// <summary> /// Gets or Sets a value indicating if document encoding must be automatically detected. /// </summary> public bool AutoDetectEncoding { get { return _autoDetectEncoding; } set { _autoDetectEncoding = value; } } /// <summary> /// Gets or Sets a value indicating whether to get document only from the cache. /// If this is set to true and document is not found in the cache, nothing will be loaded. /// </summary> public bool CacheOnly { get { return _cacheOnly; } set { if ((value) && !UsingCache) { throw new HtmlWebException("Cache is not enabled. Set UsingCache to true first."); } _cacheOnly = value; } } /// <summary> /// Gets or Sets the cache path. If null, no caching mechanism will be used. /// </summary> public string CachePath { get { return _cachePath; } set { _cachePath = value; } } /// <summary> /// Gets a value indicating if the last document was retrieved from the cache. /// </summary> public bool FromCache { get { return _fromCache; } } /// <summary> /// Gets the last request duration in milliseconds. /// </summary> public int RequestDuration { get { return _requestDuration; } } /// <summary> /// Gets the URI of the Internet resource that actually responded to the request. /// </summary> public Uri ResponseUri { get { return _responseUri; } } /// <summary> /// Gets the last request status. /// </summary> public HttpStatusCode StatusCode { get { return _statusCode; } } /// <summary> /// Gets or Sets the size of the buffer used for memory operations. /// </summary> public int StreamBufferSize { get { return _streamBufferSize; } set { if (_streamBufferSize <= 0) { throw new ArgumentException("Size must be greater than zero."); } _streamBufferSize = value; } } /// <summary> /// Gets or Sets a value indicating if cookies will be stored. /// </summary> public bool UseCookies { get { return _useCookies; } set { _useCookies = value; } } /// <summary> /// Gets or Sets the User Agent HTTP 1.1 header sent on any webrequest /// </summary> public string UserAgent { get { return _userAgent; } set { _userAgent = value; } } /// <summary> /// Gets or Sets a value indicating whether the caching mechanisms should be used or not. /// </summary> public bool UsingCache { get { return _cachePath != null && _usingCache; } set { if ((value) && (_cachePath == null)) { throw new HtmlWebException("You need to define a CachePath first."); } _usingCache = value; } } #endregion #region Public Methods #pragma warning disable 618 /// <summary> /// Gets the MIME content type for a given path extension. /// </summary> /// <param name="extension">The input path extension.</param> /// <param name="def">The default content type to return if any error occurs.</param> /// <returns>The path extension's MIME content type.</returns> public static string GetContentTypeForExtension(string extension, string def) { if (string.IsNullOrEmpty(extension)) { return def; } string contentType = ""; if (!SecurityManager.IsGranted(new RegistryPermission(PermissionState.Unrestricted))) { if (MimeTypes.ContainsKey(extension)) contentType = MimeTypes[extension]; else contentType = def; } if (!SecurityManager.IsGranted(new DnsPermission(PermissionState.Unrestricted))) { //do something.... not at full trust try { RegistryKey reg = Registry.ClassesRoot; reg = reg.OpenSubKey(extension, false); if (reg != null) contentType = (string)reg.GetValue("", def); } catch (Exception) { contentType = def; } } return contentType; } /// <summary> /// Gets the path extension for a given MIME content type. /// </summary> /// <param name="contentType">The input MIME content type.</param> /// <param name="def">The default path extension to return if any error occurs.</param> /// <returns>The MIME content type's path extension.</returns> public static string GetExtensionForContentType(string contentType, string def) { if (string.IsNullOrEmpty(contentType)) { return def; } string ext = ""; if (!SecurityManager.IsGranted(new RegistryPermission(PermissionState.Unrestricted))) { if (MimeTypes.ContainsValue(contentType)) { foreach (KeyValuePair<string, string> pair in MimeTypes) if (pair.Value == contentType) return pair.Value; } return def; } if (SecurityManager.IsGranted(new RegistryPermission(PermissionState.Unrestricted))) { try { RegistryKey reg = Registry.ClassesRoot; reg = reg.OpenSubKey(@"MIME\Database\Content Type\" + contentType, false); if (reg != null) ext = (string)reg.GetValue("Extension", def); } catch (Exception) { ext = def; } } return ext; } #pragma warning restore 618 /// <summary> /// Creates an instance of the given type from the specified Internet resource. /// </summary> /// <param name="url">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param> /// <param name="type">The requested type.</param> /// <returns>An newly created instance.</returns> public object CreateInstance(string url, Type type) { return CreateInstance(url, null, null, type); } /// <summary> /// Creates an instance of the given type from the specified Internet resource. /// </summary> /// <param name="htmlUrl">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param> /// <param name="xsltUrl">The URL that specifies the XSLT stylesheet to load.</param> /// <param name="xsltArgs">An <see cref="XsltArgumentList"/> containing the namespace-qualified arguments used as input to the transform.</param> /// <param name="type">The requested type.</param> /// <returns>An newly created instance.</returns> public object CreateInstance(string htmlUrl, string xsltUrl, XsltArgumentList xsltArgs, Type type) { return CreateInstance(htmlUrl, xsltUrl, xsltArgs, type, null); } /// <summary> /// Creates an instance of the given type from the specified Internet resource. /// </summary> /// <param name="htmlUrl">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param> /// <param name="xsltUrl">The URL that specifies the XSLT stylesheet to load.</param> /// <param name="xsltArgs">An <see cref="XsltArgumentList"/> containing the namespace-qualified arguments used as input to the transform.</param> /// <param name="type">The requested type.</param> /// <param name="xmlPath">A file path where the temporary XML before transformation will be saved. Mostly used for debugging purposes.</param> /// <returns>An newly created instance.</returns> public object CreateInstance(string htmlUrl, string xsltUrl, XsltArgumentList xsltArgs, Type type, string xmlPath) { StringWriter sw = new StringWriter(); XmlTextWriter writer = new XmlTextWriter(sw); if (xsltUrl == null) { LoadHtmlAsXml(htmlUrl, writer); } else { if (xmlPath == null) { LoadHtmlAsXml(htmlUrl, xsltUrl, xsltArgs, writer); } else { LoadHtmlAsXml(htmlUrl, xsltUrl, xsltArgs, writer, xmlPath); } } writer.Flush(); StringReader sr = new StringReader(sw.ToString()); XmlTextReader reader = new XmlTextReader(sr); XmlSerializer serializer = new XmlSerializer(type); object o; try { o = serializer.Deserialize(reader); } catch (InvalidOperationException ex) { throw new Exception(ex + ", --- xml:" + sw); } return o; } /// <summary> /// Gets an HTML document from an Internet resource and saves it to the specified file. /// </summary> /// <param name="url">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param> /// <param name="path">The location of the file where you want to save the document.</param> public void Get(string url, string path) { Get(url, path, "GET"); } /// <summary> /// Gets an HTML document from an Internet resource and saves it to the specified file. - Proxy aware /// </summary> /// <param name="url">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param> /// <param name="path">The location of the file where you want to save the document.</param> /// <param name="proxy"></param> /// <param name="credentials"></param> public void Get(string url, string path, WebProxy proxy, NetworkCredential credentials) { Get(url, path, proxy, credentials, "GET"); } /// <summary> /// Gets an HTML document from an Internet resource and saves it to the specified file. /// </summary> /// <param name="url">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param> /// <param name="path">The location of the file where you want to save the document.</param> /// <param name="method">The HTTP method used to open the connection, such as GET, POST, PUT, or PROPFIND.</param> public void Get(string url, string path, string method) { Uri uri = new Uri(url); if ((uri.Scheme == Uri.UriSchemeHttps) || (uri.Scheme == Uri.UriSchemeHttp)) { Get(uri, method, path, null, null, null); } else { throw new HtmlWebException("Unsupported uri scheme: '" + uri.Scheme + "'."); } } /// <summary> /// Gets an HTML document from an Internet resource and saves it to the specified file. Understands Proxies /// </summary> /// <param name="url">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param> /// <param name="path">The location of the file where you want to save the document.</param> /// <param name="credentials"></param> /// <param name="method">The HTTP method used to open the connection, such as GET, POST, PUT, or PROPFIND.</param> /// <param name="proxy"></param> public void Get(string url, string path, WebProxy proxy, NetworkCredential credentials, string method) { Uri uri = new Uri(url); if ((uri.Scheme == Uri.UriSchemeHttps) || (uri.Scheme == Uri.UriSchemeHttp)) { Get(uri, method, path, null, proxy, credentials); } else { throw new HtmlWebException("Unsupported uri scheme: '" + uri.Scheme + "'."); } } /// <summary> /// Gets the cache file path for a specified url. /// </summary> /// <param name="uri">The url fo which to retrieve the cache path. May not be null.</param> /// <returns>The cache file path.</returns> public string GetCachePath(Uri uri) { if (uri == null) { throw new ArgumentNullException("uri"); } if (!UsingCache) { throw new HtmlWebException("Cache is not enabled. Set UsingCache to true first."); } string cachePath; if (uri.AbsolutePath == "/") { cachePath = Path.Combine(_cachePath, ".htm"); } else { cachePath = Path.Combine(_cachePath, (uri.Host + uri.AbsolutePath).Replace('/', '\\')); } return cachePath; } /// <summary> /// Gets an HTML document from an Internet resource. /// </summary> /// <param name="url">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param> /// <returns>A new HTML document.</returns> public HtmlDocument Load(string url) { return Load(url, "GET"); } /// <summary> /// Gets an HTML document from an Internet resource. /// </summary> /// <param name="url">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param> /// <param name="proxyHost">Host to use for Proxy</param> /// <param name="proxyPort">Port the Proxy is on</param> /// <param name="userId">User Id for Authentication</param> /// <param name="password">Password for Authentication</param> /// <returns>A new HTML document.</returns> public HtmlDocument Load(string url, string proxyHost, int proxyPort, string userId, string password) { //Create my proxy WebProxy myProxy = new WebProxy(proxyHost, proxyPort); myProxy.BypassProxyOnLocal = true; //Create my credentials NetworkCredential myCreds = null; if ((userId != null) && (password != null)) { myCreds = new NetworkCredential(userId, password); CredentialCache credCache = new CredentialCache(); //Add the creds credCache.Add(myProxy.Address, "Basic", myCreds); credCache.Add(myProxy.Address, "Digest", myCreds); } return Load(url, "GET", myProxy, myCreds); } /// <summary> /// Loads an HTML document from an Internet resource. /// </summary> /// <param name="url">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param> /// <param name="method">The HTTP method used to open the connection, such as GET, POST, PUT, or PROPFIND.</param> /// <returns>A new HTML document.</returns> public HtmlDocument Load(string url, string method) { Uri uri = new Uri(url); HtmlDocument doc; if ((uri.Scheme == Uri.UriSchemeHttps) || (uri.Scheme == Uri.UriSchemeHttp)) { doc = LoadUrl(uri, method, null, null); } else { if (uri.Scheme == Uri.UriSchemeFile) { doc = new HtmlDocument(); doc.OptionAutoCloseOnEnd = false; doc.OptionAutoCloseOnEnd = true; doc.DetectEncodingAndLoad(url, _autoDetectEncoding); } else { throw new HtmlWebException("Unsupported uri scheme: '" + uri.Scheme + "'."); } } if (PreHandleDocument != null) { PreHandleDocument(doc); } return doc; } /// <summary> /// Loads an HTML document from an Internet resource. /// </summary> /// <param name="url">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param> /// <param name="method">The HTTP method used to open the connection, such as GET, POST, PUT, or PROPFIND.</param> /// <param name="proxy">Proxy to use with this request</param> /// <param name="credentials">Credentials to use when authenticating</param> /// <returns>A new HTML document.</returns> public HtmlDocument Load(string url, string method, WebProxy proxy, NetworkCredential credentials) { Uri uri = new Uri(url); HtmlDocument doc; if ((uri.Scheme == Uri.UriSchemeHttps) || (uri.Scheme == Uri.UriSchemeHttp)) { doc = LoadUrl(uri, method, proxy, credentials); } else { if (uri.Scheme == Uri.UriSchemeFile) { doc = new HtmlDocument(); doc.OptionAutoCloseOnEnd = false; doc.OptionAutoCloseOnEnd = true; doc.DetectEncodingAndLoad(url, _autoDetectEncoding); } else { throw new HtmlWebException("Unsupported uri scheme: '" + uri.Scheme + "'."); } } if (PreHandleDocument != null) { PreHandleDocument(doc); } return doc; } /// <summary> /// Loads an HTML document from an Internet resource and saves it to the specified XmlTextWriter. /// </summary> /// <param name="htmlUrl">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param> /// <param name="writer">The XmlTextWriter to which you want to save.</param> public void LoadHtmlAsXml(string htmlUrl, XmlTextWriter writer) { HtmlDocument doc = Load(htmlUrl); doc.Save(writer); } /// <summary> /// Loads an HTML document from an Internet resource and saves it to the specified XmlTextWriter, after an XSLT transformation. /// </summary> /// <param name="htmlUrl">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param> /// <param name="xsltUrl">The URL that specifies the XSLT stylesheet to load.</param> /// <param name="xsltArgs">An XsltArgumentList containing the namespace-qualified arguments used as input to the transform.</param> /// <param name="writer">The XmlTextWriter to which you want to save.</param> public void LoadHtmlAsXml(string htmlUrl, string xsltUrl, XsltArgumentList xsltArgs, XmlTextWriter writer) { LoadHtmlAsXml(htmlUrl, xsltUrl, xsltArgs, writer, null); } /// <summary> /// Loads an HTML document from an Internet resource and saves it to the specified XmlTextWriter, after an XSLT transformation. /// </summary> /// <param name="htmlUrl">The requested URL, such as "http://Myserver/Mypath/Myfile.asp". May not be null.</param> /// <param name="xsltUrl">The URL that specifies the XSLT stylesheet to load.</param> /// <param name="xsltArgs">An XsltArgumentList containing the namespace-qualified arguments used as input to the transform.</param> /// <param name="writer">The XmlTextWriter to which you want to save.</param> /// <param name="xmlPath">A file path where the temporary XML before transformation will be saved. Mostly used for debugging purposes.</param> public void LoadHtmlAsXml(string htmlUrl, string xsltUrl, XsltArgumentList xsltArgs, XmlTextWriter writer, string xmlPath) { if (htmlUrl == null) { throw new ArgumentNullException("htmlUrl"); } HtmlDocument doc = Load(htmlUrl); if (xmlPath != null) { XmlTextWriter w = new XmlTextWriter(xmlPath, doc.Encoding); doc.Save(w); w.Close(); } if (xsltArgs == null) { xsltArgs = new XsltArgumentList(); } // add some useful variables to the xslt doc xsltArgs.AddParam("url", "", htmlUrl); xsltArgs.AddParam("requestDuration", "", RequestDuration); xsltArgs.AddParam("fromCache", "", FromCache); XslCompiledTransform xslt = new XslCompiledTransform(); xslt.Load(xsltUrl); xslt.Transform(doc, xsltArgs, writer); } #endregion #region Private Methods private static void FilePreparePath(string target) { if (File.Exists(target)) { FileAttributes atts = File.GetAttributes(target); File.SetAttributes(target, atts & ~FileAttributes.ReadOnly); } else { string dir = Path.GetDirectoryName(target); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } } } private static DateTime RemoveMilliseconds(DateTime t) { return new DateTime(t.Year, t.Month, t.Day, t.Hour, t.Minute, t.Second, 0); } // ReSharper disable UnusedMethodReturnValue.Local private static long SaveStream(Stream stream, string path, DateTime touchDate, int streamBufferSize) // ReSharper restore UnusedMethodReturnValue.Local { FilePreparePath(path); FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write); BinaryReader br = null; BinaryWriter bw = null; long len = 0; try { br = new BinaryReader(stream); bw = new BinaryWriter(fs); byte[] buffer; do { buffer = br.ReadBytes(streamBufferSize); len += buffer.Length; if (buffer.Length > 0) { bw.Write(buffer); } } while (buffer.Length > 0); } finally { if (br != null) { br.Close(); } if (bw != null) { bw.Flush(); bw.Close(); } if (fs != null) { fs.Close(); } } File.SetLastWriteTime(path, touchDate); return len; } private HttpStatusCode Get(Uri uri, string method, string path, HtmlDocument doc, IWebProxy proxy, ICredentials creds) { string cachePath = null; HttpWebRequest req; bool oldFile = false; req = WebRequest.Create(uri) as HttpWebRequest; req.Method = method; req.UserAgent = UserAgent; if (proxy != null) { if (creds != null) { proxy.Credentials = creds; req.Credentials = creds; } else { proxy.Credentials = CredentialCache.DefaultCredentials; req.Credentials = CredentialCache.DefaultCredentials; } req.Proxy = proxy; } _fromCache = false; _requestDuration = 0; int tc = Environment.TickCount; if (UsingCache) { cachePath = GetCachePath(req.RequestUri); if (File.Exists(cachePath)) { req.IfModifiedSince = File.GetLastAccessTime(cachePath); oldFile = true; } } if (_cacheOnly) { if (!File.Exists(cachePath)) { throw new HtmlWebException("File was not found at cache path: '" + cachePath + "'"); } if (path != null) { IOLibrary.CopyAlways(cachePath, path); // touch the file if (cachePath != null) File.SetLastWriteTime(path, File.GetLastWriteTime(cachePath)); } _fromCache = true; return HttpStatusCode.NotModified; } if (_useCookies) { req.CookieContainer = new CookieContainer(); } if (PreRequest != null) { // allow our user to change the request at will if (!PreRequest(req)) { return HttpStatusCode.ResetContent; } // dump cookie // if (_useCookies) // { // foreach(Cookie cookie in req.CookieContainer.GetCookies(req.RequestUri)) // { // HtmlLibrary.Trace("Cookie " + cookie.Name + "=" + cookie.Value + " path=" + cookie.Path + " domain=" + cookie.Domain); // } // } } HttpWebResponse resp; try { resp = req.GetResponse() as HttpWebResponse; } catch (WebException we) { _requestDuration = Environment.TickCount - tc; resp = (HttpWebResponse)we.Response; if (resp == null) { if (oldFile) { if (path != null) { IOLibrary.CopyAlways(cachePath, path); // touch the file File.SetLastWriteTime(path, File.GetLastWriteTime(cachePath)); } return HttpStatusCode.NotModified; } throw; } } catch (Exception) { _requestDuration = Environment.TickCount - tc; throw; } // allow our user to get some info from the response if (PostResponse != null) { PostResponse(req, resp); } _requestDuration = Environment.TickCount - tc; _responseUri = resp.ResponseUri; bool html = IsHtmlContent(resp.ContentType); Encoding respenc = !string.IsNullOrEmpty(resp.ContentEncoding) ? Encoding.GetEncoding(resp.ContentEncoding) : null; if (resp.StatusCode == HttpStatusCode.NotModified) { if (UsingCache) { _fromCache = true; if (path != null) { IOLibrary.CopyAlways(cachePath, path); // touch the file File.SetLastWriteTime(path, File.GetLastWriteTime(cachePath)); } return resp.StatusCode; } // this should *never* happen... throw new HtmlWebException("Server has send a NotModifed code, without cache enabled."); } Stream s = resp.GetResponseStream(); if (s != null) { if (UsingCache) { // NOTE: LastModified does not contain milliseconds, so we remove them to the file SaveStream(s, cachePath, RemoveMilliseconds(resp.LastModified), _streamBufferSize); // save headers SaveCacheHeaders(req.RequestUri, resp); if (path != null) { // copy and touch the file IOLibrary.CopyAlways(cachePath, path); File.SetLastWriteTime(path, File.GetLastWriteTime(cachePath)); } } else { // try to work in-memory if ((doc != null) && (html)) { if (respenc != null) { doc.Load(s, respenc); } else { doc.Load(s, true); } } } resp.Close(); } return resp.StatusCode; } private string GetCacheHeader(Uri requestUri, string name, string def) { // note: some headers are collection (ex: www-authenticate) // we don't handle that here XmlDocument doc = new XmlDocument(); doc.Load(GetCacheHeadersPath(requestUri)); XmlNode node = doc.SelectSingleNode("//h[translate(@n, 'abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ')='" + name.ToUpper() + "']"); if (node == null) { return def; } // attribute should exist return node.Attributes[name].Value; } private string GetCacheHeadersPath(Uri uri) { //return Path.Combine(GetCachePath(uri), ".h.xml"); return GetCachePath(uri) + ".h.xml"; } private bool IsCacheHtmlContent(string path) { string ct = GetContentTypeForExtension(Path.GetExtension(path), null); return IsHtmlContent(ct); } private bool IsHtmlContent(string contentType) { return contentType.ToLower().StartsWith("text/html"); } private HtmlDocument LoadUrl(Uri uri, string method, WebProxy proxy, NetworkCredential creds) { HtmlDocument doc = new HtmlDocument(); doc.OptionAutoCloseOnEnd = false; doc.OptionFixNestedTags = true; _statusCode = Get(uri, method, null, doc, proxy, creds); if (_statusCode == HttpStatusCode.NotModified) { // read cached encoding doc.DetectEncodingAndLoad(GetCachePath(uri)); } return doc; } private void SaveCacheHeaders(Uri requestUri, HttpWebResponse resp) { // we cache the original headers aside the cached document. string file = GetCacheHeadersPath(requestUri); XmlDocument doc = new XmlDocument(); doc.LoadXml("<c></c>"); XmlNode cache = doc.FirstChild; foreach (string header in resp.Headers) { XmlNode entry = doc.CreateElement("h"); XmlAttribute att = doc.CreateAttribute("n"); att.Value = header; entry.Attributes.Append(att); att = doc.CreateAttribute("v"); att.Value = resp.Headers[header]; entry.Attributes.Append(att); cache.AppendChild(entry); } doc.Save(file); } #endregion } }
using System; using System.Collections.Generic; using System.Reflection; using UnityEditor; using UnityEngine; namespace SaveDuringPlay { /// <summary>A collection of tools for finding objects</summary> public static class ObjectTreeUtil { /// <summary> /// Get the full name of an object, travelling up the transform parents to the root. /// </summary> public static string GetFullName(GameObject current) { if (current == null) return ""; if (current.transform.parent == null) return "/" + current.name; return GetFullName(current.transform.parent.gameObject) + "/" + current.name; } /// <summary> /// Will find the named object, active or inactive, from the full path. /// </summary> public static GameObject FindObjectFromFullName(string fullName) { if (fullName == null || fullName.Length == 0) return null; string[] path = fullName.Split('/'); if (path.Length < 2) // skip leading '/' return null; GameObject[] roots = UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects(); if (roots == null) return null; Transform root = null; for (int i = 0; root == null && i < roots.Length; ++i) if (roots[i].name == path[1]) root = roots[i].transform; if (root == null) return null; for (int i = 2; i < path.Length; ++i) // skip root { bool found = false; foreach (Transform child in root) { if (child.name == path[i]) { found = true; root = child; break; } } if (!found) return null; } return root.gameObject; } /// <summary> /// This finds all the behaviours in scene, active or inactive, excluding prefabs /// </summary> public static T[] FindAllBehavioursInScene<T>() where T : MonoBehaviour { List<T> objectsInScene = new List<T>(); foreach (T b in Resources.FindObjectsOfTypeAll<T>()) { GameObject go = b.gameObject; if (go.hideFlags == HideFlags.NotEditable || go.hideFlags == HideFlags.HideAndDontSave) continue; if (EditorUtility.IsPersistent(go.transform.root.gameObject)) continue; objectsInScene.Add(b); } return objectsInScene.ToArray(); } } class GameObjectFieldScanner { /// <summary> /// Called for each leaf field. Return value should be true if action was taken. /// It will be propagated back to the caller. /// </summary> public OnLeafFieldDelegate OnLeafField; public delegate bool OnLeafFieldDelegate(string fullName, Type type, ref object value); /// <summary> /// Called for each field node, if and only if OnLeafField() for it or one /// of its leaves returned true. /// </summary> public OnFieldValueChangedDelegate OnFieldValueChanged; public delegate bool OnFieldValueChangedDelegate( string fullName, FieldInfo fieldInfo, object fieldOwner, object value); /// <summary> /// Called for each field, to test whether to proceed with scanning it. Return true to scan. /// </summary> public FilterFieldDelegate FilterField; public delegate bool FilterFieldDelegate(string fullName, FieldInfo fieldInfo); /// <summary> /// Which fields will be scanned /// </summary> public BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance; bool ScanFields(string fullName, Type type, ref object obj) { bool doneSomething = false; // Check if it's a complex type bool isLeaf = true; if (obj != null && !type.IsSubclassOf(typeof(Component)) && !type.IsSubclassOf(typeof(GameObject))) { // Is it an array? if (type.IsArray) { isLeaf = false; Array array = obj as Array; object arrayLength = array.Length; if (OnLeafField != null && OnLeafField( fullName + ".Length", arrayLength.GetType(), ref arrayLength)) { Array newArray = Array.CreateInstance( array.GetType().GetElementType(), Convert.ToInt32(arrayLength)); Array.Copy(array, 0, newArray, 0, Math.Min(array.Length, newArray.Length)); array = newArray; doneSomething = true; } for (int i = 0; i < array.Length; ++i) { object element = array.GetValue(i); if (ScanFields(fullName + "[" + i + "]", array.GetType().GetElementType(), ref element)) { array.SetValue(element, i); doneSomething = true; } } if (doneSomething) obj = array; } else { // Check if it's a complex type FieldInfo[] fields = obj.GetType().GetFields(bindingFlags); if (fields.Length > 0) { isLeaf = false; for (int i = 0; i < fields.Length; ++i) { string name = fullName + "." + fields[i].Name; if (FilterField == null || FilterField(name, fields[i])) { object fieldValue = fields[i].GetValue(obj); if (ScanFields(name, fields[i].FieldType, ref fieldValue)) { doneSomething = true; if (OnFieldValueChanged != null) OnFieldValueChanged(name, fields[i], obj, fieldValue); } } } } } } // If it's a leaf field then call the leaf handler if (isLeaf && OnLeafField != null) if (OnLeafField(fullName, type, ref obj)) doneSomething = true; return doneSomething; } public bool ScanFields(string fullName, MonoBehaviour b) { bool doneSomething = false; FieldInfo[] fields = b.GetType().GetFields(bindingFlags); if (fields.Length > 0) { for (int i = 0; i < fields.Length; ++i) { string name = fullName + "." + fields[i].Name; if (FilterField == null || FilterField(name, fields[i])) { object fieldValue = fields[i].GetValue(b); if (ScanFields(name, fields[i].FieldType, ref fieldValue)) doneSomething = true; // If leaf action was taken, propagate it up to the parent node if (doneSomething && OnFieldValueChanged != null) OnFieldValueChanged(fullName, fields[i], b, fieldValue); } } } return doneSomething; } /// <summary> /// Recursively scan the MonoBehaviours of a GameObject and its children. /// For each leaf field found, call the OnFieldValue delegate. /// </summary> public bool ScanFields(GameObject go, string prefix = null) { bool doneSomething = false; if (prefix == null) prefix = ""; else if (prefix.Length > 0) prefix += "."; MonoBehaviour[] components = go.GetComponents<MonoBehaviour>(); for (int i = 0; i < components.Length; ++i) { MonoBehaviour c = components[i]; if (c != null && ScanFields(prefix + c.GetType().FullName + i, c)) doneSomething = true; } return doneSomething; } }; /// <summary> /// Using reflection, this class scans a GameObject (and optionally its children) /// and records all the field settings. This only works for "nice" field settings /// within MonoBehaviours. Changes to the behaviour stack made between saving /// and restoring will fool this class. /// </summary> class ObjectStateSaver { string mObjectFullPath; Dictionary<string, string> mValues = new Dictionary<string, string>(); /// <summary> /// Recursively collect all the field values in the MonoBehaviours /// owned by this object and its descendants. The values are stored /// in an internal dictionary. /// </summary> public void CollectFieldValues(GameObject go) { mObjectFullPath = ObjectTreeUtil.GetFullName(go); GameObjectFieldScanner scanner = new GameObjectFieldScanner(); scanner.FilterField = FilterField; scanner.OnLeafField = (string fullName, Type type, ref object value) => { // Save the value in the dictionary mValues[fullName] = StringFromLeafObject(value); //Debug.Log(mObjectFullPath + "." + fullName + " = " + mValues[fullName]); return false; }; scanner.ScanFields(go); } public GameObject FindSavedGameObject() { return GameObject.Find(mObjectFullPath); } public string ObjetFullPath { get { return mObjectFullPath; } } /// <summary> /// Recursively scan the MonoBehaviours of a GameObject and its children. /// For each field found, look up its value in the internal dictionary. /// If it's present and its value in the dictionary differs from the actual /// value in the game object, Set the GameObject's value using the value /// recorded in the dictionary. /// </summary> public bool PutFieldValues(GameObject go) { GameObjectFieldScanner scanner = new GameObjectFieldScanner(); scanner.FilterField = FilterField; scanner.OnLeafField = (string fullName, Type type, ref object value) => { // Lookup the value in the dictionary string savedValue; if (mValues.TryGetValue(fullName, out savedValue) && StringFromLeafObject(value) != savedValue) { //Debug.Log(mObjectFullPath + "." + fullName + " = " + mValues[fullName]); value = LeafObjectFromString(type, mValues[fullName].Trim()); return true; // changed } return false; }; scanner.OnFieldValueChanged = (fullName, fieldInfo, fieldOwner, value) => { fieldInfo.SetValue(fieldOwner, value); return true; }; return scanner.ScanFields(go); } /// Ignore fields marked with the [NoSaveDuringPlay] attribute bool FilterField(string fullName, FieldInfo fieldInfo) { var attrs = fieldInfo.GetCustomAttributes(false); foreach (var attr in attrs) if (attr.GetType().Name.Contains("NoSaveDuringPlay")) return false; return true; } /// <summary> /// Parse a string to generate an object. /// Only very limited primitive object types are supported. /// Enums, Vectors and most other structures are automatically supported, /// because the reflection system breaks them down into their primitive components. /// You can add more support here, as needed. /// </summary> static object LeafObjectFromString(Type type, string value) { if (type == typeof(Single)) return float.Parse(value); if (type == typeof(Double)) return double.Parse(value); if (type == typeof(Boolean)) return Boolean.Parse(value); if (type == typeof(string)) return value; if (type == typeof(Int32)) return Int32.Parse(value); if (type == typeof(UInt32)) return UInt32.Parse(value); if (type.IsSubclassOf(typeof(Component))) { // Try to find the named game object GameObject go = ObjectTreeUtil.FindObjectFromFullName(value); return (go != null) ? go.GetComponent(type) : null; } if (type.IsSubclassOf(typeof(GameObject))) { // Try to find the named game object return GameObject.Find(value); } return null; } static string StringFromLeafObject(object obj) { if (obj == null) return string.Empty; if (obj.GetType().IsSubclassOf(typeof(Component))) { Component c = (Component)obj; if (c == null) // Component overrides the == operator, so we have to check return string.Empty; return ObjectTreeUtil.GetFullName(c.gameObject); } if (obj.GetType().IsSubclassOf(typeof(GameObject))) { GameObject go = (GameObject)obj; if (go == null) // GameObject overrides the == operator, so we have to check return string.Empty; return ObjectTreeUtil.GetFullName(go); } return obj.ToString(); } }; /// <summary> /// For all registered object types, record their state when exiting Play Mode, /// and restore that state to the objects in the scene. This is a very limited /// implementation which has not been rigorously tested with many objects types. /// It's quite possible that not everything will be saved. /// /// This class is expected to become obsolete when Unity implements this functionality /// in a more general way. /// /// To use this class, /// drop this script into your project, and add the [SaveDuringPlay] attribute to your class. /// /// Note: if you want some specific field in your class NOT to be saved during play, /// add a property attribute whose class name contains the string "NoSaveDuringPlay" /// and the field will not be saved. /// </summary> [InitializeOnLoad] public class SaveDuringPlay { static SaveDuringPlay() { // Install our callbacks EditorApplication.update += OnEditorUpdate; EditorApplication.playmodeStateChanged += OnPlayStateChanged; } static void OnPlayStateChanged() { // If exiting playmode, collect the state of all interesting objects if (!EditorApplication.isPlayingOrWillChangePlaymode && EditorApplication.isPlaying) SaveAllInterestingStates(); } static float sWaitStartTime = 0; static void OnEditorUpdate() { if (sSavedStates != null && !Application.isPlaying) { // Wait a bit for things to settle before applying the saved state const float WaitTime = 1f; // GML todo: is there a better way to do this? float time = Time.realtimeSinceStartup; if (sWaitStartTime == 0) sWaitStartTime = time; else if (time - sWaitStartTime > WaitTime) { RestoreAllInterestingStates(); sWaitStartTime = 0; } } } /// <summary> /// If you need to get notified before state is collected for hotsave, this is the place /// </summary> public static OnHotSaveDelegate OnHotSave; public delegate void OnHotSaveDelegate(); /// Collect all relevant objects, active or not static Transform[] FindInterestingObjects() { List<Transform> objects = new List<Transform>(); MonoBehaviour[] everything = ObjectTreeUtil.FindAllBehavioursInScene<MonoBehaviour>(); foreach (var b in everything) { var attrs = b.GetType().GetCustomAttributes(true); foreach (var attr in attrs) { if (attr.GetType().Name.Contains("SaveDuringPlay")) { //Debug.Log("Found " + b.gameObject.name + " for hot-save"); objects.Add(b.transform); break; } } } return objects.ToArray(); } static List<ObjectStateSaver> sSavedStates = null; static GameObject sSaveStatesGameObject; static void SaveAllInterestingStates() { //Debug.Log("Exiting play mode: Saving state for all interesting objects"); if (OnHotSave != null) OnHotSave(); sSavedStates = new List<ObjectStateSaver>(); Transform[] objects = FindInterestingObjects(); foreach (Transform obj in objects) { ObjectStateSaver saver = new ObjectStateSaver(); saver.CollectFieldValues(obj.gameObject); sSavedStates.Add(saver); } if (sSavedStates.Count == 0) sSavedStates = null; } static void RestoreAllInterestingStates() { //Debug.Log("Updating state for all interesting objects"); foreach (ObjectStateSaver saver in sSavedStates) { GameObject go = saver.FindSavedGameObject(); if (go != null) { // Doesn't work unless I use the obsolete API. // It still doesn't seem to play well with Undo. // GML: How to fix this? I'm out of ideas... #pragma warning disable 0618 Undo.RegisterUndo(go, "SaveDuringPlay"); if (saver.PutFieldValues(go)) { //Debug.Log("SaveDuringPlay: updated settings of " + saver.ObjetFullPath); EditorUtility.SetDirty(go); } } } sSavedStates = null; } } }
/* * OANDA v20 REST API * * The full OANDA v20 REST API Specification. This specification defines how to interact with v20 Accounts, Trades, Orders, Pricing and more. * * OpenAPI spec version: 3.0.15 * Contact: [email protected] * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace Oanda.RestV20.Model { /// <summary> /// A TradeClientExtensionsModifyTransaction represents the modification of a Trade&#39;s Client Extensions. /// </summary> [DataContract] public partial class TradeClientExtensionsModifyTransaction : IEquatable<TradeClientExtensionsModifyTransaction>, IValidatableObject { /// <summary> /// The Type of the Transaction. Always set to \"TRADE_CLIENT_EXTENSIONS_MODIFY\" for a TradeClientExtensionsModifyTransaction. /// </summary> /// <value>The Type of the Transaction. Always set to \"TRADE_CLIENT_EXTENSIONS_MODIFY\" for a TradeClientExtensionsModifyTransaction.</value> [JsonConverter(typeof(StringEnumConverter))] public enum TypeEnum { /// <summary> /// Enum CREATE for "CREATE" /// </summary> [EnumMember(Value = "CREATE")] CREATE, /// <summary> /// Enum CLOSE for "CLOSE" /// </summary> [EnumMember(Value = "CLOSE")] CLOSE, /// <summary> /// Enum REOPEN for "REOPEN" /// </summary> [EnumMember(Value = "REOPEN")] REOPEN, /// <summary> /// Enum CLIENTCONFIGURE for "CLIENT_CONFIGURE" /// </summary> [EnumMember(Value = "CLIENT_CONFIGURE")] CLIENTCONFIGURE, /// <summary> /// Enum CLIENTCONFIGUREREJECT for "CLIENT_CONFIGURE_REJECT" /// </summary> [EnumMember(Value = "CLIENT_CONFIGURE_REJECT")] CLIENTCONFIGUREREJECT, /// <summary> /// Enum TRANSFERFUNDS for "TRANSFER_FUNDS" /// </summary> [EnumMember(Value = "TRANSFER_FUNDS")] TRANSFERFUNDS, /// <summary> /// Enum TRANSFERFUNDSREJECT for "TRANSFER_FUNDS_REJECT" /// </summary> [EnumMember(Value = "TRANSFER_FUNDS_REJECT")] TRANSFERFUNDSREJECT, /// <summary> /// Enum MARKETORDER for "MARKET_ORDER" /// </summary> [EnumMember(Value = "MARKET_ORDER")] MARKETORDER, /// <summary> /// Enum MARKETORDERREJECT for "MARKET_ORDER_REJECT" /// </summary> [EnumMember(Value = "MARKET_ORDER_REJECT")] MARKETORDERREJECT, /// <summary> /// Enum LIMITORDER for "LIMIT_ORDER" /// </summary> [EnumMember(Value = "LIMIT_ORDER")] LIMITORDER, /// <summary> /// Enum LIMITORDERREJECT for "LIMIT_ORDER_REJECT" /// </summary> [EnumMember(Value = "LIMIT_ORDER_REJECT")] LIMITORDERREJECT, /// <summary> /// Enum STOPORDER for "STOP_ORDER" /// </summary> [EnumMember(Value = "STOP_ORDER")] STOPORDER, /// <summary> /// Enum STOPORDERREJECT for "STOP_ORDER_REJECT" /// </summary> [EnumMember(Value = "STOP_ORDER_REJECT")] STOPORDERREJECT, /// <summary> /// Enum MARKETIFTOUCHEDORDER for "MARKET_IF_TOUCHED_ORDER" /// </summary> [EnumMember(Value = "MARKET_IF_TOUCHED_ORDER")] MARKETIFTOUCHEDORDER, /// <summary> /// Enum MARKETIFTOUCHEDORDERREJECT for "MARKET_IF_TOUCHED_ORDER_REJECT" /// </summary> [EnumMember(Value = "MARKET_IF_TOUCHED_ORDER_REJECT")] MARKETIFTOUCHEDORDERREJECT, /// <summary> /// Enum TAKEPROFITORDER for "TAKE_PROFIT_ORDER" /// </summary> [EnumMember(Value = "TAKE_PROFIT_ORDER")] TAKEPROFITORDER, /// <summary> /// Enum TAKEPROFITORDERREJECT for "TAKE_PROFIT_ORDER_REJECT" /// </summary> [EnumMember(Value = "TAKE_PROFIT_ORDER_REJECT")] TAKEPROFITORDERREJECT, /// <summary> /// Enum STOPLOSSORDER for "STOP_LOSS_ORDER" /// </summary> [EnumMember(Value = "STOP_LOSS_ORDER")] STOPLOSSORDER, /// <summary> /// Enum STOPLOSSORDERREJECT for "STOP_LOSS_ORDER_REJECT" /// </summary> [EnumMember(Value = "STOP_LOSS_ORDER_REJECT")] STOPLOSSORDERREJECT, /// <summary> /// Enum TRAILINGSTOPLOSSORDER for "TRAILING_STOP_LOSS_ORDER" /// </summary> [EnumMember(Value = "TRAILING_STOP_LOSS_ORDER")] TRAILINGSTOPLOSSORDER, /// <summary> /// Enum TRAILINGSTOPLOSSORDERREJECT for "TRAILING_STOP_LOSS_ORDER_REJECT" /// </summary> [EnumMember(Value = "TRAILING_STOP_LOSS_ORDER_REJECT")] TRAILINGSTOPLOSSORDERREJECT, /// <summary> /// Enum ORDERFILL for "ORDER_FILL" /// </summary> [EnumMember(Value = "ORDER_FILL")] ORDERFILL, /// <summary> /// Enum ORDERCANCEL for "ORDER_CANCEL" /// </summary> [EnumMember(Value = "ORDER_CANCEL")] ORDERCANCEL, /// <summary> /// Enum ORDERCANCELREJECT for "ORDER_CANCEL_REJECT" /// </summary> [EnumMember(Value = "ORDER_CANCEL_REJECT")] ORDERCANCELREJECT, /// <summary> /// Enum ORDERCLIENTEXTENSIONSMODIFY for "ORDER_CLIENT_EXTENSIONS_MODIFY" /// </summary> [EnumMember(Value = "ORDER_CLIENT_EXTENSIONS_MODIFY")] ORDERCLIENTEXTENSIONSMODIFY, /// <summary> /// Enum ORDERCLIENTEXTENSIONSMODIFYREJECT for "ORDER_CLIENT_EXTENSIONS_MODIFY_REJECT" /// </summary> [EnumMember(Value = "ORDER_CLIENT_EXTENSIONS_MODIFY_REJECT")] ORDERCLIENTEXTENSIONSMODIFYREJECT, /// <summary> /// Enum TRADECLIENTEXTENSIONSMODIFY for "TRADE_CLIENT_EXTENSIONS_MODIFY" /// </summary> [EnumMember(Value = "TRADE_CLIENT_EXTENSIONS_MODIFY")] TRADECLIENTEXTENSIONSMODIFY, /// <summary> /// Enum TRADECLIENTEXTENSIONSMODIFYREJECT for "TRADE_CLIENT_EXTENSIONS_MODIFY_REJECT" /// </summary> [EnumMember(Value = "TRADE_CLIENT_EXTENSIONS_MODIFY_REJECT")] TRADECLIENTEXTENSIONSMODIFYREJECT, /// <summary> /// Enum MARGINCALLENTER for "MARGIN_CALL_ENTER" /// </summary> [EnumMember(Value = "MARGIN_CALL_ENTER")] MARGINCALLENTER, /// <summary> /// Enum MARGINCALLEXTEND for "MARGIN_CALL_EXTEND" /// </summary> [EnumMember(Value = "MARGIN_CALL_EXTEND")] MARGINCALLEXTEND, /// <summary> /// Enum MARGINCALLEXIT for "MARGIN_CALL_EXIT" /// </summary> [EnumMember(Value = "MARGIN_CALL_EXIT")] MARGINCALLEXIT, /// <summary> /// Enum DELAYEDTRADECLOSURE for "DELAYED_TRADE_CLOSURE" /// </summary> [EnumMember(Value = "DELAYED_TRADE_CLOSURE")] DELAYEDTRADECLOSURE, /// <summary> /// Enum DAILYFINANCING for "DAILY_FINANCING" /// </summary> [EnumMember(Value = "DAILY_FINANCING")] DAILYFINANCING, /// <summary> /// Enum RESETRESETTABLEPL for "RESET_RESETTABLE_PL" /// </summary> [EnumMember(Value = "RESET_RESETTABLE_PL")] RESETRESETTABLEPL } /// <summary> /// The Type of the Transaction. Always set to \"TRADE_CLIENT_EXTENSIONS_MODIFY\" for a TradeClientExtensionsModifyTransaction. /// </summary> /// <value>The Type of the Transaction. Always set to \"TRADE_CLIENT_EXTENSIONS_MODIFY\" for a TradeClientExtensionsModifyTransaction.</value> [DataMember(Name="type", EmitDefaultValue=false)] public TypeEnum? Type { get; set; } /// <summary> /// Initializes a new instance of the <see cref="TradeClientExtensionsModifyTransaction" /> class. /// </summary> /// <param name="Id">The Transaction&#39;s Identifier..</param> /// <param name="Time">The date/time when the Transaction was created..</param> /// <param name="UserID">The ID of the user that initiated the creation of the Transaction..</param> /// <param name="AccountID">The ID of the Account the Transaction was created for..</param> /// <param name="BatchID">The ID of the \&quot;batch\&quot; that the Transaction belongs to. Transactions in the same batch are applied to the Account simultaneously..</param> /// <param name="RequestID">The Request ID of the request which generated the transaction..</param> /// <param name="Type">The Type of the Transaction. Always set to \&quot;TRADE_CLIENT_EXTENSIONS_MODIFY\&quot; for a TradeClientExtensionsModifyTransaction..</param> /// <param name="TradeID">The ID of the Trade who&#39;s client extensions are to be modified..</param> /// <param name="ClientTradeID">The original Client ID of the Trade who&#39;s client extensions are to be modified..</param> /// <param name="TradeClientExtensionsModify">TradeClientExtensionsModify.</param> public TradeClientExtensionsModifyTransaction(string Id = default(string), string Time = default(string), int? UserID = default(int?), string AccountID = default(string), string BatchID = default(string), string RequestID = default(string), TypeEnum? Type = default(TypeEnum?), string TradeID = default(string), string ClientTradeID = default(string), ClientExtensions TradeClientExtensionsModify = default(ClientExtensions)) { this.Id = Id; this.Time = Time; this.UserID = UserID; this.AccountID = AccountID; this.BatchID = BatchID; this.RequestID = RequestID; this.Type = Type; this.TradeID = TradeID; this.ClientTradeID = ClientTradeID; this.TradeClientExtensionsModify = TradeClientExtensionsModify; } /// <summary> /// The Transaction&#39;s Identifier. /// </summary> /// <value>The Transaction&#39;s Identifier.</value> [DataMember(Name="id", EmitDefaultValue=false)] public string Id { get; set; } /// <summary> /// The date/time when the Transaction was created. /// </summary> /// <value>The date/time when the Transaction was created.</value> [DataMember(Name="time", EmitDefaultValue=false)] public string Time { get; set; } /// <summary> /// The ID of the user that initiated the creation of the Transaction. /// </summary> /// <value>The ID of the user that initiated the creation of the Transaction.</value> [DataMember(Name="userID", EmitDefaultValue=false)] public int? UserID { get; set; } /// <summary> /// The ID of the Account the Transaction was created for. /// </summary> /// <value>The ID of the Account the Transaction was created for.</value> [DataMember(Name="accountID", EmitDefaultValue=false)] public string AccountID { get; set; } /// <summary> /// The ID of the \&quot;batch\&quot; that the Transaction belongs to. Transactions in the same batch are applied to the Account simultaneously. /// </summary> /// <value>The ID of the \&quot;batch\&quot; that the Transaction belongs to. Transactions in the same batch are applied to the Account simultaneously.</value> [DataMember(Name="batchID", EmitDefaultValue=false)] public string BatchID { get; set; } /// <summary> /// The Request ID of the request which generated the transaction. /// </summary> /// <value>The Request ID of the request which generated the transaction.</value> [DataMember(Name="requestID", EmitDefaultValue=false)] public string RequestID { get; set; } /// <summary> /// The ID of the Trade who&#39;s client extensions are to be modified. /// </summary> /// <value>The ID of the Trade who&#39;s client extensions are to be modified.</value> [DataMember(Name="tradeID", EmitDefaultValue=false)] public string TradeID { get; set; } /// <summary> /// The original Client ID of the Trade who&#39;s client extensions are to be modified. /// </summary> /// <value>The original Client ID of the Trade who&#39;s client extensions are to be modified.</value> [DataMember(Name="clientTradeID", EmitDefaultValue=false)] public string ClientTradeID { get; set; } /// <summary> /// Gets or Sets TradeClientExtensionsModify /// </summary> [DataMember(Name="tradeClientExtensionsModify", EmitDefaultValue=false)] public ClientExtensions TradeClientExtensionsModify { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class TradeClientExtensionsModifyTransaction {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Time: ").Append(Time).Append("\n"); sb.Append(" UserID: ").Append(UserID).Append("\n"); sb.Append(" AccountID: ").Append(AccountID).Append("\n"); sb.Append(" BatchID: ").Append(BatchID).Append("\n"); sb.Append(" RequestID: ").Append(RequestID).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append(" TradeID: ").Append(TradeID).Append("\n"); sb.Append(" ClientTradeID: ").Append(ClientTradeID).Append("\n"); sb.Append(" TradeClientExtensionsModify: ").Append(TradeClientExtensionsModify).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as TradeClientExtensionsModifyTransaction); } /// <summary> /// Returns true if TradeClientExtensionsModifyTransaction instances are equal /// </summary> /// <param name="other">Instance of TradeClientExtensionsModifyTransaction to be compared</param> /// <returns>Boolean</returns> public bool Equals(TradeClientExtensionsModifyTransaction other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.Time == other.Time || this.Time != null && this.Time.Equals(other.Time) ) && ( this.UserID == other.UserID || this.UserID != null && this.UserID.Equals(other.UserID) ) && ( this.AccountID == other.AccountID || this.AccountID != null && this.AccountID.Equals(other.AccountID) ) && ( this.BatchID == other.BatchID || this.BatchID != null && this.BatchID.Equals(other.BatchID) ) && ( this.RequestID == other.RequestID || this.RequestID != null && this.RequestID.Equals(other.RequestID) ) && ( this.Type == other.Type || this.Type != null && this.Type.Equals(other.Type) ) && ( this.TradeID == other.TradeID || this.TradeID != null && this.TradeID.Equals(other.TradeID) ) && ( this.ClientTradeID == other.ClientTradeID || this.ClientTradeID != null && this.ClientTradeID.Equals(other.ClientTradeID) ) && ( this.TradeClientExtensionsModify == other.TradeClientExtensionsModify || this.TradeClientExtensionsModify != null && this.TradeClientExtensionsModify.Equals(other.TradeClientExtensionsModify) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.Time != null) hash = hash * 59 + this.Time.GetHashCode(); if (this.UserID != null) hash = hash * 59 + this.UserID.GetHashCode(); if (this.AccountID != null) hash = hash * 59 + this.AccountID.GetHashCode(); if (this.BatchID != null) hash = hash * 59 + this.BatchID.GetHashCode(); if (this.RequestID != null) hash = hash * 59 + this.RequestID.GetHashCode(); if (this.Type != null) hash = hash * 59 + this.Type.GetHashCode(); if (this.TradeID != null) hash = hash * 59 + this.TradeID.GetHashCode(); if (this.ClientTradeID != null) hash = hash * 59 + this.ClientTradeID.GetHashCode(); if (this.TradeClientExtensionsModify != null) hash = hash * 59 + this.TradeClientExtensionsModify.GetHashCode(); return hash; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
// Visual Studio Shared Project // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using OleConstants = Microsoft.VisualStudio.OLE.Interop.Constants; using VsCommands = Microsoft.VisualStudio.VSConstants.VSStd97CmdID; using VsCommands2K = Microsoft.VisualStudio.VSConstants.VSStd2KCmdID; using Microsoft.VisualStudioTools.Infrastructure; #if DEV14_OR_LATER using Microsoft.VisualStudio.Imaging; using Microsoft.VisualStudio.Imaging.Interop; #endif namespace Microsoft.VisualStudioTools.Project { internal class FolderNode : HierarchyNode, IDiskBasedNode { #region ctors /// <summary> /// Constructor for the FolderNode /// </summary> /// <param name="root">Root node of the hierarchy</param> /// <param name="relativePath">relative path from root i.e.: "NewFolder1\\NewFolder2\\NewFolder3</param> /// <param name="element">Associated project element</param> public FolderNode(ProjectNode root, ProjectElement element) : base(root, element) { } #endregion #region overridden properties public override bool CanOpenCommandPrompt { get { return true; } } internal override string FullPathToChildren { get { return Url; } } public override int SortPriority { get { return DefaultSortOrderNode.FolderNode; } } /// <summary> /// This relates to the SCC glyph /// </summary> public override VsStateIcon StateIconIndex { get { // The SCC manager does not support being asked for the state icon of a folder (result of the operation is undefined) return VsStateIcon.STATEICON_NOSTATEICON; } } public override bool CanAddFiles { get { return true; } } #endregion #region overridden methods protected override NodeProperties CreatePropertiesObject() { return new FolderNodeProperties(this); } protected internal override void DeleteFromStorage(string path) { this.DeleteFolder(path); } /// <summary> /// Get the automation object for the FolderNode /// </summary> /// <returns>An instance of the Automation.OAFolderNode type if succeeded</returns> public override object GetAutomationObject() { if (this.ProjectMgr == null || this.ProjectMgr.IsClosed) { return null; } return new Automation.OAFolderItem(this.ProjectMgr.GetAutomationObject() as Automation.OAProject, this); } #if DEV14_OR_LATER protected override bool SupportsIconMonikers { get { return true; } } protected override ImageMoniker GetIconMoniker(bool open) { return open ? KnownMonikers.FolderOpened : KnownMonikers.FolderClosed; } #else public override object GetIconHandle(bool open) { return ProjectMgr.GetIconHandleByName(open ? ProjectNode.ImageName.OpenFolder : ProjectNode.ImageName.Folder ); } #endif /// <summary> /// Rename Folder /// </summary> /// <param name="label">new Name of Folder</param> /// <returns>VSConstants.S_OK, if succeeded</returns> public override int SetEditLabel(string label) { if (IsBeingCreated) { return FinishFolderAdd(label, false); } else { if (String.Equals(CommonUtils.GetFileOrDirectoryName(Url), label, StringComparison.Ordinal)) { // Label matches current Name return VSConstants.S_OK; } string newPath = CommonUtils.GetAbsoluteDirectoryPath(CommonUtils.GetParent(Url), label); // Verify that No Directory/file already exists with the new name among current children var existingChild = Parent.FindImmediateChildByName(label); if (existingChild != null && existingChild != this) { return ShowFileOrFolderAlreadyExistsErrorMessage(newPath); } // Verify that No Directory/file already exists with the new name on disk. // Unless the path exists because it is the path to the source file also. if ((Directory.Exists(newPath) || File.Exists(newPath)) && !CommonUtils.IsSamePath(Url, newPath)) { return ShowFileOrFolderAlreadyExistsErrorMessage(newPath); } if (!ProjectMgr.Tracker.CanRenameItem(Url, newPath, VSRENAMEFILEFLAGS.VSRENAMEFILEFLAGS_Directory)) { return VSConstants.S_OK; } } try { var oldTriggerFlag = this.ProjectMgr.EventTriggeringFlag; ProjectMgr.EventTriggeringFlag |= ProjectNode.EventTriggering.DoNotTriggerTrackerQueryEvents; try { RenameFolder(label); } finally { ProjectMgr.EventTriggeringFlag = oldTriggerFlag; } //Refresh the properties in the properties window IVsUIShell shell = this.ProjectMgr.GetService(typeof(SVsUIShell)) as IVsUIShell; Utilities.CheckNotNull(shell, "Could not get the UI shell from the project"); ErrorHandler.ThrowOnFailure(shell.RefreshPropertyBrowser(0)); // Notify the listeners that the name of this folder is changed. This will // also force a refresh of the SolutionExplorer's node. ProjectMgr.OnPropertyChanged(this, (int)__VSHPROPID.VSHPROPID_Caption, 0); } catch (Exception e) { if (e.IsCriticalException()) { throw; } throw new InvalidOperationException(SR.GetString(SR.RenameFolder, e.Message)); } return VSConstants.S_OK; } internal static string PathTooLongMessage { get { return SR.GetString(SR.PathTooLongShortMessage); } } private int FinishFolderAdd(string label, bool wasCancelled) { // finish creation string filename = label.Trim(); if (filename == "." || filename == "..") { Debug.Assert(!wasCancelled); // cancelling leaves us with a valid label NativeMethods.SetErrorDescription("{0} is an invalid filename.", filename); return VSConstants.E_FAIL; } var path = Path.Combine(Parent.FullPathToChildren, label); if (path.Length >= NativeMethods.MAX_FOLDER_PATH) { if (wasCancelled) { // cancelling an edit label doesn't result in the error // being displayed, so we'll display one for the user. Utilities.ShowMessageBox( ProjectMgr.Site, null, PathTooLongMessage, OLEMSGICON.OLEMSGICON_CRITICAL, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST ); } else { NativeMethods.SetErrorDescription(PathTooLongMessage); } return VSConstants.E_FAIL; } if (filename == Caption || Parent.FindImmediateChildByName(filename) == null) { if (ProjectMgr.QueryFolderAdd(Parent, path)) { Directory.CreateDirectory(path); IsBeingCreated = false; var relativePath = CommonUtils.GetRelativeDirectoryPath( ProjectMgr.ProjectHome, CommonUtils.GetAbsoluteDirectoryPath(CommonUtils.GetParent(Url), label) ); this.ItemNode.Rename(relativePath); ProjectMgr.OnItemDeleted(this); this.Parent.RemoveChild(this); ProjectMgr.Site.GetUIThread().MustBeCalledFromUIThread(); this.ID = ProjectMgr.ItemIdMap.Add(this); this.Parent.AddChild(this); ExpandItem(EXPANDFLAGS.EXPF_SelectItem); ProjectMgr.Tracker.OnFolderAdded( path, VSADDDIRECTORYFLAGS.VSADDDIRECTORYFLAGS_NoFlags ); } } else { Debug.Assert(!wasCancelled); // we choose a label which didn't exist when we started the edit // Set error: folder already exists NativeMethods.SetErrorDescription("The folder {0} already exists.", filename); return VSConstants.E_FAIL; } return VSConstants.S_OK; } public override int MenuCommandId { get { return VsMenus.IDM_VS_CTXT_FOLDERNODE; } } public override Guid ItemTypeGuid { get { return VSConstants.GUID_ItemType_PhysicalFolder; } } public override string Url { get { return CommonUtils.EnsureEndSeparator(ItemNode.Url); } } public override string Caption { get { // it might have a backslash at the end... // and it might consist of Grandparent\parent\this\ return CommonUtils.GetFileOrDirectoryName(Url); } } public override string GetMkDocument() { Debug.Assert(!string.IsNullOrEmpty(this.Url), "No url specified for this node"); Debug.Assert(Path.IsPathRooted(this.Url), "Url should not be a relative path"); return this.Url; } /// <summary> /// Recursively walks the folder nodes and redraws the state icons /// </summary> protected internal override void UpdateSccStateIcons() { for (HierarchyNode child = this.FirstChild; child != null; child = child.NextSibling) { child.UpdateSccStateIcons(); } } internal override int QueryStatusOnNode(Guid cmdGroup, uint cmd, IntPtr pCmdText, ref QueryStatusResult result) { if (cmdGroup == VsMenus.guidStandardCommandSet97) { switch ((VsCommands)cmd) { case VsCommands.Copy: case VsCommands.Paste: case VsCommands.Cut: case VsCommands.Rename: result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED; return VSConstants.S_OK; case VsCommands.NewFolder: if (!IsNonMemberItem) { result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED; return VSConstants.S_OK; } break; } } else if (cmdGroup == VsMenus.guidStandardCommandSet2K) { if ((VsCommands2K)cmd == VsCommands2K.EXCLUDEFROMPROJECT) { result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED; return VSConstants.S_OK; } } else if (cmdGroup != ProjectMgr.SharedCommandGuid) { return (int)OleConstants.OLECMDERR_E_UNKNOWNGROUP; } return base.QueryStatusOnNode(cmdGroup, cmd, pCmdText, ref result); } internal override bool CanDeleteItem(__VSDELETEITEMOPERATION deleteOperation) { if (deleteOperation == __VSDELETEITEMOPERATION.DELITEMOP_DeleteFromStorage) { return this.ProjectMgr.CanProjectDeleteItems; } return false; } protected internal override void GetSccFiles(IList<string> files, IList<tagVsSccFilesFlags> flags) { for (HierarchyNode n = this.FirstChild; n != null; n = n.NextSibling) { n.GetSccFiles(files, flags); } } protected internal override void GetSccSpecialFiles(string sccFile, IList<string> files, IList<tagVsSccFilesFlags> flags) { for (HierarchyNode n = this.FirstChild; n != null; n = n.NextSibling) { n.GetSccSpecialFiles(sccFile, files, flags); } } #endregion #region virtual methods /// <summary> /// Override if your node is not a file system folder so that /// it does nothing or it deletes it from your storage location. /// </summary> /// <param name="path">Path to the folder to delete</param> public virtual void DeleteFolder(string path) { if (Directory.Exists(path)) { try { try { Directory.Delete(path, true); } catch (UnauthorizedAccessException) { // probably one or more files are read only foreach (var file in Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories)) { // We will ignore all exceptions here and rethrow when // we retry the Directory.Delete. try { File.SetAttributes(file, FileAttributes.Normal); } catch (UnauthorizedAccessException) { } catch (IOException) { } } Directory.Delete(path, true); } } catch (IOException ioEx) { // re-throw with a friendly path throw new IOException(ioEx.Message.Replace(path, Caption)); } } } /// <summary> /// creates the physical directory for a folder node /// Override if your node does not use file system folder /// </summary> public virtual void CreateDirectory() { if (Directory.Exists(this.Url) == false) { Directory.CreateDirectory(this.Url); } } /// <summary> /// Creates a folder nodes physical directory /// Override if your node does not use file system folder /// </summary> /// <param name="newName"></param> /// <returns></returns> public virtual void CreateDirectory(string newName) { if (String.IsNullOrEmpty(newName)) { throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty), "newName"); } // on a new dir && enter, we get called with the same name (so do nothing if name is the same string strNewDir = CommonUtils.GetAbsoluteDirectoryPath(CommonUtils.GetParent(Url), newName); if (!CommonUtils.IsSameDirectory(Url, strNewDir)) { if (Directory.Exists(strNewDir)) { throw new InvalidOperationException(SR.GetString(SR.DirectoryExistsShortMessage)); } Directory.CreateDirectory(strNewDir); } } /// <summary> /// Rename the physical directory for a folder node /// Override if your node does not use file system folder /// </summary> /// <returns></returns> public virtual void RenameDirectory(string newPath) { if (Directory.Exists(this.Url)) { if (CommonUtils.IsSamePath(this.Url, newPath)) { // This is a rename to the same location with (possible) capitilization changes. // Directory.Move does not allow renaming to the same name so P/Invoke MoveFile to bypass this. if (!NativeMethods.MoveFile(this.Url, newPath)) { // Rather than perform error handling, Call Directory.Move and let it handle the error handling. // If this succeeds, then we didn't really have errors that needed handling. Directory.Move(this.Url, newPath); } } else if (Directory.Exists(newPath)) { // Directory exists and it wasn't the source. Item cannot be moved as name exists. ShowFileOrFolderAlreadyExistsErrorMessage(newPath); } else { Directory.Move(this.Url, newPath); } } } void IDiskBasedNode.RenameForDeferredSave(string basePath, string baseNewPath) { string oldPath = Path.Combine(basePath, ItemNode.GetMetadata(ProjectFileConstants.Include)); string newPath = Path.Combine(baseNewPath, ItemNode.GetMetadata(ProjectFileConstants.Include)); Directory.CreateDirectory(newPath); ProjectMgr.UpdatePathForDeferredSave(oldPath, newPath); } #endregion #region helper methods /// <summary> /// Renames the folder to the new name. /// </summary> public virtual void RenameFolder(string newName) { // Do the rename (note that we only do the physical rename if the leaf name changed) string newPath = Path.Combine(Parent.FullPathToChildren, newName); string oldPath = Url; if (!String.Equals(Path.GetFileName(Url), newName, StringComparison.Ordinal)) { RenameDirectory(CommonUtils.GetAbsoluteDirectoryPath(ProjectMgr.ProjectHome, newPath)); } bool wasExpanded = GetIsExpanded(); ReparentFolder(newPath); var oldTriggerFlag = ProjectMgr.EventTriggeringFlag; ProjectMgr.EventTriggeringFlag |= ProjectNode.EventTriggering.DoNotTriggerTrackerEvents; try { // Let all children know of the new path for (HierarchyNode child = this.FirstChild; child != null; child = child.NextSibling) { FolderNode node = child as FolderNode; if (node == null) { child.SetEditLabel(child.GetEditLabel()); } else { node.RenameFolder(node.Caption); } } } finally { ProjectMgr.EventTriggeringFlag = oldTriggerFlag; } ProjectMgr.Tracker.OnItemRenamed(oldPath, newPath, VSRENAMEFILEFLAGS.VSRENAMEFILEFLAGS_Directory); // Some of the previous operation may have changed the selection so set it back to us ExpandItem(wasExpanded ? EXPANDFLAGS.EXPF_ExpandFolder : EXPANDFLAGS.EXPF_CollapseFolder); ExpandItem(EXPANDFLAGS.EXPF_SelectItem); } /// <summary> /// Moves the HierarchyNode from the old path to be a child of the /// newly specified node. /// /// This is a low-level operation that only updates the hierarchy and our MSBuild /// state. The parents of the node must already be created. /// /// To do a general rename, call RenameFolder instead. /// </summary> internal void ReparentFolder(string newPath) { // Reparent the folder ProjectMgr.OnItemDeleted(this); Parent.RemoveChild(this); ProjectMgr.Site.GetUIThread().MustBeCalledFromUIThread(); ID = ProjectMgr.ItemIdMap.Add(this); ItemNode.Rename(CommonUtils.GetRelativeDirectoryPath(ProjectMgr.ProjectHome, newPath)); var parent = ProjectMgr.GetParentFolderForPath(newPath); if (parent == null) { Debug.Fail("ReparentFolder called without full path to parent being created"); throw new DirectoryNotFoundException(newPath); } parent.AddChild(this); } /// <summary> /// Show error message if not in automation mode, otherwise throw exception /// </summary> /// <param name="newPath">path of file or folder already existing on disk</param> /// <returns>S_OK</returns> private int ShowFileOrFolderAlreadyExistsErrorMessage(string newPath) { //A file or folder with the name '{0}' already exists on disk at this location. Please choose another name. //If this file or folder does not appear in the Solution Explorer, then it is not currently part of your project. To view files which exist on disk, but are not in the project, select Show All Files from the Project menu. string errorMessage = SR.GetString(SR.FileOrFolderAlreadyExists, newPath); if (!Utilities.IsInAutomationFunction(this.ProjectMgr.Site)) { string title = null; OLEMSGICON icon = OLEMSGICON.OLEMSGICON_CRITICAL; OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK; OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST; Utilities.ShowMessageBox(this.ProjectMgr.Site, title, errorMessage, icon, buttons, defaultButton); return VSConstants.S_OK; } else { throw new InvalidOperationException(errorMessage); } } protected override void OnCancelLabelEdit() { if (IsBeingCreated) { // finish the creation FinishFolderAdd(Caption, true); } } internal bool IsBeingCreated { get { return ProjectMgr.FolderBeingCreated == this; } set { if (value) { ProjectMgr.FolderBeingCreated = this; } else { ProjectMgr.FolderBeingCreated = null; } } } #endregion protected override void RaiseOnItemRemoved(string documentToRemove, string[] filesToBeDeleted) { VSREMOVEDIRECTORYFLAGS[] removeFlags = new VSREMOVEDIRECTORYFLAGS[1]; this.ProjectMgr.Tracker.OnFolderRemoved(documentToRemove, removeFlags[0]); } } }
// 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.Xml; using System.Collections.Generic; using System.IO; using System.Threading; using Microsoft.Build.Framework; using Microsoft.Build.BackEnd; using Microsoft.Build.Collections; using Microsoft.Build.Evaluation; using Microsoft.Build.Execution; using Microsoft.Build.Shared; using Shouldly; using ILoggingService = Microsoft.Build.BackEnd.Logging.ILoggingService; using ProjectLoggingContext = Microsoft.Build.BackEnd.Logging.ProjectLoggingContext; using NodeLoggingContext = Microsoft.Build.BackEnd.Logging.NodeLoggingContext; using LegacyThreadingData = Microsoft.Build.Execution.LegacyThreadingData; using System.Threading.Tasks; using Microsoft.Build.BackEnd.SdkResolution; using Microsoft.Build.Engine.UnitTests.BackEnd; using Xunit; namespace Microsoft.Build.UnitTests.BackEnd { /// <summary> /// This is the unit test for the TargetBuilder. This particular test is confined to just using the /// actual TargetBuilder, and uses a mock TaskBuilder on which TargetBuilder depends. /// </summary> public class TargetBuilder_Tests : IRequestBuilderCallback, IDisposable { /// <summary> /// The component host. /// </summary> private MockHost _host; /// <summary> /// A mock logger for scenario tests. /// </summary> private MockLogger _mockLogger; /// <summary> /// The node request id counter /// </summary> private int _nodeRequestId; #pragma warning disable xUnit1013 /// <summary> /// Callback used to receive exceptions from loggers. Unused here. /// </summary> /// <param name="e">The exception</param> public void LoggingException(Exception e) { } #pragma warning restore xUnit1013 /// <summary> /// Sets up to run tests. Creates the host object. /// </summary> public TargetBuilder_Tests() { _nodeRequestId = 1; _host = new MockHost(); _mockLogger = new MockLogger(); _host.OnLoggingThreadException += this.LoggingException; } /// <summary> /// Executed after all tests are run. /// </summary> public void Dispose() { File.Delete("testProject.proj"); _mockLogger = null; _host = null; } /// <summary> /// Runs the constructor. /// </summary> [Fact] public void TestConstructor() { TargetBuilder builder = new TargetBuilder(); } /// <summary> /// Runs a "simple" build with no dependencies and no outputs. /// </summary> [Fact] public void TestSimpleBuild() { ProjectInstance project = CreateTestProject(); // The Empty target has no inputs or outputs. TargetBuilder builder = (TargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestEntry entry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "Empty" }), cache[1]); BuildResult result = builder.BuildTargets(GetProjectLoggingContext(entry), entry, this, entry.Request.Targets.ToArray(), CreateStandardLookup(project), CancellationToken.None).Result; Assert.True(result.HasResultsForTarget("Empty")); Assert.Equal(TargetResultCode.Success, result["Empty"].ResultCode); Assert.Empty(result["Empty"].Items); } /// <summary> /// Runs a build with a target which depends on one other target. /// </summary> [Fact] public void TestDependencyBuild() { ProjectInstance project = CreateTestProject(); // The Baz project depends on the Bar target. Both should succeed. TargetBuilder builder = (TargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestEntry entry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "Baz" }), cache[1]); BuildResult result = builder.BuildTargets(GetProjectLoggingContext(entry), entry, this, entry.Request.Targets.ToArray(), CreateStandardLookup(project), CancellationToken.None).Result; // The result returned from the builder includes only those for the specified targets. Assert.True(result.HasResultsForTarget("Baz")); Assert.False(result.HasResultsForTarget("Bar")); Assert.Equal(TargetResultCode.Success, result["Baz"].ResultCode); // The results cache should have ALL of the results. IResultsCache resultsCache = (IResultsCache)_host.GetComponent(BuildComponentType.ResultsCache); Assert.True(resultsCache.GetResultForRequest(entry.Request).HasResultsForTarget("Bar")); Assert.Equal(TargetResultCode.Success, resultsCache.GetResultForRequest(entry.Request)["Bar"].ResultCode); } /// <summary> /// Tests a project with a dependency which will be skipped because its up-to-date. /// </summary> [Fact] public void TestDependencyBuildWithSkip() { ProjectInstance project = CreateTestProject(); // DepSkip depends on Skip (which skips) but should succeed itself. TargetBuilder builder = (TargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestEntry entry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "DepSkip" }), cache[1]); BuildResult result = builder.BuildTargets(GetProjectLoggingContext(entry), entry, this, entry.Request.Targets.ToArray(), CreateStandardLookup(project), CancellationToken.None).Result; Assert.True(result.HasResultsForTarget("DepSkip")); Assert.False(result.HasResultsForTarget("Skip")); Assert.Equal(TargetResultCode.Success, result["DepSkip"].ResultCode); IResultsCache resultsCache = (IResultsCache)_host.GetComponent(BuildComponentType.ResultsCache); Assert.True(resultsCache.GetResultForRequest(entry.Request).HasResultsForTarget("SkipCondition")); Assert.Equal(TargetResultCode.Skipped, resultsCache.GetResultForRequest(entry.Request)["SkipCondition"].ResultCode); } /// <summary> /// This test is currently ignored because the error tasks aren't implemented yet (due to needing the task builder.) /// </summary> [Fact] public void TestDependencyBuildWithError() { ProjectInstance project = CreateTestProject(); // The DepError target builds Foo (which succeeds), Skip (which skips) and Error (which fails), and Baz2 // Baz2 should not run since it came after Error. // Error tries to build Foo again as an error (which is already built) and Bar, which produces outputs. // DepError builds Baz as an error, which produces outputs TargetBuilder builder = (TargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); MockTaskBuilder taskBuilder = (MockTaskBuilder)_host.GetComponent(BuildComponentType.TaskBuilder); taskBuilder.FailTaskNumber = 3; // Succeed on Foo's one task, and Error's first task, and fail the second. IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestEntry entry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "DepError" }), cache[1]); BuildResult result = builder.BuildTargets(GetProjectLoggingContext(entry), entry, this, entry.Request.Targets.ToArray(), CreateStandardLookup(project), CancellationToken.None).Result; Assert.True(result.HasResultsForTarget("DepError")); Assert.False(result.HasResultsForTarget("Foo")); Assert.False(result.HasResultsForTarget("Skip")); Assert.False(result.HasResultsForTarget("Error")); Assert.False(result.HasResultsForTarget("Baz2")); Assert.False(result.HasResultsForTarget("Bar")); Assert.False(result.HasResultsForTarget("Baz")); IResultsCache resultsCache = (IResultsCache)_host.GetComponent(BuildComponentType.ResultsCache); Assert.True(resultsCache.GetResultForRequest(entry.Request).HasResultsForTarget("Foo")); Assert.True(resultsCache.GetResultForRequest(entry.Request).HasResultsForTarget("Skip")); Assert.True(resultsCache.GetResultForRequest(entry.Request).HasResultsForTarget("Error")); Assert.False(resultsCache.GetResultForRequest(entry.Request).HasResultsForTarget("Baz2")); Assert.True(resultsCache.GetResultForRequest(entry.Request).HasResultsForTarget("Bar")); Assert.True(resultsCache.GetResultForRequest(entry.Request).HasResultsForTarget("Baz")); Assert.Equal(TargetResultCode.Failure, resultsCache.GetResultForRequest(entry.Request)["DepError"].ResultCode); Assert.Equal(TargetResultCode.Success, resultsCache.GetResultForRequest(entry.Request)["Foo"].ResultCode); Assert.Equal(TargetResultCode.Success, resultsCache.GetResultForRequest(entry.Request)["Skip"].ResultCode); Assert.Equal(TargetResultCode.Failure, resultsCache.GetResultForRequest(entry.Request)["Error"].ResultCode); Assert.Equal(TargetResultCode.Success, resultsCache.GetResultForRequest(entry.Request)["Bar"].ResultCode); Assert.Equal(TargetResultCode.Success, resultsCache.GetResultForRequest(entry.Request)["Baz"].ResultCode); } /// <summary> /// Ensure that skipped targets only infer outputs once /// </summary> [Fact] public void SkippedTargetsShouldOnlyInferOutputsOnce() { MockLogger logger = new MockLogger(); string path = FileUtilities.GetTemporaryFile(); Thread.Sleep(100); string content = String.Format ( @" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <Target Name='Build' DependsOnTargets='GFA;GFT;DFTA;GAFT'> <Message Text='Build: [@(Outs)]' /> </Target> <Target Name='GFA' Inputs='{0}' Outputs='{0}'> <Message Text='GFA' /> <CreateItem Include='GFA'> <Output TaskParameter='Include' ItemName='Outs' /> </CreateItem> </Target> <Target Name='GFT' Inputs='{0}' Outputs='{0}'> <CreateItem Include='GFT'> <Output TaskParameter='Include' ItemName='Outs' /> </CreateItem> <Message Text='GFT' /> </Target> <Target Name='DFTA' Inputs='{0}' Outputs='{0}'> <CreateItem Include='DFTA'> <Output TaskParameter='Include' ItemName='Outs' /> </CreateItem> <Message Text='DFTA' /> </Target> <Target Name='GAFT' Inputs='{0}' Outputs='{0}' DependsOnTargets='DFTA'> <CreateItem Include='GAFT'> <Output TaskParameter='Include' ItemName='Outs' /> </CreateItem> <Message Text='GAFT' /> </Target> </Project> ", path ); Project p = new Project(XmlReader.Create(new StringReader(content))); p.Build(new string[] { "Build" }, new ILogger[] { logger }); // There should be no duplicates in the list - if there are, then skipped targets are being inferred multiple times logger.AssertLogContains("[GFA;GFT;DFTA;GAFT]"); File.Delete(path); } /// <summary> /// Test empty before targets /// </summary> [Fact] public void TestLegacyCallTarget() { string projectBody = @" <Target Name='Build'> <CallTarget Targets='Foo;Goo'/> </Target> <Target Name='Foo' DependsOnTargets='Foo2'> <FooTarget/> </Target> <Target Name='Goo'> <GooTarget/> </Target> <Target Name='Foo2'> <Foo2Target/> </Target> "; ProjectInstance project = CreateTestProject(projectBody); TargetBuilder builder = (TargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestEntry entry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "Build" }), cache[1]); BuildResult result = builder.BuildTargets(GetProjectLoggingContext(entry), entry, this, entry.Request.Targets.ToArray(), CreateStandardLookup(project), CancellationToken.None).Result; AssertTaskExecutionOrder(new string[] { "CallTarget", "Foo2Target", "FooTarget", "GooTarget" }); } /// <summary> /// BeforeTargets specifies a missing target. Should not warn or error. /// </summary> [Fact] public void TestBeforeTargetsMissing() { string content = @" <Project DefaultTargets='t' xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <Target Name='t' BeforeTargets='x'> <Message Text='[t]' /> </Target> </Project> "; MockLogger log = Helpers.BuildProjectWithNewOMExpectSuccess(content); log.AssertLogContains("[t]"); log.AssertLogDoesntContain("MSB4057"); // missing target log.AssertNoErrors(); log.AssertNoWarnings(); } /// <summary> /// BeforeTargets specifies a missing target. Should not warn or error. /// </summary> [Fact] public void TestBeforeTargetsMissingRunsOthers() { string content = @" <Project DefaultTargets='a;c' xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <Target Name='t' BeforeTargets='a;b;c'> <Message Text='[t]' /> </Target> <Target Name='a'> <Message Text='[a]' /> </Target> <Target Name='c'> <Message Text='[c]' /> </Target> </Project> "; MockLogger log = Helpers.BuildProjectWithNewOMExpectSuccess(content); log.AssertLogContains("[t]", "[a]", "[c]"); log.AssertLogDoesntContain("MSB4057"); // missing target log.AssertNoErrors(); log.AssertNoWarnings(); } /// <summary> /// AfterTargets specifies a missing target. Should not warn or error. /// </summary> [Fact] public void TestAfterTargetsMissing() { string content = @" <Project DefaultTargets='t' xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <Target Name='t' AfterTargets='x'> <Message Text='[t]' /> </Target> </Project> "; MockLogger log = Helpers.BuildProjectWithNewOMExpectSuccess(content); log.AssertLogContains("[t]"); log.AssertLogDoesntContain("MSB4057"); // missing target log.AssertNoErrors(); log.AssertNoWarnings(); } /// <summary> /// AfterTargets specifies a missing target. Should not warn or error. /// </summary> [Fact] public void TestAfterTargetsMissingRunsOthers() { string content = @" <Project DefaultTargets='a;c' xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <Target Name='t' AfterTargets='a;b'> <Message Text='[t]' /> </Target> <Target Name='t2' AfterTargets='b;c'> <Message Text='[t2]' /> </Target> <Target Name='a'> <Message Text='[a]' /> </Target> <Target Name='c'> <Message Text='[c]' /> </Target> </Project> "; MockLogger log = Helpers.BuildProjectWithNewOMExpectSuccess(content); log.AssertLogContains("[a]", "[t]", "[c]", "[t2]"); log.AssertLogDoesntContain("MSB4057"); // missing target log.AssertNoErrors(); log.AssertNoWarnings(); } /// <summary> /// Test empty before targets /// </summary> [Fact] public void TestBeforeTargetsEmpty() { string projectBody = @" <Target Name='Build'> <BuildTask/> </Target> <Target Name='Before' BeforeTargets=''> <BeforeTask/> </Target>"; ProjectInstance project = CreateTestProject(projectBody); TargetBuilder builder = (TargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestEntry entry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "Build" }), cache[1]); BuildResult result = builder.BuildTargets(GetProjectLoggingContext(entry), entry, this, entry.Request.Targets.ToArray(), CreateStandardLookup(project), CancellationToken.None).Result; AssertTaskExecutionOrder(new string[] { "BuildTask" }); } /// <summary> /// Test single before targets /// </summary> [Fact] public void TestBeforeTargetsSingle() { string projectBody = @" <Target Name='Build' Outputs='$(Test)'> <BuildTask/> </Target> <Target Name='Before' BeforeTargets='Build'> <BeforeTask/> </Target>"; ProjectInstance project = CreateTestProject(projectBody); TargetBuilder builder = (TargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestEntry entry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "Build" }), cache[1]); BuildResult result = builder.BuildTargets(GetProjectLoggingContext(entry), entry, this, entry.Request.Targets.ToArray(), CreateStandardLookup(project), CancellationToken.None).Result; AssertTaskExecutionOrder(new string[] { "BeforeTask", "BuildTask" }); } /// <summary> /// Test single before targets on an escaped target /// </summary> [Fact] public void TestBeforeTargetsEscaped() { string projectBody = @" <Target Name='Build;Me' Outputs='$(Test)'> <BuildTask/> </Target> <Target Name='Before' BeforeTargets='Build%3bMe'> <BeforeTask/> </Target>"; ProjectInstance project = CreateTestProject(projectBody); TargetBuilder builder = (TargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestEntry entry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "Build;Me" }), cache[1]); BuildResult result = builder.BuildTargets(GetProjectLoggingContext(entry), entry, this, entry.Request.Targets.ToArray(), CreateStandardLookup(project), CancellationToken.None).Result; AssertTaskExecutionOrder(new string[] { "BeforeTask", "BuildTask" }); } /// <summary> /// Test single before targets /// </summary> [Fact] public void TestBeforeTargetsSingleWithError() { string projectBody = @" <Target Name='Before' BeforeTargets='Build'> <BeforeTask/> </Target> <Target Name='Build'> <BuildTask/> </Target> "; MockTaskBuilder taskBuilder = (MockTaskBuilder)_host.GetComponent(BuildComponentType.TaskBuilder); taskBuilder.FailTaskNumber = 2; // Succeed on BeforeTask, fail on BuildTask ProjectInstance project = CreateTestProject(projectBody); TargetBuilder builder = (TargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestEntry entry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "Build" }), cache[1]); BuildResult result = builder.BuildTargets(GetProjectLoggingContext(entry), entry, this, entry.Request.Targets.ToArray(), CreateStandardLookup(project), CancellationToken.None).Result; AssertTaskExecutionOrder(new string[] { "BeforeTask", "BuildTask" }); } /// <summary> /// Test single before targets /// </summary> [Fact] public void TestBeforeTargetsSingleWithErrorAndParent() { string projectBody = @" <Target Name='Before' BeforeTargets='Build'> <BeforeTask/> </Target> <Target Name='Build'> <BuildTask/> <OnError ExecuteTargets='ErrorTarget'/> </Target> <Target Name='ErrorTarget'> <Error/> </Target> "; MockTaskBuilder taskBuilder = (MockTaskBuilder)_host.GetComponent(BuildComponentType.TaskBuilder); taskBuilder.FailTaskNumber = 2; // Succeed on BeforeTask, fail on BuildTask ProjectInstance project = CreateTestProject(projectBody); TargetBuilder builder = (TargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestEntry entry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "Build" }), cache[1]); BuildResult result = builder.BuildTargets(GetProjectLoggingContext(entry), entry, this, entry.Request.Targets.ToArray(), CreateStandardLookup(project), CancellationToken.None).Result; AssertTaskExecutionOrder(new string[] { "BeforeTask", "BuildTask", "Error" }); } /// <summary> /// Test multiple before targets /// </summary> [Fact] public void TestBeforeTargetsWithTwoReferringToOne() { string projectBody = @" <Target Name='Build' Outputs='$(Test)'> <BuildTask/> </Target> <Target Name='Before' BeforeTargets='Build'> <BeforeTask/> </Target> <Target Name='Before2' BeforeTargets='Build'> <BeforeTask2/> </Target> "; ProjectInstance project = CreateTestProject(projectBody); TargetBuilder builder = (TargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestEntry entry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "Build" }), cache[1]); BuildResult result = builder.BuildTargets(GetProjectLoggingContext(entry), entry, this, entry.Request.Targets.ToArray(), CreateStandardLookup(project), CancellationToken.None).Result; AssertTaskExecutionOrder(new string[] { "BeforeTask", "BeforeTask2", "BuildTask" }); } /// <summary> /// Test multiple before targets /// </summary> [Fact] public void TestBeforeTargetsWithOneReferringToTwo() { string projectBody = @" <Target Name='Build' Outputs='$(Test)'> <BuildTask/> </Target> <Target Name='Foo' Outputs='$(Test)'> <FooTask/> </Target> <Target Name='Before' BeforeTargets='Build;Foo'> <BeforeTask/> </Target> "; ProjectInstance project = CreateTestProject(projectBody); TargetBuilder builder = (TargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestEntry entry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "Foo" }), cache[1]); BuildResult result = builder.BuildTargets(GetProjectLoggingContext(entry), entry, this, entry.Request.Targets.ToArray(), CreateStandardLookup(project), CancellationToken.None).Result; AssertTaskExecutionOrder(new string[] { "BeforeTask", "FooTask" }); } /// <summary> /// Test before target on a skipped target /// </summary> [Fact] public void TestBeforeTargetsSkip() { string projectBody = @" <Target Name='Build' Condition=""'0'=='1'""> <BuildTask/> </Target> <Target Name='Before' BeforeTargets='Build'> <BeforeTask/> </Target>"; ProjectInstance project = CreateTestProject(projectBody); TargetBuilder builder = (TargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestEntry entry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "Build" }), cache[1]); BuildResult result = builder.BuildTargets(GetProjectLoggingContext(entry), entry, this, entry.Request.Targets.ToArray(), CreateStandardLookup(project), CancellationToken.None).Result; AssertTaskExecutionOrder(new string[] { "BeforeTask" }); } /// <summary> /// Test before target on a skipped target /// </summary> [Fact] public void TestBeforeTargetsDependencyOrdering() { string projectBody = @" <Target Name='Build' DependsOnTargets='BuildDep'> <BuildTask/> </Target> <Target Name='Before' DependsOnTargets='BeforeDep' BeforeTargets='Build'> <BeforeTask/> </Target> <Target Name='BuildDep'> <BuildDepTask/> </Target> <Target Name='BeforeDep'> <BeforeDepTask/> </Target> "; ProjectInstance project = CreateTestProject(projectBody); TargetBuilder builder = (TargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestEntry entry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "Build" }), cache[1]); BuildResult result = builder.BuildTargets(GetProjectLoggingContext(entry), entry, this, entry.Request.Targets.ToArray(), CreateStandardLookup(project), CancellationToken.None).Result; AssertTaskExecutionOrder(new string[] { "BuildDepTask", "BeforeDepTask", "BeforeTask", "BuildTask" }); } /// <summary> /// Test after target on a skipped target /// </summary> [Fact] public void TestAfterTargetsEmpty() { string projectBody = @" <Target Name='Build'> <BuildTask/> </Target> <Target Name='After' AfterTargets=''> <AfterTask/> </Target>"; ProjectInstance project = CreateTestProject(projectBody); TargetBuilder builder = (TargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestEntry entry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "Build" }), cache[1]); BuildResult result = builder.BuildTargets(GetProjectLoggingContext(entry), entry, this, entry.Request.Targets.ToArray(), CreateStandardLookup(project), CancellationToken.None).Result; AssertTaskExecutionOrder(new string[] { "BuildTask" }); Assert.False(result.ResultsByTarget["Build"].AfterTargetsHaveFailed); } /// <summary> /// Test after target on a skipped target /// </summary> [Fact] public void TestAfterTargetsSkip() { string projectBody = @" <Target Name='Build' Condition=""'0'=='1'""> <BuildTask/> </Target> <Target Name='After' AfterTargets='Build'> <AfterTask/> </Target>"; ProjectInstance project = CreateTestProject(projectBody); TargetBuilder builder = (TargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestEntry entry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "Build" }), cache[1]); BuildResult result = builder.BuildTargets(GetProjectLoggingContext(entry), entry, this, entry.Request.Targets.ToArray(), CreateStandardLookup(project), CancellationToken.None).Result; AssertTaskExecutionOrder(new string[] { "AfterTask" }); Assert.False(result.ResultsByTarget["Build"].AfterTargetsHaveFailed); } /// <summary> /// Test single before targets /// </summary> [Fact] public void TestAfterTargetsSingleWithError() { string projectBody = @" <Target Name='Build'> <BuildTask/> </Target> <Target Name='After' AfterTargets='Build'> <AfterTask/> </Target>"; MockTaskBuilder taskBuilder = (MockTaskBuilder)_host.GetComponent(BuildComponentType.TaskBuilder); taskBuilder.FailTaskNumber = 1; // Fail on BuildTask ProjectInstance project = CreateTestProject(projectBody); TargetBuilder builder = (TargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestEntry entry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "Build" }), cache[1]); BuildResult result = builder.BuildTargets(GetProjectLoggingContext(entry), entry, this, entry.Request.Targets.ToArray(), CreateStandardLookup(project), CancellationToken.None).Result; AssertTaskExecutionOrder(new string[] { "BuildTask" }); Assert.False(result.ResultsByTarget["Build"].AfterTargetsHaveFailed); } /// <summary> /// Test single before targets /// </summary> [Fact] public void TestAfterTargetsSingleWithErrorAndParent() { string projectBody = @" <Target Name='After' AfterTargets='Build'> <AfterTask/> </Target> <Target Name='Build'> <BuildTask/> <OnError ExecuteTargets='ErrorTarget'/> </Target> <Target Name='ErrorTarget'> <Error/> </Target> <Target Name='ErrorTarget2'> <Error2/> </Target> <Target Name='PostBuild' DependsOnTargets='Build'> <OnError ExecuteTargets='ErrorTarget2'/> </Target> "; MockTaskBuilder taskBuilder = (MockTaskBuilder)_host.GetComponent(BuildComponentType.TaskBuilder); taskBuilder.FailTaskNumber = 2; // Succeed on BuildTask, fail on AfterTask ProjectInstance project = CreateTestProject(projectBody); TargetBuilder builder = (TargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestEntry entry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "PostBuild" }), cache[1]); BuildResult result = builder.BuildTargets(GetProjectLoggingContext(entry), entry, this, entry.Request.Targets.ToArray(), CreateStandardLookup(project), CancellationToken.None).Result; AssertTaskExecutionOrder(new string[] { "BuildTask", "AfterTask", "Error2" }); Assert.False(result.ResultsByTarget["PostBuild"].AfterTargetsHaveFailed); } /// <summary> /// Test after target on a normal target /// </summary> [Fact] public void TestAfterTargetsSingle() { string projectBody = @" <Target Name='Build'> <BuildTask/> </Target> <Target Name='After' AfterTargets='Build'> <AfterTask/> </Target>"; ProjectInstance project = CreateTestProject(projectBody); TargetBuilder builder = (TargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestEntry entry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "Build" }), cache[1]); BuildResult result = builder.BuildTargets(GetProjectLoggingContext(entry), entry, this, entry.Request.Targets.ToArray(), CreateStandardLookup(project), CancellationToken.None).Result; AssertTaskExecutionOrder(new string[] { "BuildTask", "AfterTask" }); Assert.False(result.ResultsByTarget["Build"].AfterTargetsHaveFailed); } /// <summary> /// Test after target on a target name which needs escaping /// </summary> [Fact] public void TestAfterTargetsEscaped() { string projectBody = @" <Target Name='Build;Me'> <BuildTask/> </Target> <Target Name='After' AfterTargets='Build%3bMe'> <AfterTask/> </Target>"; ProjectInstance project = CreateTestProject(projectBody); TargetBuilder builder = (TargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestEntry entry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "Build;Me" }), cache[1]); BuildResult result = builder.BuildTargets(GetProjectLoggingContext(entry), entry, this, entry.Request.Targets.ToArray(), CreateStandardLookup(project), CancellationToken.None).Result; AssertTaskExecutionOrder(new string[] { "BuildTask", "AfterTask" }); Assert.False(result.ResultsByTarget["Build;Me"].AfterTargetsHaveFailed); } /// <summary> /// Test after target on a skipped target /// </summary> [Fact] public void TestAfterTargetsWithTwoReferringToOne() { string projectBody = @" <Target Name='Build'> <BuildTask/> </Target> <Target Name='After' AfterTargets='Build'> <AfterTask/> </Target> <Target Name='After2' AfterTargets='Build'> <AfterTask2/> </Target> "; ProjectInstance project = CreateTestProject(projectBody); TargetBuilder builder = (TargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestEntry entry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "Build" }), cache[1]); BuildResult result = builder.BuildTargets(GetProjectLoggingContext(entry), entry, this, entry.Request.Targets.ToArray(), CreateStandardLookup(project), CancellationToken.None).Result; AssertTaskExecutionOrder(new string[] { "BuildTask", "AfterTask", "AfterTask2" }); Assert.False(result.ResultsByTarget["Build"].AfterTargetsHaveFailed); } /// <summary> /// Test a failing after target /// </summary> [Fact] public void TestAfterTargetsWithFailure() { string projectBody = @" <Target Name='Build'> <BuildTask/> </Target> <Target Name='After' AfterTargets='Build'> <ErrorTask1/> </Target> "; BuildResult result = BuildSimpleProject(projectBody, new string[] { "Build" }, failTaskNumber: 2 /* Fail on After */); result.ResultsByTarget["Build"].ResultCode.ShouldBe(TargetResultCode.Success); result.ResultsByTarget["Build"].AfterTargetsHaveFailed.ShouldBe(true); } /// <summary> /// Test a transitively failing after target /// </summary> [Fact] public void TestAfterTargetsWithTransitiveFailure() { string projectBody = @" <Target Name='Build'> <BuildTask/> </Target> <Target Name='After1' AfterTargets='Build'> <BuildTask/> </Target> <Target Name='After2' AfterTargets='After1'> <ErrorTask1/> </Target> "; BuildResult result = BuildSimpleProject(projectBody, new string[] { "Build" }, failTaskNumber: 3 /* Fail on After2 */); result.ResultsByTarget["Build"].ResultCode.ShouldBe(TargetResultCode.Success); result.ResultsByTarget["Build"].AfterTargetsHaveFailed.ShouldBe(true); } /// <summary> /// Test a project that has a cycle in AfterTargets /// </summary> [Fact] public void TestAfterTargetsWithCycleDoesNotHang() { string projectBody = @" <Target Name='Build' AfterTargets='After2' /> <Target Name='After1' AfterTargets='Build' /> <Target Name='After2' AfterTargets='After1' /> "; BuildResult result = BuildSimpleProject(projectBody, new string[] { "Build" }, failTaskNumber: int.MaxValue /* no task failure needed here */); result.ResultsByTarget["Build"].ResultCode.ShouldBe(TargetResultCode.Success); result.ResultsByTarget["Build"].AfterTargetsHaveFailed.ShouldBe(false); } /// <summary> /// Test after target on a skipped target /// </summary> [Fact] public void TestAfterTargetsWithOneReferringToTwo() { string projectBody = @" <Target Name='Build'> <BuildTask/> </Target> <Target Name='Foo'> <FooTask/> </Target> <Target Name='After' AfterTargets='Build;Foo'> <AfterTask/> </Target> "; ProjectInstance project = CreateTestProject(projectBody); TargetBuilder builder = (TargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestEntry entry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "Foo" }), cache[1]); BuildResult result = builder.BuildTargets(GetProjectLoggingContext(entry), entry, this, entry.Request.Targets.ToArray(), CreateStandardLookup(project), CancellationToken.None).Result; AssertTaskExecutionOrder(new string[] { "FooTask", "AfterTask" }); } /// <summary> /// Test after target on a skipped target /// </summary> [Fact] public void TestAfterTargetsWithDependencyOrdering() { string projectBody = @" <Target Name='Build' DependsOnTargets='BuildDep'> <BuildTask/> </Target> <Target Name='After' DependsOnTargets='AfterDep' AfterTargets='Build'> <AfterTask/> </Target> <Target Name='BuildDep'> <BuildDepTask/> </Target> <Target Name='AfterDep'> <AfterDepTask/> </Target> "; ProjectInstance project = CreateTestProject(projectBody); TargetBuilder builder = (TargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestEntry entry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "Build" }), cache[1]); BuildResult result = builder.BuildTargets(GetProjectLoggingContext(entry), entry, this, entry.Request.Targets.ToArray(), CreateStandardLookup(project), CancellationToken.None).Result; AssertTaskExecutionOrder(new string[] { "BuildDepTask", "BuildTask", "AfterDepTask", "AfterTask" }); } /// <summary> /// Test a complex ordering with depends, before and after targets /// </summary> [Fact] public void TestComplexOrdering() { string projectBody = @" <Target Name='Build' DependsOnTargets='BuildDep'> <BuildTask/> </Target> <Target Name='Before' DependsOnTargets='BeforeDep' BeforeTargets='Build'> <BeforeTask/> </Target> <Target Name='After' DependsOnTargets='AfterDep' AfterTargets='Build'> <AfterTask/> </Target> <Target Name='BuildDep'> <BuildDepTask/> </Target> <Target Name='AfterDep' DependsOnTargets='AfterDepDep'> <AfterDepTask/> </Target> <Target Name='BeforeDep' DependsOnTargets='BeforeDepDep'> <BeforeDepTask/> </Target> <Target Name='BeforeDepDep'> <BeforeDepDepTask/> </Target> <Target Name='AfterDepDep'> <AfterDepDepTask/> </Target> "; ProjectInstance project = CreateTestProject(projectBody); TargetBuilder builder = (TargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestEntry entry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "Build" }), cache[1]); BuildResult result = builder.BuildTargets(GetProjectLoggingContext(entry), entry, this, entry.Request.Targets.ToArray(), CreateStandardLookup(project), CancellationToken.None).Result; AssertTaskExecutionOrder(new string[] { "BuildDepTask", "BeforeDepDepTask", "BeforeDepTask", "BeforeTask", "BuildTask", "AfterDepDepTask", "AfterDepTask", "AfterTask" }); } /// <summary> /// Test a complex ordering with depends, before and after targets /// </summary> [Fact] public void TestComplexOrdering2() { string projectBody = @" <Target Name='BuildDep'> <BuildDepTask/> </Target> <Target Name='BeforeDepDep'> <BeforeDepDepTask/> </Target> <Target Name='BeforeBeforeDep' BeforeTargets='BeforeDep'> <BeforeBeforeDepTask/> </Target> <Target Name='AfterBeforeBeforeDep' AfterTargets='BeforeBeforeDep'> <AfterBeforeBeforeDepTask/> </Target> <Target Name='BeforeDep' DependsOnTargets='BeforeDepDep'> <BeforeDepTask/> </Target> <Target Name='Before' DependsOnTargets='BeforeDep' BeforeTargets='Build'> <BeforeTask/> </Target> <Target Name='AfterBeforeDepDep'> <AfterBeforeDepDepTask/> </Target> <Target Name='AfterBeforeDep' DependsOnTargets='AfterBeforeDepDep'> <AfterBeforeDepTask/> </Target> <Target Name='AfterBefore' DependsOnTargets='AfterBeforeDep' AfterTargets='Before'> <AfterBeforeTask/> </Target> <Target Name='Build' DependsOnTargets='BuildDep'> <BuildTask/> </Target> "; ProjectInstance project = CreateTestProject(projectBody); TargetBuilder builder = (TargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestEntry entry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "Build" }), cache[1]); BuildResult result = builder.BuildTargets(GetProjectLoggingContext(entry), entry, this, entry.Request.Targets.ToArray(), CreateStandardLookup(project), CancellationToken.None).Result; AssertTaskExecutionOrder(new string[] { "BuildDepTask", "BeforeDepDepTask", "BeforeBeforeDepTask", "AfterBeforeBeforeDepTask", "BeforeDepTask", "BeforeTask", "AfterBeforeDepDepTask", "AfterBeforeDepTask", "AfterBeforeTask", "BuildTask" }); } /// <summary> /// Test a complex ordering with depends, before and after targets /// </summary> [Fact] public void TestBeforeAndAfterWithErrorTargets() { string projectBody = @" <Target Name='Build' > <BuildTask/> <OnError ExecuteTargets='ErrorTarget'/> </Target> <Target Name='ErrorTarget'> <ErrorTargetTask/> </Target> <Target Name='BeforeErrorTarget' BeforeTargets='ErrorTarget'> <BeforeErrorTargetTask/> </Target> <Target Name='AfterErrorTarget' AfterTargets='ErrorTarget'> <AfterErrorTargetTask/> </Target> "; MockTaskBuilder taskBuilder = (MockTaskBuilder)_host.GetComponent(BuildComponentType.TaskBuilder); taskBuilder.FailTaskNumber = 1; // Fail on BuildTask ProjectInstance project = CreateTestProject(projectBody); TargetBuilder builder = (TargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestEntry entry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "Build" }), cache[1]); BuildResult result = builder.BuildTargets(GetProjectLoggingContext(entry), entry, this, entry.Request.Targets.ToArray(), CreateStandardLookup(project), CancellationToken.None).Result; AssertTaskExecutionOrder(new string[] { "BuildTask", "BeforeErrorTargetTask", "ErrorTargetTask", "AfterErrorTargetTask" }); Assert.False(result.ResultsByTarget["Build"].AfterTargetsHaveFailed); } /// <summary> /// Test after target on a skipped target /// </summary> [Fact] public void TestBeforeAndAfterOverrides() { string projectBody = @" <Target Name='BuildDep'> <BuildDepTask/> </Target> <Target Name='Build' DependsOnTargets='BuildDep'> <BuildTask/> </Target> <Target Name='After' AfterTargets='Build'> <AfterTask/> </Target> <Target Name='After' AfterTargets='BuildDep'> <AfterTask/> </Target> <Target Name='Before' BeforeTargets='Build'> <BeforeTask/> </Target> <Target Name='Before' BeforeTargets='BuildDep'> <BeforeTask/> </Target> "; ProjectInstance project = CreateTestProject(projectBody); TargetBuilder builder = (TargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestEntry entry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "Build" }), cache[1]); BuildResult result = builder.BuildTargets(GetProjectLoggingContext(entry), entry, this, entry.Request.Targets.ToArray(), CreateStandardLookup(project), CancellationToken.None).Result; AssertTaskExecutionOrder(new string[] { "BeforeTask", "BuildDepTask", "AfterTask", "BuildTask" }); } /// <summary> /// Test that if before and after targets skip, the main target still runs (bug 476908) /// </summary> [Fact] public void TestSkippingBeforeAndAfterTargets() { string projectBody = @" <Target Name='Build'> <BuildTask/> </Target> <Target Name='Before' BeforeTargets='Build' Condition=""'0'=='1'""> <BeforeTask/> </Target> <Target Name='After' AfterTargets='Build' Condition=""'0'=='1'""> <AfterTask/> </Target> "; ProjectInstance project = CreateTestProject(projectBody); TargetBuilder builder = (TargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestEntry entry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "Build" }), cache[1]); BuildResult result = builder.BuildTargets(GetProjectLoggingContext(entry), entry, this, entry.Request.Targets.ToArray(), CreateStandardLookup(project), CancellationToken.None).Result; AssertTaskExecutionOrder(new string[] { "BuildTask" }); } /// <summary> /// Tests that a circular dependency within a CallTarget call correctly propagates the failure. Bug 502570. /// </summary> [Fact] public void TestCircularDependencyInCallTarget() { string projectContents = @" <Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <Target Name=""t1""> <CallTarget Targets=""t3""/> </Target> <Target Name=""t2"" DependsOnTargets=""t1""> </Target> <Target Name=""t3"" DependsOnTargets=""t2""> </Target> </Project> "; StringReader reader = new StringReader(projectContents); Project project = new Project(new XmlTextReader(reader), null, null); bool success = project.Build(_mockLogger); Assert.False(success); } /// <summary> /// Tests that cancel with no entries after building does not fail. /// </summary> [Fact] public void TestCancelWithNoEntriesAfterBuild() { string projectBody = @" <Target Name='Build'> <BuildTask/> </Target> "; ProjectInstance project = CreateTestProject(projectBody); TargetBuilder builder = (TargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestEntry entry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "Build" }), cache[1]); using (CancellationTokenSource source = new CancellationTokenSource()) { BuildResult result = builder.BuildTargets(GetProjectLoggingContext(entry), entry, this, entry.Request.Targets.ToArray(), CreateStandardLookup(project), source.Token).Result; AssertTaskExecutionOrder(new string[] { "BuildTask" }); // This simply should not fail. source.Cancel(); } } [Fact] public void SkippedTargetWithFailedDependenciesStopsBuild() { string projectContents = @" <Target Name=""Build"" DependsOnTargets=""ProduceError1;ProduceError2"" /> <Target Name=""ProduceError1"" Condition=""false"" /> <Target Name=""ProduceError2""> <ErrorTask2 /> </Target> <Target Name=""_Error1"" BeforeTargets=""ProduceError1""> <ErrorTask1 /> </Target> "; var project = CreateTestProject(projectContents, string.Empty, "Build"); TargetBuilder builder = (TargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); MockTaskBuilder taskBuilder = (MockTaskBuilder)_host.GetComponent(BuildComponentType.TaskBuilder); // Fail the first task taskBuilder.FailTaskNumber = 1; IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestEntry entry = new BuildRequestEntry(CreateNewBuildRequest(1, new[] { "Build" }), cache[1]); var buildResult = builder.BuildTargets(GetProjectLoggingContext(entry), entry, this, entry.Request.Targets.ToArray(), CreateStandardLookup(project), CancellationToken.None).Result; IResultsCache resultsCache = (IResultsCache)_host.GetComponent(BuildComponentType.ResultsCache); Assert.True(resultsCache.GetResultForRequest(entry.Request).HasResultsForTarget("Build")); Assert.True(resultsCache.GetResultForRequest(entry.Request).HasResultsForTarget("ProduceError1")); Assert.False(resultsCache.GetResultForRequest(entry.Request).HasResultsForTarget("ProduceError2")); Assert.True(resultsCache.GetResultForRequest(entry.Request).HasResultsForTarget("_Error1")); Assert.Equal(TargetResultCode.Failure, resultsCache.GetResultForRequest(entry.Request)["Build"].ResultCode); Assert.Equal(TargetResultCode.Skipped, resultsCache.GetResultForRequest(entry.Request)["ProduceError1"].ResultCode); Assert.Equal(TargetResultCode.Failure, resultsCache.GetResultForRequest(entry.Request)["_Error1"].ResultCode); } [Fact] public void SkipNonexistentTargetsDoesNotExecuteOrCacheTargetResult() { string projectContents = @"<Target Name=""Build"" />"; var project = CreateTestProject(projectContents, string.Empty, "Build"); TargetBuilder builder = (TargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); MockTaskBuilder taskBuilder = (MockTaskBuilder)_host.GetComponent(BuildComponentType.TaskBuilder); taskBuilder.FailTaskNumber = 1; IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestEntry entry = new BuildRequestEntry(CreateNewBuildRequest(1, new[] { "NotFound" }, BuildRequestDataFlags.SkipNonexistentTargets), cache[1]); var buildResult = builder.BuildTargets(GetProjectLoggingContext(entry), entry, this, entry.Request.Targets.ToArray(), CreateStandardLookup(project), CancellationToken.None).Result; IResultsCache resultsCache = (IResultsCache)_host.GetComponent(BuildComponentType.ResultsCache); // This should throw because the results cache should not contain the results for the target that was not // executed. This is different than when a target is skipped due to condition not met where the result // would be in the cache. In this case we can't cache the result because it is only valid for the single // request. Assert.Throws<InternalErrorException>(() => resultsCache.GetResultForRequest(entry.Request)); } #region IRequestBuilderCallback Members /// <summary> /// We have to have this interface, but it won't be used in this test because we aren't doing MSBuild callbacks. /// </summary> /// <param name="projectFiles">N/A</param> /// <param name="properties">N/A</param> /// <param name="toolsVersions">N/A</param> /// <param name="targets">N/A</param> /// <param name="waitForResults">N/A</param> /// <param name="skipNonexistentTargets">N/A</param> /// <returns>N/A</returns> Task<BuildResult[]> IRequestBuilderCallback.BuildProjects(string[] projectFiles, PropertyDictionary<ProjectPropertyInstance>[] properties, string[] toolsVersions, string[] targets, bool waitForResults, bool skipNonexistentTargets) { throw new NotImplementedException(); } /// <summary> /// Not implemented /// </summary> Task IRequestBuilderCallback.BlockOnTargetInProgress(int blockingRequestId, string blockingTarget, BuildResult partialBuildResult) { throw new NotImplementedException(); } /// <summary> /// Empty impl /// </summary> void IRequestBuilderCallback.Yield() { } /// <summary> /// Empty impl /// </summary> void IRequestBuilderCallback.Reacquire() { } /// <summary> /// Empty impl /// </summary> void IRequestBuilderCallback.EnterMSBuildCallbackState() { } /// <summary> /// Empty impl /// </summary> void IRequestBuilderCallback.ExitMSBuildCallbackState() { } #endregion /// <summary> /// Verifies the order in which tasks executed. /// </summary> private void AssertTaskExecutionOrder(string[] tasks) { MockTaskBuilder mockBuilder = (MockTaskBuilder)_host.GetComponent(BuildComponentType.TaskBuilder); Assert.Equal(tasks.Length, mockBuilder.ExecutedTasks.Count); int currentTask = 0; foreach (ProjectTaskInstance task in mockBuilder.ExecutedTasks) { Assert.Equal(task.Name, tasks[currentTask]); currentTask++; } } /// <summary> /// Creates a new build request /// </summary> private BuildRequest CreateNewBuildRequest(int configurationId, string[] targets, BuildRequestDataFlags flags = BuildRequestDataFlags.None) { return new BuildRequest(1 /* submissionId */, _nodeRequestId++, configurationId, targets, null, BuildEventContext.Invalid, null, flags); } /// <summary> /// Creates a 'Lookup' used to deal with projects. /// </summary> /// <param name="project">The project for which to create the lookup</param> /// <returns>The lookup</returns> private Lookup CreateStandardLookup(ProjectInstance project) { Lookup lookup = new Lookup(new ItemDictionary<ProjectItemInstance>(project.Items), new PropertyDictionary<ProjectPropertyInstance>(project.Properties)); return lookup; } /// <summary> /// Creates a test project. /// </summary> /// <returns>The project.</returns> private ProjectInstance CreateTestProject() { string projectBodyContents = @" <ItemGroup> <Compile Include='b.cs' /> <Compile Include='c.cs' /> </ItemGroup> <ItemGroup> <Reference Include='System' /> </ItemGroup> <Target Name='Empty' /> <Target Name='Skip' Inputs='testProject.proj' Outputs='testProject.proj' /> <Target Name='SkipCondition' Condition=""'true' == 'false'"" /> <Target Name='Error' > <ErrorTask1 ContinueOnError='True'/> <ErrorTask2 ContinueOnError='False'/> <ErrorTask3 /> <OnError ExecuteTargets='Foo'/> <OnError ExecuteTargets='Bar'/> </Target> <Target Name='DepError' DependsOnTargets='Foo;Skip;Error;Baz2'> <OnError ExecuteTargets='Baz'/> </Target> <Target Name='Foo' Inputs='foo.cpp' Outputs='foo.o'> <FooTask1/> </Target> <Target Name='Bar'> <BarTask1/> </Target> <Target Name='Baz' DependsOnTargets='Bar'> <BazTask1/> <BazTask2/> </Target> <Target Name='Baz2' DependsOnTargets='Bar;Foo'> <Baz2Task1/> <Baz2Task2/> <Baz2Task3/> </Target> <Target Name='DepSkip' DependsOnTargets='SkipCondition'> <DepSkipTask1/> <DepSkipTask2/> <DepSkipTask3/> </Target> <Target Name='DepSkip2' DependsOnTargets='Skip' Inputs='testProject.proj' Outputs='testProject.proj'> <DepSkipTask1/> <DepSkipTask2/> <DepSkipTask3/> </Target> "; return CreateTestProject(projectBodyContents); } /// <summary> /// Creates a test project. /// </summary> private ProjectInstance CreateTestProject(string projectBodyContents) { return CreateTestProject(projectBodyContents, String.Empty, String.Empty); } /// <summary> /// Creates a test project. /// </summary> private ProjectInstance CreateTestProject(string projectBodyContents, string initialTargets, string defaultTargets) { string projectFileContents = String.Format("<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='http://schemas.microsoft.com/developer/msbuild/2003' InitialTargets='{0}' DefaultTargets='{1}'>{2}</Project>", initialTargets, defaultTargets, projectBodyContents); // retries to deal with occasional locking issues where the file can't be written to initially for (int retries = 0; retries < 5; retries++) { try { File.Create("testProject.proj").Dispose(); break; } catch (Exception ex) { if (retries < 4) { Console.WriteLine(ex.ToString()); } else { // All the retries have failed. We will now fail with the // actual problem now instead of with some more difficult-to-understand // issue later. throw; } } } IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestConfiguration config = new BuildRequestConfiguration(1, new BuildRequestData("testFile", new Dictionary<string, string>(), "3.5", new string[0], null), "2.0"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); config.Project = project.CreateProjectInstance(); cache.AddConfiguration(config); return config.Project; } /// <summary> /// Creates a project logging context. /// </summary> /// <param name="entry">The entry on which to base the logging context.</param> /// <returns>The context</returns> private ProjectLoggingContext GetProjectLoggingContext(BuildRequestEntry entry) { return new ProjectLoggingContext(new NodeLoggingContext(_host, 1, false), entry, null); } /// <summary> /// Builds a project using TargetBuilder and returns the result. /// </summary> /// <param name="projectBody">The project contents.</param> /// <param name="targets">The targets to build.</param> /// <param name="failTaskNumber">The task ordinal to fail on.</param> /// <returns>The result of building the specified project/tasks.</returns> private BuildResult BuildSimpleProject(string projectBody, string[] targets, int failTaskNumber) { ProjectInstance project = CreateTestProject(projectBody); MockTaskBuilder taskBuilder = (MockTaskBuilder)_host.GetComponent(BuildComponentType.TaskBuilder); taskBuilder.FailTaskNumber = failTaskNumber; TargetBuilder builder = (TargetBuilder)_host.GetComponent(BuildComponentType.TargetBuilder); IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestEntry entry = new BuildRequestEntry(CreateNewBuildRequest(1, targets), cache[1]); return builder.BuildTargets(GetProjectLoggingContext(entry), entry, this, entry.Request.Targets.ToArray(), CreateStandardLookup(project), CancellationToken.None).Result; } /// <summary> /// The mock component host object. /// </summary> private class MockHost : MockLoggingService, IBuildComponentHost, IBuildComponent { #region IBuildComponentHost Members /// <summary> /// The config cache /// </summary> private IConfigCache _configCache; /// <summary> /// The logging service /// </summary> private ILoggingService _loggingService; /// <summary> /// The results cache /// </summary> private IResultsCache _resultsCache; /// <summary> /// The request builder /// </summary> private IRequestBuilder _requestBuilder; /// <summary> /// The mock task builder /// </summary> private ITaskBuilder _taskBuilder; /// <summary> /// The target builder /// </summary> private ITargetBuilder _targetBuilder; /// <summary> /// The build parameters /// </summary> private BuildParameters _buildParameters; /// <summary> /// Retrieves the LegacyThreadingData associated with a particular component host /// </summary> private LegacyThreadingData _legacyThreadingData; private ISdkResolverService _sdkResolverService; /// <summary> /// Constructor /// </summary> public MockHost() { _buildParameters = new BuildParameters(); _legacyThreadingData = new LegacyThreadingData(); _configCache = new ConfigCache(); ((IBuildComponent)_configCache).InitializeComponent(this); _loggingService = this; _resultsCache = new ResultsCache(); ((IBuildComponent)_resultsCache).InitializeComponent(this); _requestBuilder = new RequestBuilder(); ((IBuildComponent)_requestBuilder).InitializeComponent(this); _taskBuilder = new MockTaskBuilder(); ((IBuildComponent)_taskBuilder).InitializeComponent(this); _targetBuilder = new TargetBuilder(); ((IBuildComponent)_targetBuilder).InitializeComponent(this); _sdkResolverService = new MockSdkResolverService(); ((IBuildComponent)_sdkResolverService).InitializeComponent(this); } /// <summary> /// Returns the node logging service. We don't distinguish here. /// </summary> /// <returns>The logging service.</returns> public ILoggingService LoggingService { get { return _loggingService; } } /// <summary> /// Retrieves the LegacyThreadingData associated with a particular component host /// </summary> LegacyThreadingData IBuildComponentHost.LegacyThreadingData { get { return _legacyThreadingData; } } /// <summary> /// Retrieves the name of the host. /// </summary> public string Name { get { return "TargetBuilder_Tests.MockHost"; } } /// <summary> /// Returns the build parameters. /// </summary> public BuildParameters BuildParameters { get { return _buildParameters; } } /// <summary> /// Constructs and returns a component of the specified type. /// </summary> /// <param name="type">The type of component to return</param> /// <returns>The component</returns> public IBuildComponent GetComponent(BuildComponentType type) { return type switch { BuildComponentType.ConfigCache => (IBuildComponent)_configCache, BuildComponentType.LoggingService => (IBuildComponent)_loggingService, BuildComponentType.ResultsCache => (IBuildComponent)_resultsCache, BuildComponentType.RequestBuilder => (IBuildComponent)_requestBuilder, BuildComponentType.TaskBuilder => (IBuildComponent)_taskBuilder, BuildComponentType.TargetBuilder => (IBuildComponent)_targetBuilder, BuildComponentType.SdkResolverService => (IBuildComponent)_sdkResolverService, _ => throw new ArgumentException("Unexpected type " + type), }; } /// <summary> /// Registers a component factory /// </summary> public void RegisterFactory(BuildComponentType type, BuildComponentFactoryDelegate factory) { } #endregion #region IBuildComponent Members /// <summary> /// Sets the component host /// </summary> /// <param name="host">The component host</param> public void InitializeComponent(IBuildComponentHost host) { throw new NotImplementedException(); } /// <summary> /// Shuts down the component /// </summary> public void ShutdownComponent() { throw new NotImplementedException(); } #endregion } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Threading; using Newtonsoft.Json.Linq; namespace esquery { class CommandProcessor { static string GetFirst(string s) { if (string.IsNullOrEmpty(s)) return null; var next = s.IndexOf(char.IsWhiteSpace); if (next < 0) return null; return s.Substring(0, next); } static List<string> EatFirstN(int n, string s) { var ret = new List<string>(); var current = 0; for (int i = 0; i < n;i++) { var next = s.IndexOfAfter(current, char.IsWhiteSpace); if(next < 0) { return null; } ret.Add(s.Substring(current, next - current)); current = next + 1; } //get whatever else is on the line. ret.Add(s.Substring(current, s.Length - current)); return ret; } public static object Process(string command, State state) { var c = GetFirst(command); if (c == null) return new HelpCommandResult(); try { switch (c) { case "a": case "append": var append = EatFirstN(3, command); if (append.Count != 4) return new InvalidCommandResult(command); return Append(state.Args.BaseUri, append[1], append[2], append[3]); case "h": case "help": return new HelpCommandResult(); case "q": case "query": var query = EatFirstN(1, command); if (query.Count != 2) return new InvalidCommandResult(command); return CreateAndRunQuery(state.Args.BaseUri, query[1], state.Args.Credentials, state.Piped); case "s": case "subscribe": var sub = EatFirstN(2, command); if (sub.Count != 3) return new InvalidCommandResult(command); return Subscribe(state.Args.BaseUri, sub[1], state.Args.Credentials, state.Piped); default: return new InvalidCommandResult(command); } } catch(Exception ex) { return new ExceptionResult(command, ex); } } private static Uri PostQuery(Uri baseUri, string query, NetworkCredential credential) { var request = WebRequest.Create(baseUri.AbsoluteUri +"projections/transient?enabled=yes"); request.Method = "POST"; request.ContentType = "application/json"; request.ContentLength = query.Length; //TODO take from args request.Credentials = credential; using (var sw = new StreamWriter(request.GetRequestStream())) { sw.Write(query); } using (var response = (HttpWebResponse)request.GetResponse()) { var s = new StreamReader(response.GetResponseStream()).ReadToEnd(); if(response.StatusCode != HttpStatusCode.Created) { throw new Exception("Query Failed with Status Code: " + response.StatusCode + "\n" + s); } return new Uri(response.Headers["Location"]); } } private static QueryInformation CheckQueryStatus(Uri toCheck, NetworkCredential credential) { var request = (HttpWebRequest) WebRequest.Create(toCheck); request.Method = "GET"; request.Accept = "application/json"; //TODO take from args request.Credentials = credential; using (var response = (HttpWebResponse)request.GetResponse()) { var s = new StreamReader(response.GetResponseStream()).ReadToEnd(); JObject json = JObject.Parse(s); if (response.StatusCode != HttpStatusCode.OK) { throw new Exception("Query Polling Failed with Status Code: " + response.StatusCode + "\n" + s); } var faulted = json["status"].Value<string>().StartsWith( "Faulted"); var completed = json["status"].Value<string>().StartsWith("Completed"); var faultReason = json["stateReason"].Value<string>(); var streamurl = json["resultStreamUrl"]; var cancelurl = json["disableCommandUrl"]; Uri resulturi = null; if(streamurl != null) resulturi = new Uri(streamurl.Value<string>()); Uri canceluri = null; if(cancelurl != null) canceluri = new Uri(cancelurl.Value<string>()); var progress = json["progress"].Value<decimal>(); return new QueryInformation() { Faulted = faulted, FaultReason = faultReason, ResultUri = resulturi, Progress=progress, Completed=completed, CancelUri = canceluri }; } } private static Uri GetNamedLink(JObject feed, string name) { var links = feed["links"]; if (links == null) return null; return (from item in links where item["relation"].Value<string>() == name select new Uri(item["uri"].Value<string>())).FirstOrDefault(); } private static Uri GetLast(Uri head, NetworkCredential credential) { var request = (HttpWebRequest)WebRequest.Create(head); request.Credentials = credential; request.Accept = "application/vnd.eventstore.atom+json"; using (var response = (HttpWebResponse)request.GetResponse()) { var json = JObject.Parse(new StreamReader(response.GetResponseStream()).ReadToEnd()); var last = GetNamedLink(json, "last"); return last ?? GetNamedLink(json, "self"); } } private static Uri GetPrevFromHead(Uri head, NetworkCredential credential) { var request = (HttpWebRequest)WebRequest.Create(head); request.Credentials = credential; request.Accept = "application/vnd.eventstore.atom+json"; using (var response = (HttpWebResponse)request.GetResponse()) { var json = JObject.Parse(new StreamReader(response.GetResponseStream()).ReadToEnd()); return GetNamedLink(json, "previous"); } } static Uri ReadResults(Uri uri, NetworkCredential credential) { var request = (HttpWebRequest) WebRequest.Create(new Uri(uri.AbsoluteUri + "?embed=body")); request.Credentials = credential; request.Accept = "application/vnd.eventstore.atom+json"; request.Headers.Add("ES-LongPoll", "1"); //add long polling using (var response = request.GetResponse()) { var json = JObject.Parse(new StreamReader(response.GetResponseStream()).ReadToEnd()); if (json["entries"] != null) { foreach (var item in json["entries"]) { Console.WriteLine(item["title"].ToString()); if (item["data"] != null) { Console.WriteLine(item["data"].ToString()); } else { Console.WriteLine(GetData(item, credential)); } } return GetNamedLink(json, "previous") ?? uri; } } return uri; } private static string GetData(JToken item, NetworkCredential credential) { var links = item["links"]; if (links == null) return "unable to get link."; foreach(var c in links) { var rel = c["relation"]; if (rel == null) continue; var r = rel.Value<string>(); if (r.ToLower() == "alternate") { var request = (HttpWebRequest) WebRequest.Create(new Uri(c["uri"].Value<string>())); request.Credentials = credential; request.Accept = "application/json"; using (var response = request.GetResponse()) { return new StreamReader(response.GetResponseStream()).ReadToEnd(); } } } return "relation link not found"; } private static object CreateAndRunQuery(Uri baseUri, string query, NetworkCredential credential, bool piped) { try { var watch = new Stopwatch(); watch.Start(); var toCheck = PostQuery(baseUri, query, credential); var queryInformation = new QueryInformation(); if(!piped) Console.WriteLine("Query started. Press esc to cancel."); while (!queryInformation.Completed) { queryInformation = CheckQueryStatus(toCheck, credential); if (queryInformation.Faulted) { throw new Exception("Query Faulted.\n" + queryInformation.FaultReason); } Console.Write("\r{0}", queryInformation.Progress.ToString("f2") + "%"); if (!piped && Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape) { Console.WriteLine("\nCancelling query."); Cancel(queryInformation); return new QueryCancelledResult(); } Thread.Sleep(500); } Console.WriteLine("\rQuery Completed in: " + watch.Elapsed); var last = GetLast(queryInformation.ResultUri, credential); last = new Uri(last.OriginalString + "?embed=body"); var next = ReadResults(last, credential); return new QueryResult() {Query = query}; } catch(Exception ex) { return new ErrorResult(ex); } } private static object Subscribe(Uri baseUri, string stream, NetworkCredential credential, bool piped) { try { var previous = GetPrevFromHead(new Uri(baseUri.AbsoluteUri + "streams/" + stream + "?embed=body"), credential); if (!piped) Console.WriteLine("Beginning Subscription. Press esc to cancel."); var uri = previous; while (true) { uri = ReadResults(uri, credential); if (!piped && Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape) { Console.WriteLine("\nCancelling query."); return new SubscriptionCancelledResult(); } } } catch(Exception ex) { return new ErrorResult(ex); } } private static void Cancel(QueryInformation queryInformation) { if (queryInformation.CancelUri == null) return; var request = WebRequest.Create(queryInformation.CancelUri); request.Method = "POST"; request.ContentLength = 0; using (var response = (HttpWebResponse)request.GetResponse()) {} } private static AppendResult Append(Uri baseUri, string stream, string eventType, string data) { var message = "[{'eventType':'" + eventType + "', 'eventId' :'" + Guid.NewGuid() + "', 'data' : " + data +"}]"; var request = WebRequest.Create(baseUri.AbsoluteUri + "streams/" + stream); request.Method = "POST"; request.ContentType = "application/json"; request.ContentLength = message.Length; using (var sw = new StreamWriter(request.GetRequestStream())) { sw.Write(message); } using (var response = (HttpWebResponse) request.GetResponse()) { return new AppendResult() {StatusCode = response.StatusCode}; } } private class AppendResult { public HttpStatusCode StatusCode; public override string ToString() { if (StatusCode == HttpStatusCode.Created) { return "Succeeded."; } return StatusCode.ToString(); } } private class QueryResult { public string Query; public override string ToString() { return "Query Completed"; } } } class ExceptionResult { private readonly string _command; private readonly Exception _exception; public ExceptionResult(string command, Exception exception) { _command = command; _exception = exception; } public override string ToString() { return "Command " + _command + " failed \n" + _exception.ToString(); } } class SubscriptionCancelledResult { public override string ToString() { return "Subscription Cancelled"; } } class QueryCancelledResult { public override string ToString() { return "Query Cancelled"; } } class QueryInformation { public bool Faulted; public string FaultReason; public decimal Progress; public Uri ResultUri; public bool Completed; public Uri CancelUri; } class ErrorResult { private Exception _exception; public ErrorResult(Exception exception) { _exception = exception; } public override string ToString() { return "An error has occured\n" + _exception.Message; } } class HelpCommandResult { public override string ToString() { return "esquery help:\n" + "\th/help: prints help\n" + "\tq/query {js query} executes a query.\n" + "\ta/append {stream} {js object}: appends to a stream.\n" + "\ts/subscribe {stream}: subscribes to a stream.\n"; } } class InvalidCommandResult { private string _command; public InvalidCommandResult(string command) { _command = command; } public override string ToString() { return "Invalid command: '" + _command + "'"; } } static class IEnumerableExtensions { public static int IndexOf<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) { int i = 0; foreach (var element in source) { if (predicate(element)) return i; i++; } return i; } public static int IndexOfAfter<TSource>(this IEnumerable<TSource> source, int start, Func<TSource, bool> predicate) { int i = 0; foreach (var element in source) { if (predicate(element) && i >= start) return i; i++; } return i; } } }
using System; using System.Collections.Generic; using ClosedXML.Utils; namespace ClosedXML.Excel { internal class XLConditionalFormat : IXLConditionalFormat, IXLStylized { public XLConditionalFormat(XLRange range, Boolean copyDefaultModify = false) { Id = Guid.NewGuid(); Range = range; Style = new XLStyle(this, range.Worksheet.Style); Values = new XLDictionary<XLFormula>(); Colors = new XLDictionary<XLColor>(); ContentTypes = new XLDictionary<XLCFContentType>(); IconSetOperators = new XLDictionary<XLCFIconSetOperator>(); CopyDefaultModify = copyDefaultModify; } public XLConditionalFormat(XLConditionalFormat conditionalFormat) { Id = Guid.NewGuid(); Range = conditionalFormat.Range; Style = new XLStyle(this, conditionalFormat.Style); Values = new XLDictionary<XLFormula>(conditionalFormat.Values); Colors = new XLDictionary<XLColor>(conditionalFormat.Colors); ContentTypes = new XLDictionary<XLCFContentType>(conditionalFormat.ContentTypes); IconSetOperators = new XLDictionary<XLCFIconSetOperator>(conditionalFormat.IconSetOperators); ConditionalFormatType = conditionalFormat.ConditionalFormatType; TimePeriod = conditionalFormat.TimePeriod; IconSetStyle = conditionalFormat.IconSetStyle; Operator = conditionalFormat.Operator; Bottom = conditionalFormat.Bottom; Percent = conditionalFormat.Percent; ReverseIconOrder = conditionalFormat.ReverseIconOrder; ShowIconOnly = conditionalFormat.ShowIconOnly; ShowBarOnly = conditionalFormat.ShowBarOnly; StopIfTrueInternal = OpenXmlHelper.GetBooleanValueAsBool(conditionalFormat.StopIfTrueInternal, true); } public Guid Id { get; internal set; } public Boolean CopyDefaultModify { get; set; } private IXLStyle _style; private Int32 _styleCacheId; public IXLStyle Style { get { return GetStyle(); } set { SetStyle(value); } } private IXLStyle GetStyle() { //return _style; if (_style != null) return _style; return _style = new XLStyle(this, Range.Worksheet.Workbook.GetStyleById(_styleCacheId), CopyDefaultModify); } private void SetStyle(IXLStyle styleToUse) { //_style = new XLStyle(this, styleToUse); _styleCacheId = Range.Worksheet.Workbook.GetStyleId(styleToUse); _style = null; StyleChanged = false; } public IEnumerable<IXLStyle> Styles { get { UpdatingStyle = true; yield return Style; UpdatingStyle = false; } } public bool UpdatingStyle { get; set; } public IXLStyle InnerStyle { get; set; } public IXLRanges RangesUsed { get { return new XLRanges(); } } public bool StyleChanged { get; set; } public XLDictionary<XLFormula> Values { get; private set; } public XLDictionary<XLColor> Colors { get; private set; } public XLDictionary<XLCFContentType> ContentTypes { get; private set; } public XLDictionary<XLCFIconSetOperator> IconSetOperators { get; private set; } public IXLRange Range { get; set; } public XLConditionalFormatType ConditionalFormatType { get; set; } public XLTimePeriod TimePeriod { get; set; } public XLIconSetStyle IconSetStyle { get; set; } public XLCFOperator Operator { get; set; } public Boolean Bottom { get; set; } public Boolean Percent { get; set; } public Boolean ReverseIconOrder { get; set; } public Boolean ShowIconOnly { get; set; } public Boolean ShowBarOnly { get; set; } internal bool StopIfTrueInternal { get; set; } public IXLConditionalFormat StopIfTrue(bool value = true) { StopIfTrueInternal = value; return this; } public void CopyFrom(IXLConditionalFormat other) { Style = other.Style; ConditionalFormatType = other.ConditionalFormatType; TimePeriod = other.TimePeriod; IconSetStyle = other.IconSetStyle; Operator = other.Operator; Bottom = other.Bottom; Percent = other.Percent; ReverseIconOrder = other.ReverseIconOrder; ShowIconOnly = other.ShowIconOnly; ShowBarOnly = other.ShowBarOnly; StopIfTrueInternal = ((XLConditionalFormat)other).StopIfTrueInternal; Values.Clear(); other.Values.ForEach(kp => Values.Add(kp.Key, new XLFormula(kp.Value))); //CopyDictionary(Values, other.Values); CopyDictionary(Colors, other.Colors); CopyDictionary(ContentTypes, other.ContentTypes); CopyDictionary(IconSetOperators, other.IconSetOperators); } private void CopyDictionary<T>(XLDictionary<T> target, XLDictionary<T> source) { target.Clear(); source.ForEach(kp => target.Add(kp.Key, kp.Value)); } public IXLStyle WhenIsBlank() { ConditionalFormatType = XLConditionalFormatType.IsBlank; return Style; } public IXLStyle WhenNotBlank() { ConditionalFormatType = XLConditionalFormatType.NotBlank; return Style; } public IXLStyle WhenIsError() { ConditionalFormatType = XLConditionalFormatType.IsError; return Style; } public IXLStyle WhenNotError() { ConditionalFormatType = XLConditionalFormatType.NotError; return Style; } public IXLStyle WhenDateIs(XLTimePeriod timePeriod) { TimePeriod = timePeriod; ConditionalFormatType = XLConditionalFormatType.TimePeriod; return Style; } public IXLStyle WhenContains(String value) { Values.Initialize(new XLFormula { Value = value }); ConditionalFormatType = XLConditionalFormatType.ContainsText; Operator = XLCFOperator.Contains; return Style; } public IXLStyle WhenNotContains(String value) { Values.Initialize(new XLFormula { Value = value }); ConditionalFormatType = XLConditionalFormatType.NotContainsText; Operator = XLCFOperator.NotContains; return Style; } public IXLStyle WhenStartsWith(String value) { Values.Initialize(new XLFormula { Value = value }); ConditionalFormatType = XLConditionalFormatType.StartsWith; Operator = XLCFOperator.StartsWith; return Style; } public IXLStyle WhenEndsWith(String value) { Values.Initialize(new XLFormula { Value = value }); ConditionalFormatType = XLConditionalFormatType.EndsWith; Operator = XLCFOperator.EndsWith; return Style; } public IXLStyle WhenEquals(String value) { Values.Initialize(new XLFormula { Value = value }); Operator = XLCFOperator.Equal; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenNotEquals(String value) { Values.Initialize(new XLFormula { Value = value }); Operator = XLCFOperator.NotEqual; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenGreaterThan(String value) { Values.Initialize(new XLFormula { Value = value }); Operator = XLCFOperator.GreaterThan; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenLessThan(String value) { Values.Initialize(new XLFormula { Value = value }); Operator = XLCFOperator.LessThan; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenEqualOrGreaterThan(String value) { Values.Initialize(new XLFormula { Value = value }); Operator = XLCFOperator.EqualOrGreaterThan; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenEqualOrLessThan(String value) { Values.Initialize(new XLFormula { Value = value }); Operator = XLCFOperator.EqualOrLessThan; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenBetween(String minValue, String maxValue) { Values.Initialize(new XLFormula { Value = minValue }); Values.Add(new XLFormula { Value = maxValue }); Operator = XLCFOperator.Between; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenNotBetween(String minValue, String maxValue) { Values.Initialize(new XLFormula { Value = minValue }); Values.Add(new XLFormula { Value = maxValue }); Operator = XLCFOperator.NotBetween; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenEquals(Double value) { Values.Initialize(new XLFormula(value)); Operator = XLCFOperator.Equal; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenNotEquals(Double value) { Values.Initialize(new XLFormula(value)); Operator = XLCFOperator.NotEqual; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenGreaterThan(Double value) { Values.Initialize(new XLFormula(value)); Operator = XLCFOperator.GreaterThan; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenLessThan(Double value) { Values.Initialize(new XLFormula(value)); Operator = XLCFOperator.LessThan; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenEqualOrGreaterThan(Double value) { Values.Initialize(new XLFormula(value)); Operator = XLCFOperator.EqualOrGreaterThan; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenEqualOrLessThan(Double value) { Values.Initialize(new XLFormula(value)); Operator = XLCFOperator.EqualOrLessThan; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenBetween(Double minValue, Double maxValue) { Values.Initialize(new XLFormula(minValue)); Values.Add(new XLFormula(maxValue)); Operator = XLCFOperator.Between; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenNotBetween(Double minValue, Double maxValue) { Values.Initialize(new XLFormula(minValue)); Values.Add(new XLFormula(maxValue)); Operator = XLCFOperator.NotBetween; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenIsDuplicate() { ConditionalFormatType = XLConditionalFormatType.IsDuplicate; return Style; } public IXLStyle WhenIsUnique() { ConditionalFormatType = XLConditionalFormatType.IsUnique; return Style; } public IXLStyle WhenIsTrue(String formula) { String f = formula.TrimStart()[0] == '=' ? formula : "=" + formula; Values.Initialize(new XLFormula { Value = f }); ConditionalFormatType = XLConditionalFormatType.Expression; return Style; } public IXLStyle WhenIsTop(Int32 value, XLTopBottomType topBottomType = XLTopBottomType.Items) { Values.Initialize(new XLFormula(value)); Percent = topBottomType == XLTopBottomType.Percent; ConditionalFormatType = XLConditionalFormatType.Top10; Bottom = false; return Style; } public IXLStyle WhenIsBottom(Int32 value, XLTopBottomType topBottomType = XLTopBottomType.Items) { Values.Initialize(new XLFormula(value)); Percent = topBottomType == XLTopBottomType.Percent; ConditionalFormatType = XLConditionalFormatType.Top10; Bottom = true; return Style; } public IXLCFColorScaleMin ColorScale() { ConditionalFormatType = XLConditionalFormatType.ColorScale; return new XLCFColorScaleMin(this); } public IXLCFDataBarMin DataBar(XLColor color, Boolean showBarOnly = false) { Colors.Initialize(color); ShowBarOnly = showBarOnly; ConditionalFormatType = XLConditionalFormatType.DataBar; return new XLCFDataBarMin(this); } public IXLCFDataBarMin DataBar(XLColor positiveColor, XLColor negativeColor, Boolean showBarOnly = false) { Colors.Initialize(positiveColor); Colors.Add(negativeColor); ShowBarOnly = showBarOnly; ConditionalFormatType = XLConditionalFormatType.DataBar; return new XLCFDataBarMin(this); } public IXLCFIconSet IconSet(XLIconSetStyle iconSetStyle, Boolean reverseIconOrder = false, Boolean showIconOnly = false) { IconSetOperators.Clear(); Values.Clear(); ContentTypes.Clear(); ConditionalFormatType = XLConditionalFormatType.IconSet; IconSetStyle = iconSetStyle; ReverseIconOrder = reverseIconOrder; ShowIconOnly = showIconOnly; return new XLCFIconSet(this); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO.PortsTests; using System.Threading; using Legacy.Support; using Xunit; namespace System.IO.Ports.Tests { [KnownFailure] public class StopBits_Property : PortsTest { //The default ammount of time the a transfer should take at any given baud rate and stop bits combination. //The bytes sent should be adjusted to take this ammount of time to transfer at the specified baud rate and stop bits combination. private const int DEFAULT_TIME = 750; //If the percentage difference between the expected time to transfer with the specified stopBits //and the actual time found through Stopwatch is greater then 5% then the StopBits value was not correctly //set and the testcase fails. private const double MAX_ACCEPTABEL_PERCENTAGE_DIFFERENCE = .07; //The default number of databits to use when testing StopBits private const int DEFAULT_DATABITS = 8; private const int NUM_TRYS = 5; private enum ThrowAt { Set, Open }; #region Test Cases [ConditionalFact(nameof(HasNullModem))] public void StopBits_Default() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { SerialPortProperties serPortProp = new SerialPortProperties(); Debug.WriteLine("Verifying default StopBits"); serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); com1.Open(); serPortProp.VerifyPropertiesAndPrint(com1); VerifyStopBits(com1); serPortProp.VerifyPropertiesAndPrint(com1); } } [ConditionalFact(nameof(HasNullModem))] public void StopBits_1_BeforeOpen() { Debug.WriteLine("Verifying 1 StopBits before open"); VerifyStopBitsBeforeOpen((int)StopBits.One); } [ConditionalFact(nameof(HasNullModem))] public void StopBits_2_BeforeOpen() { Debug.WriteLine("Verifying 2 StopBits before open"); VerifyStopBitsBeforeOpen((int)StopBits.Two); } [ConditionalFact(nameof(HasNullModem))] public void StopBits_1_AfterOpen() { Debug.WriteLine("Verifying 1 StopBits after open"); VerifyStopBitsAfterOpen((int)StopBits.One); } [ConditionalFact(nameof(HasNullModem))] public void StopBits_2_AfterOpen() { Debug.WriteLine("Verifying 2 StopBits after open"); VerifyStopBitsAfterOpen((int)StopBits.Two); } [ConditionalFact(nameof(HasOneSerialPort))] public void StopBits_Int32MinValue() { Debug.WriteLine("Verifying Int32.MinValue StopBits"); VerifyException(int.MinValue, ThrowAt.Set, typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void StopBits_Neg1() { Debug.WriteLine("Verifying -1 StopBits"); VerifyException(-1, ThrowAt.Set, typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void StopBits_0() { Debug.WriteLine("Verifying 0 StopBits"); VerifyException(0, ThrowAt.Set, typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void StopBits_4() { Debug.WriteLine("Verifying 4 StopBits"); VerifyException(4, ThrowAt.Set, typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void StopBits_Int32MaxValue() { Debug.WriteLine("Verifying Int32.MaxValue StopBits"); VerifyException(int.MaxValue, ThrowAt.Set, typeof(ArgumentOutOfRangeException)); } #endregion #region Verification for Test Cases private void VerifyException(int stopBits, ThrowAt throwAt, Type expectedException) { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { VerifyExceptionAtOpen(com, stopBits, throwAt, expectedException); if (com.IsOpen) com.Close(); VerifyExceptionAfterOpen(com, stopBits, expectedException); } } private void VerifyExceptionAtOpen(SerialPort com, int stopBits, ThrowAt throwAt, Type expectedException) { int origStopBits = (int)com.StopBits; SerialPortProperties serPortProp = new SerialPortProperties(); serPortProp.SetAllPropertiesToDefaults(); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); if (ThrowAt.Open == throwAt) serPortProp.SetProperty("StopBits", (StopBits)stopBits); try { com.StopBits = (StopBits)stopBits; if (ThrowAt.Open == throwAt) com.Open(); if (null != expectedException) { Fail("ERROR!!! Expected Open() to throw {0} and nothing was thrown", expectedException); } } catch (Exception e) { if (null == expectedException) { Fail("ERROR!!! Expected Open() NOT to throw an exception and {0} was thrown", e.GetType()); } else if (e.GetType() != expectedException) { Fail("ERROR!!! Expected Open() throw {0} and {1} was thrown", expectedException, e.GetType()); } } serPortProp.VerifyPropertiesAndPrint(com); com.StopBits = (StopBits)origStopBits; } private void VerifyExceptionAfterOpen(SerialPort com, int stopBits, Type expectedException) { SerialPortProperties serPortProp = new SerialPortProperties(); com.Open(); serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); try { com.StopBits = (StopBits)stopBits; if (null != expectedException) { Fail("ERROR!!! Expected setting the StopBits after Open() to throw {0} and nothing was thrown", expectedException); } } catch (Exception e) { if (null == expectedException) { Fail("ERROR!!! Expected setting the StopBits after Open() NOT to throw an exception and {0} was thrown", e.GetType()); } else if (e.GetType() != expectedException) { Fail("ERROR!!! Expected setting the StopBits after Open() throw {0} and {1} was thrown", expectedException, e.GetType()); } } serPortProp.VerifyPropertiesAndPrint(com); } private void VerifyStopBitsBeforeOpen(int stopBits) { VerifyStopBitsBeforeOpen(stopBits, DEFAULT_DATABITS); } private void VerifyStopBitsBeforeOpen(int stopBits, int dataBits) { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { SerialPortProperties serPortProp = new SerialPortProperties(); serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); com1.DataBits = dataBits; com1.StopBits = (StopBits)stopBits; com1.Open(); serPortProp.SetProperty("DataBits", dataBits); serPortProp.SetProperty("StopBits", (StopBits)stopBits); serPortProp.VerifyPropertiesAndPrint(com1); VerifyStopBits(com1); serPortProp.VerifyPropertiesAndPrint(com1); } } private void VerifyStopBitsAfterOpen(int stopBits) { VerifyStopBitsAfterOpen(stopBits, DEFAULT_DATABITS); } private void VerifyStopBitsAfterOpen(int stopBits, int dataBits) { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { SerialPortProperties serPortProp = new SerialPortProperties(); serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); com1.Open(); com1.DataBits = dataBits; com1.StopBits = (StopBits)stopBits; serPortProp.SetProperty("DataBits", dataBits); serPortProp.SetProperty("StopBits", (StopBits)stopBits); serPortProp.VerifyPropertiesAndPrint(com1); VerifyStopBits(com1); serPortProp.VerifyPropertiesAndPrint(com1); if (com1.IsOpen) com1.Close(); } } private void VerifyStopBits(SerialPort com1) { Random rndGen = new Random(-55); Stopwatch sw = new Stopwatch(); using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { double expectedTime, actualTime, percentageDifference; int numBytes = 0; byte shiftMask = 0xFF; double stopBits = -1; switch ((int)com1.StopBits) { case (int)StopBits.One: stopBits = 1.0; break; case (int)StopBits.OnePointFive: stopBits = 1.5; break; case (int)StopBits.Two: stopBits = 2.0; break; } int numBytesToSend = (int)(((DEFAULT_TIME / 1000.0) * com1.BaudRate) / (stopBits + com1.DataBits + 1)); byte[] xmitBytes = new byte[numBytesToSend]; byte[] expectedBytes = new byte[numBytesToSend]; byte[] rcvBytes = new byte[numBytesToSend]; //Create a mask that when logicaly and'd with the transmitted byte will //will result in the byte recievied due to the leading bits being chopped //off due to DataBits less then 8 shiftMask >>= 8 - com1.DataBits; //Generate some random bytes to read/write for this StopBits setting for (int i = 0; i < xmitBytes.Length; i++) { xmitBytes[i] = (byte)rndGen.Next(0, 256); expectedBytes[i] = (byte)(xmitBytes[i] & shiftMask); } com2.DataBits = com1.DataBits; com2.StopBits = com1.StopBits; com2.Open(); actualTime = 0; Thread.CurrentThread.Priority = ThreadPriority.Highest; int initialNumBytes; for (int i = 0; i < NUM_TRYS; i++) { com2.DiscardInBuffer(); IAsyncResult beginWriteResult = com1.BaseStream.BeginWrite(xmitBytes, 0, numBytesToSend, null, null); while (0 == (initialNumBytes = com2.BytesToRead)) { } sw.Start(); TCSupport.WaitForReadBufferToLoad(com2, numBytesToSend); sw.Stop(); actualTime += sw.ElapsedMilliseconds; actualTime += ((initialNumBytes * (stopBits + com1.DataBits + 1)) / com1.BaudRate) * 1000; com1.BaseStream.EndWrite(beginWriteResult); sw.Reset(); } Thread.CurrentThread.Priority = ThreadPriority.Normal; actualTime /= NUM_TRYS; expectedTime = ((xmitBytes.Length * (stopBits + com1.DataBits + 1)) / com1.BaudRate) * 1000; percentageDifference = Math.Abs((expectedTime - actualTime) / expectedTime); //If the percentageDifference between the expected time and the actual time is to high //then the expected baud rate must not have been used and we should report an error if (MAX_ACCEPTABEL_PERCENTAGE_DIFFERENCE < percentageDifference) { Fail("ERROR!!! StopBits not used Expected time:{0}, actual time:{1} percentageDifference:{2}", expectedTime, actualTime, percentageDifference, numBytes); } com2.Read(rcvBytes, 0, rcvBytes.Length); //Verify that the bytes we sent were the same ones we received for (int i = 0; i < expectedBytes.Length; i++) { if (expectedBytes[i] != rcvBytes[i]) { Fail("ERROR!!! Expected to read {0} actual read {1}", expectedBytes[i], rcvBytes[i]); } } } } #endregion } }
/// SYNTAX TEST "Packages/C#/C#.sublime-syntax" class Foo { /// <- meta.class storage.type.class /// <- meta.class /// <- meta.class ///^^^^^^^^ meta.class /// ^ meta.class.body void Main(string[] args) { /// ^^^^ storage.type /// ^^^^^^^^^^^^^^^^^^^^^ meta.method /// ^^^^^^^^^^^^^^^^^^^^^ - meta.method meta.method /// ^^^^ entity.name.function /// ^^^^^^^^^^^^^^^ meta.method.parameters /// ^ punctuation.section.parameters.begin /// ^^^^^^ storage.type /// ^^ meta.brackets /// ^ punctuation.section.brackets.begin /// ^ punctuation.section.brackets.end /// ^^^^ variable.parameter /// ^ punctuation.section.parameters.end /// ^ punctuation.section.block.begin int x = 37; /// ^^^ storage.type /// ^ - entity.name /// ^ keyword.operator.assignment /// ^^ constant.numeric /// ^ punctuation.terminator // simple nested function int[] add(int y) {return x + y;} /// ^^^ storage.type /// ^^ meta.brackets /// ^ punctuation.section.brackets.begin /// ^ punctuation.section.brackets.end /// ^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.method.body meta.method /// ^^^ entity.name.function /// ^^^^^^^ meta.method.parameters /// ^ punctuation.section.parameters.begin /// ^^^ storage.type /// ^ variable.parameter /// ^ punctuation.section.parameters.end /// ^^^^^^^^^^^^^^^ meta.method.body meta.method.body /// ^ punctuation.section.block.begin /// ^^^^^^ keyword.control /// ^ keyword.operator /// ^ punctuation.terminator /// ^ punctuation.section.block.end T add(int y) {return x + y;}; /// ^ support.type /// ^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.method /// ^^^ entity.name.function /// ^^^^^^^ meta.method.parameters /// ^ punctuation.section.parameters.begin /// ^^^ storage.type /// ^ variable.parameter /// ^ punctuation.section.parameters.end /// ^^^^^^^^^^^^^^^ meta.method.body /// ^^^^^^ keyword.control /// ^ keyword.operator /// ^ punctuation.terminator /// ^ punctuation.section.block.end /// ^ punctuation.terminator List<int>[] add(int y) {return x + y;}; /// ^^^^ support.type /// ^^^^^ meta.generic /// ^ punctuation.definition.generic.begin /// ^^^ storage.type /// ^ punctuation.definition.generic.end /// ^^ meta.brackets /// ^ punctuation.section.brackets.begin /// ^ punctuation.section.brackets.end /// ^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.method /// ^^^ entity.name.function /// ^^^^^^^ meta.method.parameters /// ^ punctuation.section.parameters.begin /// ^^^ storage.type /// ^ variable.parameter /// ^ punctuation.section.parameters.end /// ^^^^^^^^^^^^^^^ meta.method.body /// ^^^^^^ keyword.control /// ^ keyword.operator /// ^ punctuation.terminator /// ^ punctuation.section.block.end /// ^ punctuation.terminator List<T, List<T>> add<T, R>(int y) {return x + y;}; /// ^^^^ support.type /// ^^^^^^^^^^^^ meta.generic /// ^ support.type /// ^ punctuation.separator /// ^^^ meta.generic meta.generic /// ^ support.type /// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.method /// ^^^ entity.name.function /// ^^^^^^ meta.generic /// ^ punctuation.definition.generic.begin /// ^ support.type /// ^ punctuation.separator /// ^ support.type /// ^ punctuation.definition.generic.end /// ^^^^^^^ meta.method.parameters /// ^ punctuation.section.parameters.begin /// ^^^ storage.type /// ^ variable.parameter /// ^ punctuation.section.parameters.end /// ^^^^^^^^^^^^^^^ meta.method.body /// ^^^^^^ keyword.control /// ^ keyword.operator /// ^ punctuation.terminator /// ^ punctuation.section.block.end /// ^ punctuation.terminator // lambda Func<int, string> store = (x, y) => x + y; /// ^^^^^^^^^^^^^ meta.generic /// ^^^ storage.type /// ^ punctuation.separator /// ^^^^^^ storage.type /// ^ punctuation.definition.generic.end /// ^^^^^ variable.other /// ^ keyword.operator /// ^^^^^^ meta.group /// ^ punctuation.section.group.begin /// ^ punctuation.section.group.end Console.Writeline(add(5)); /// ^ punctuation.accessor /// ^^^^^^^^^^^^^^^^^ meta.function-call /// ^^^^^^^^^ variable.function /// ^^^^^^^^ meta.group /// ^ punctuation.section.group.begin /// ^^^^^^ meta.function-call meta.function-call /// ^^^ variable.function /// ^^^ meta.group meta.group /// ^ punctuation.section.group.begin /// ^ constant.numeric /// ^ punctuation.section.group.end /// ^ punctuation.section.group.end // https://github.com/dotnet/roslyn/pull/2950 int bin = 0b1001_1010_0001_0100; /// ^^^^^^^^^^^^^^^^^^^^^ constant.numeric.integer.binary /// ^^ punctuation.definition.numeric.binary int hex = 0x1b_a0_44_fe; /// ^^^^^^^^^^^^^ constant.numeric.integer.hexadecimal /// ^^ punctuation.definition.numeric.hexadecimal int dec = 33_554_432; /// ^^^^^^^^^^ constant.numeric.integer.decimal int weird = 1_2__3___4____5_____6______7_______8________9; /// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ constant.numeric.integer.decimal double real = 1_000.111_1e-1_000; /// ^^^^^^^^^^^^^^^^^^ constant.numeric.float.decimal double dbl = 33_554_432.5_2; /// ^^^^^^^^^^^^^^ constant.numeric.float.decimal long lng = 33_554_4321L; /// ^^^^^^^^^^^ constant.numeric.integer.decimal /// ^ storage.type.numeric bin = _0b1001_1010_0001_0100; /// ^^^^^^^^^^^^^^^^^^^^^^ variable.other bin = 0b1001_1010_0001_0100_; /// ^ - constant.numeric bin = 0b_1001_1010_0001_0100; /// ^^^^^^^^^^^^^^^^^^^^^^ constant.numeric bin = 0b__1001__1010__0001__0_1_0_0; /// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ constant.numeric hex = _0x1b_a0_44_fe; /// ^^^^^^^^^^^^^^ variable.other hex = 0x_1b_a0_44_fe; /// ^^^^^^^^^^^^^^ constant.numeric int abc = _123; /// ^^^^ variable.other switch (sh) { case Shape shape when sh.Area == 0: /// ^^^^ keyword.control.switch.case /// ^^^^^ support.type /// ^^^^^ variable.other /// ^^^^ keyword.control.switch.case.when /// ^^ variable.other /// ^ punctuation.accessor.dot /// ^^^^ variable.other /// ^^ keyword.operator /// ^ constant.numeric /// ^ punctuation.separator.case-statement Console.WriteLine($"The shape: {sh.GetType().Name} with no dimensions"); break; case int? example when example == 5: /// ^^^^ keyword.control.switch.case /// ^^^ storage.type /// ^ storage.type.nullable /// ^^^^^^^ variable.other /// ^^^^ keyword.control.switch.case.when /// ^^^^^^^ variable.other /// ^^ keyword.operator /// ^ constant.numeric /// ^ punctuation.separator.case-statement case Shape<Shape> shape when shape.Area > 0: /// ^^^^ keyword.control.switch.case /// ^^^^^ support.type /// ^ punctuation.definition.generic.begin /// ^^^^^ support.type /// ^ punctuation.definition.generic.end /// ^^^^^ variable.other /// ^^^^ keyword.control.switch.case.when /// ^^^^^ variable.other /// ^ punctuation.accessor.dot /// ^^^^ variable.other /// ^ keyword.operator /// ^ constant.numeric /// ^ punctuation.separator.case-statement } // https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#out-variables if (int.TryParse(input, out var quantity)) /// ^^^ storage.modifier.argument /// ^ - storage.modifier.argument /// ^^^ storage.type.variable /// ^^^^^^^^ variable.other /// ^^ punctuation.section.group.end WriteLine(quantity); else WriteLine("Quantity is not a valid integer!"); Console.WriteLine($"{nameof(quantity)}: {quantity}"); // still valid /// ^^^^^^^ variable.other /// ^ punctuation.accessor.dot /// ^^^^^^^^^ variable.function int.TryParse(input, out ref int quantity); /// ^^^ storage.type /// ^ punctuation.accessor.dot /// ^^^^^^^^ variable.function /// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.function-call /// ^ punctuation.section.group.begin /// ^^^ storage.modifier.argument /// ^^^ storage.modifier.argument /// ^^^ storage.type /// ^^^^^^^^ variable.other /// ^ punctuation.section.group.end } /// ^ meta.class.body meta.method.body punctuation.section.block.end // https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#local-functions public Task<string> PerformLongRunningWork(string address, int index, string name) { if (string.IsNullOrWhiteSpace(address)) throw new ArgumentException(message: "An address is required", paramName: nameof(address)); if (index < 0) throw new ArgumentOutOfRangeException(paramName: nameof(index), message: "The index must be non-negative"); if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException(message: "You must supply a name", paramName: nameof(name)); return longRunningWorkImplementation(); async Task<string> longRunningWorkImplementation () /// ^^^^^ storage.modifier /// ^^^^ support.type /// ^ punctuation.definition.generic.begin /// ^^^^^^ storage.type /// ^ punctuation.definition.generic.end /// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ entity.name.function /// ^^ meta.method.parameters { /// ^ punctuation.section.block.begin /// ^ meta.class.body meta.method.body meta.method.body var interimResult = await FirstWork(address); var secondResult = await SecondStep(index, name); return $"The results are {interimResult} and {secondResult}. Enjoy."; } /// ^ punctuation.section.block.end /// ^ meta.class.body meta.method.body - meta.method.body meta.method.body } // https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#ref-locals-and-returns public static ref int Find3(int[,] matrix, Func<int, bool> predicate) { /// ^^^^^^ storage.modifier.access /// ^^^^^^ storage.modifier /// ^^^ storage.modifier /// ^^^ storage.type /// ^^^^^ entity.name.function /// ^ punctuation.section.parameters.begin /// ^^^ storage.type /// ^ punctuation.section.brackets.begin /// ^ punctuation.separator /// ^ punctuation.section.brackets.end /// ^^^^^^ variable.parameter for (int i = 0; i < matrix.GetLength(0); i++) for (int j = 0; j < matrix.GetLength(1); j++) if (predicate(matrix[i, j])) return ref matrix[i, j]; /// ^^^^^^ keyword.control.flow.return /// ^^^ keyword.other /// ^^^^^^ variable.other /// ^ punctuation.section.brackets.begin /// ^ variable.other /// ^ punctuation.separator.accessor /// ^ variable.other /// ^ punctuation.section.brackets.end /// ^ punctuation.terminator.statement throw new InvalidOperationException("Not found"); } // https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#tuples public void TupleTest () { var letters = ("a", "b"); /// ^^^^^^^^^^ meta.group.tuple /// ^ punctuation.section.group.begin /// ^ punctuation.separator.tuple /// ^ punctuation.section.group.end /// ^ punctuation.terminator.statement var (a, b, c) = (1, 2, 3); /// ^^^ storage.type.variable /// ^^^^^^^^^ meta.group.tuple /// ^ variable.other /// ^ punctuation.separator.tuple /// ^ variable.other /// ^ punctuation.separator.tuple /// ^ keyword.operator.assignment - meta.group /// ^^^^^^^^^ meta.group.tuple /// ^ constant.numeric.integer.decimal /// ^ punctuation.separator.tuple (string Alpha, string Beta) namedLetters = ("a", "b"); /// ^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.group.tuple /// ^ punctuation.section.group.begin /// ^^^^^^ storage.type /// ^^^^^ variable.other /// ^ punctuation.separator.tuple /// ^^^^^^ storage.type /// ^^^^ variable.other /// ^ punctuation.section.group.end /// ^^^^^^^^^^^^ variable.other /// ^ keyword.operator.assignment /// ^ punctuation.section.group.begin /// ^ punctuation.separator.tuple /// ^ punctuation.section.group.end /// ^ punctuation.terminator.statement (SomeType[] Alpha, SomeType<int> Beta) example = (a, b); /// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.group.tuple /// ^ punctuation.section.group.begin /// ^^^^^^^^ support.type /// ^ punctuation.section.brackets.begin /// ^ punctuation.section.brackets.end /// ^^^^^ variable.other /// ^ punctuation.separator.tuple /// ^^^^^^^^ support.type /// ^ punctuation.definition.generic.begin /// ^^^ storage.type /// ^ punctuation.definition.generic.end /// ^^^^ variable.other /// ^ punctuation.section.group.end /// ^^^^^^^ variable.other /// ^ keyword.operator.assignment /// ^^^^^^ meta.group.tuple /// ^ punctuation.section.group.begin /// ^ variable.other /// ^ punctuation.separator.tuple /// ^ punctuation.section.group.end /// ^ punctuation.terminator.statement var alphabetStart = (Alpha: "a", Beta: "b"); /// ^^^^^^^^^^^^^^^^^^^^^^^ meta.group.tuple /// ^ punctuation.section.group.begin /// ^^^^^ variable.other /// ^ keyword.operator.assignment /// ^ punctuation.separator.tuple /// ^^^^ variable.other /// ^ keyword.operator.assignment /// ^ punctuation.section.group.end /// ^ punctuation.terminator.statement var abc = (this as object, input); /// ^ punctuation.section.group.begin /// ^^^^ variable.language /// ^^ keyword.operator.reflection /// ^^^^^^ storage.type /// ^ punctuation.separator.tuple /// ^^^^^ variable.other /// ^ punctuation.section.group.end /// ^ punctuation.terminator.statement var abc = (example.Alpha as SomeType); /// ^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.group - meta.group.tuple /// ^ punctuation.section.group.begin /// ^^^^^^^ variable.other /// ^ punctuation.accessor.dot /// ^^^^^ variable.other /// ^^ keyword.operator.reflection /// ^^^^^^^^ support.type /// ^ punctuation.section.group.end /// ^ punctuation.terminator.statement // https://docs.microsoft.com/en-us/dotnet/csharp/deconstruct (string city, _, double area) = QueryCityData("New York City"); /// ^ punctuation.section.group.begin /// ^^^^^^ storage.type /// ^^^^ variable.other /// ^ punctuation.separator.tuple /// ^ variable.language.deconstruction.discard /// ^ punctuation.separator.tuple /// ^^^^^^ storage.type /// ^^^^ variable.other /// ^ punctuation.section.group.end /// ^ keyword.operator.assignment (city, population, _) = QueryCityData("New York City"); /// ^ punctuation.section.group.begin /// ^^^^ variable.other /// ^ punctuation.separator.tuple /// ^^^^^^^^^^ variable.other /// ^ punctuation.separator.tuple /// ^ variable.language.deconstruction /// ^ punctuation.section.group.end /// ^ keyword.operator.assignment var (_, _, _, pop1, _, pop2) = QueryCityDataForYears("New York City", 1960, 2010); /// ^^^ storage.type.variable /// ^^^^^^^^^^^^^^^^^^^^^^^^ meta.group.tuple /// ^ - meta.group /// ^ punctuation.definition.group.begin /// ^ variable.language /// ^ punctuation.separator.tuple /// ^ variable.language /// ^ punctuation.separator.tuple /// ^^^^ variable.other /// ^ punctuation.separator.tuple /// ^ variable.language /// ^ punctuation.separator.tuple /// ^^^^ variable.other /// ^ punctuation.definition.group.end (Func<int, int> test1, string test2) = ((int d) => d * 2, 5.ToString()); /// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.group.tuple /// ^^^^ support.type /// ^^^^^^^^^^ meta.generic /// ^^^^^ variable.other /// ^ punctuation.separator.tuple /// ^^^^^^ storage.type /// ^^^^^ variable.other /// ^ keyword.operator.assignment - meta.group /// ^ meta.group.tuple punctuation.section.group.begin /// ^^^^^^^^^^^^^^^^ meta.function.anonymous /// ^ punctuation.separator.tuple - meta.function.anonymous /// ^ constant.numeric.float.decimal /// ^ punctuation.accessor.dot /// ^^^^^^^^ variable.function /// ^ punctuation.section.group.begin /// ^ punctuation.section.group.end /// ^ punctuation.section.group.end (a, b) = (new Random().Next(), 15); /// ^^^ keyword.operator.new /// ^^^^^^ support.type /// ^ punctuation.separator.tuple /// ^^ meta.group.tuple constant.numeric.integer.decimal /// ^ punctuation.section.group.end var dic = new Dictionary<string, int> { ["Bob"] = 32, ["Alice"] = 17 }; foreach (var (name, age) in dic.Select(x => (x.Key, x.Value))) /// ^^^ storage.type.variable /// ^^^^^^^^^^^ meta.group.tuple /// ^ punctuation.definition.group.begin /// ^^^^ variable.other /// ^ punctuation.separator.tuple /// ^^^ variable.other /// ^ punctuation.definition.group.end /// ^^ keyword.control.flow { Console.WriteLine($"{name} is {age} years old."); } } private static (int Max, int Min) Range(IEnumerable<int> numbers) /// ^^^^^^^ storage.modifier.access /// ^^^^^^ storage.modifier /// ^ punctuation.section.group.begin /// ^^^ storage.type /// ^^^ variable.other /// ^ punctuation.separator.tuple /// ^^^ storage.type /// ^^^ variable.other /// ^ punctuation.section.group.end /// ^^^^^ entity.name.function - entity.name.function.constructor /// ^ punctuation.section.parameters.begin /// ^^^^^^^^^^^ support.type /// ^ punctuation.definition.generic.begin /// ^^^ storage.type /// ^ punctuation.definition.generic.end /// ^^^^^^^ variable.parameter /// ^ punctuation.section.parameters.end { int min = int.MaxValue; int max = int.MinValue; foreach(var n in numbers) { min = (n < min) ? n : min; max = (n > max) ? n : max; } return (max, min); /// ^^^^^^ keyword.control.flow.return /// ^ punctuation.section.group.begin /// ^^^ variable.other /// ^ punctuation.separator.tuple /// ^^^ variable.other /// ^ punctuation.section.group.end /// ^ punctuation.terminator.statement Func<string, (string example1, int Example2)> test = s => (example1: "hello", Example2: "world"); /// ^^^^ support.type /// ^ punctuation.definition.generic.begin /// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.generic /// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.group.tuple /// ^ punctuation.section.group.begin /// ^^^^^^ storage.type /// ^^^^^^^^ variable.other /// ^ punctuation.separator.tuple /// ^^^ storage.type /// ^^^^^^^^ variable.other /// ^ punctuation.section.group.end /// ^ punctuation.definition.generic.end /// ^^^^ variable.other /// ^ keyword.operator.assignment.variable /// ^ variable.parameter /// ^^ storage.type.function.lambda /// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.group /// ^ punctuation.section.group.begin /// ^^^^^^^^ variable.other /// ^ keyword.operator.assignment /// ^ punctuation.separator /// ^^^^^^^^ variable.other /// ^ keyword.operator.assignment /// ^ punctuation.section.group.end /// ^ punctuation.terminator.statement } public void Deconstruct(out string firstName, out string lastName, out int age) { firstName = FirstName; lastName = LastName; age = Age; } public void Example((int foo, float bar) val, (int foo, string bar) otherVal) {} /// ^^^^^^^ entity.name.function /// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.method.parameters /// ^ punctuation.section.parameters.begin /// ^^^^^^^^^^^^^^^^^^^^ meta.group.tuple /// ^ punctuation.section.group.begin /// ^^^ storage.type /// ^^^ variable.other /// ^ punctuation.separator.tuple /// ^^^^^ storage.type /// ^^^ variable.other /// ^ punctuation.section.group.end /// ^^^ variable.parameter /// ^ punctuation.separator.parameter.function /// ^^^^^^^^^^^^^^^^^^^^^ meta.group.tuple /// ^^^^^^^^ variable.parameter /// ^ punctuation.section.parameters.end public void Example((int , float ) val, (int, string) otherVal) {} /// ^^^^^^^ entity.name.function /// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.method.parameters /// ^^^^^^^^^^^^^^ meta.group.tuple /// ^^^ storage.type /// ^ punctuation.separator.tuple /// ^^^^^ storage.type /// ^ punctuation.section.group.end /// ^^^ variable.parameter - meta.group.tuple /// ^ punctuation.separator.parameter.function /// ^^^^^^^^^^^^^ meta.group.tuple /// ^ punctuation.section.group.begin /// ^^^ storage.type /// ^ punctuation.separator.tuple /// ^^^^^^ storage.type /// ^ punctuation.section.group.end /// ^^^^^^^^ variable.parameter /// ^ punctuation.section.parameters.end } /// <- meta.class.body punctuation.section.block.end public readonly struct S /// ^^ storage.modifier.access /// ^^^^^^^^ storage.modifier /// ^^^^^^ storage.type.struct /// ^ entity.name.struct { /// <- meta.struct.body meta.block punctuation.section.block.begin public readonly int Age; /// ^^^^^^ storage.modifier.access /// ^^^^^^^^ storage.modifier /// ^^^ storage.type /// ^^^ variable.other.member public string Name { get; } public readonly int X, Y; // All fields must be readonly /// ^ variable.other.member /// ^ punctuation.separator.variables /// ^ variable.other.member /// ^ punctuation.terminator.statement public S(int age, string name) { this.Age = age; this.Name = name; } public S(S other) { this = other; } } // "private protected" is now a valid modifier. It's equivalent to protected, except that it can only be // accessed inside the current assembly. class BaseClass { private protected void Foo() {} } /// ^^^^^^^ storage.modifier.access /// ^^^^^^^^^ storage.modifier.access /// ^^^^ storage.type /// ^^^ entity.name.function class Derived : BaseClass { void Bar() => Foo(); } // You can now place the "in" keyword before parameters to prevent them from being modified. This is // particularly useful with structs, because the compiler avoids the overhead of having to copy the value: void Foo (in string s, in int x, in Point point) ///^ storage.type /// ^^^ entity.name.function /// ^^ storage.modifier.parameter /// ^^^^^^ storage.type /// ^ variable.parameter /// ^ punctuation.separator.parameter { // s = "new"; // error // x++; // error // point.X++; // error } // Note that you don't specify the 'in' modifier when calling the method: void TestFoo() => Foo ("hello", 123, new Point (2, 3)); // https://msdn.microsoft.com/en-us/magazine/mt814808.aspx Span<byte> bytes = length <= 128 ? stackalloc byte[length] : new byte[length]; /// ^^^^^^^^^^ keyword.other /// ^^^^ variable.other bytes[0] = 42; bytes[1] = 43; Assert.Equal(42, bytes[0]); Assert.Equal(43, bytes[1]); bytes[2] = 44; // throws IndexOutOfRangeException public readonly ref struct Span<T> /// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.struct /// ^ storage.modifier.access /// ^^^^^^^^ storage.modifier /// ^^^ storage.modifier /// ^^^^^^ storage.type.struct /// ^^^^ entity.name.struct { private readonly ref T _pointer; /// ^^^^^^^ storage.modifier.access /// ^^^^^^^^ storage.modifier /// ^^^ storage.modifier /// ^ support.type /// ^^^^^^^^ variable.other.member private readonly int _length; } public delegate void SpanAction<T, in TArg>(Span<T> span, TArg arg); /// ^^^^^^^^ storage.type.delegate /// ^^^^ storage.type /// ^^^^^^^^^^ variable.other.member.delegate /// ^^^^^^^^^^^^ meta.generic /// ^ support.type /// ^ punctuation.separator.type /// ^^ storage.modifier /// ^^^^ support.type void Test () { int[] array = { 1, 15, -39, 0, 7, 14, -12 }; /// ^ constant.numeric.integer.decimal /// ^ punctuation.separator.array-element /// ^ punctuation.terminator.statement ref int place = ref Find (7, array); // aliases 7's place in the array /// ^^^ storage.modifier /// ^^^ storage.type /// ^^^^^ variable.other /// ^ keyword.operator.assignment.variable /// ^^^ keyword.other /// ^^^^ variable.function place = 9; // replaces 7 with 9 in the array Console.WriteLine (array [4]); // prints 9 } public ref int Find (int number, int[] numbers) /// ^^ storage.modifier.access /// ^^^ storage.modifier /// ^^^ storage.type /// ^^^^ entity.name.function { for (int i = 0; i < numbers.Length; i++) { if (numbers [i] == number) { return ref numbers [i]; // return the storage location, not the value /// ^^^^^^ keyword.control.flow.return /// ^^^ keyword.other /// ^^^^^^^ variable.other } } throw new IndexOutOfRangeException ($"{nameof (number)} not found"); } public class MyClass { object obj; public MyClass () => obj = null; /// ^^^^^^^ meta.method.constructor entity.name.function.constructor /// ^^^^^^^^^^^^^^^^^ meta.class.body meta.block meta.method /// ^^ storage.type.function /// ^^^ variable.other /// ^ keyword.operator.assignment /// ^^^^ constant.language /// ^ punctuation.terminator.statement - meta.method } /// <- meta.class.body meta.block punctuation.section.block.end public class Person // https://stackoverflow.com/a/41974829/4473405 { public string Name { get; } public int Age { get; } public Person(string name, int age) => (Name, Age) = (name, age); /// ^^^^^^ storage.modifier.access /// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.method.constructor /// ^^^^^^ entity.name.function.constructor /// ^ punctuation.section.parameters.begin /// ^^^^^^ storage.type /// ^^^^ variable.parameter /// ^ punctuation.separator.parameter.function /// ^^^ storage.type /// ^^^ variable.parameter /// ^ punctuation.section.parameters.end /// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.method /// ^^ storage.type.function /// ^ meta.group punctuation.section.group.begin /// ^^^^ meta.group variable.other /// ^ meta.group punctuation.separator.tuple /// ^^^ meta.group variable.other /// ^ meta.group punctuation.section.group.end /// ^ keyword.operator.assignment /// ^ meta.group punctuation.section.group.begin /// ^^^^ meta.group variable.other /// ^ punctuation.separator.tuple /// ^^^ meta.group variable.other /// ^ meta.group punctuation.section.group.end /// ^ punctuation.terminator.statement }
// Copyright 2014 Stefan Negritoiu. See LICENSE file for more information. using System; using System.Globalization; using System.Security.Claims; using Microsoft.Owin; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Provider; using Newtonsoft.Json.Linq; namespace Owin.Security.Providers.AzureAD { /// <summary> /// Contains information about the login session as well as the user <see cref="System.Security.Claims.ClaimsIdentity"/>. /// </summary> public class AzureADAuthenticatedContext : BaseContext { private readonly string[] SCOPE_SEPARATOR = new string[] { " " }; /// <summary> /// Initializes a <see cref="AzureADAuthenticatedContext"/> /// </summary> /// <param name="context">The OWIN environment</param> /// <param name="user">The JSON-serialized user</param> /// <param name="accessToken">Azure AD Access token</param> public AzureADAuthenticatedContext(IOwinContext context, string accessToken, string expires, string refreshToken, JObject response) : base(context) { AccessToken = accessToken; RefreshToken = refreshToken; // parse expires field int expiresValue; if (Int32.TryParse(expires, NumberStyles.Integer, CultureInfo.InvariantCulture, out expiresValue)) { ExpiresIn = TimeSpan.FromSeconds(expiresValue); } // parse scope field string scope = response["scope"]?.Value<string>(); Scope = scope != null ? scope.Split(SCOPE_SEPARATOR, StringSplitOptions.RemoveEmptyEntries) : new string[0]; // parse resource field Resource = response["resource"]?.Value<string>(); // parse pwd fields string pwdchange = response["pwd_url"]?.Value<string>(); string pwdexpires = response["pwd_exp"]?.Value<string>(); if (!String.IsNullOrEmpty(pwdexpires) && Int32.TryParse(pwdexpires, NumberStyles.Integer, CultureInfo.InvariantCulture, out expiresValue)) { PasswordExpiresIn = TimeSpan.FromSeconds(expiresValue); PasswordChangeUrl = pwdchange; } // parse id_token as a Base64 url encoded JSON web token string idToken = response["id_token"].Value<string>(); JObject idTokenObj = null; string[] segments; if (!String.IsNullOrEmpty(idToken) && (segments = idToken.Split('.')).Length == 3) { string payload = base64urldecode(segments[1]); if (!String.IsNullOrEmpty(payload)) idTokenObj = JObject.Parse(payload); } if (idTokenObj != null) { // per https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-token-and-claims Subject = TryGetValue(idTokenObj, "sub"); ObjectId = TryGetValue(idTokenObj, "oid"); TenantId = TryGetValue(idTokenObj, "tid"); Upn = TryGetValue(idTokenObj, "upn"); UserName = TryGetValue(idTokenObj, "unique_name"); Name = TryGetValue(idTokenObj, "name"); GivenName = TryGetValue(idTokenObj, "given_name"); FamilyName = TryGetValue(idTokenObj, "family_name"); AppId = TryGetValue(idTokenObj, "appid"); } } /// <summary> /// Gets the AzureAD OAuth access token /// </summary> public string AccessToken { get; private set; } /// <summary> /// Gets the scope for this AzureAD OAuth access token /// </summary> public string[] Scope { get; private set; } /// <summary> /// Gets the resource for this AzureAD OAuth access token /// </summary> public string Resource { get; private set; } /// <summary> /// Gets the AzureAD access token expiration time /// </summary> public TimeSpan? ExpiresIn { get; private set; } /// <summary> /// Gets the AzureAD OAuth refresh token /// </summary> public string RefreshToken { get; private set; } /// <summary> /// Gets the user's ID (unique across tenants; unique across applications) /// </summary> public string Subject { get; private set; } /// <summary> /// Gets the user's ID (unique across tenants; not unique across applications) /// </summary> public string ObjectId { get; private set; } /// <summary> /// Gets the tenant's ID /// </summary> public string TenantId { get; private set; } /// <summary> /// Gets the UPN /// </summary> public string Upn { get; private set; } /// <summary> /// Gets the display UPN /// </summary> public string UserName { get; private set; } /// <summary> /// Gets the email address /// </summary> public string Email { get; set; } /// <summary> /// Gets the user's first name /// </summary> public string GivenName { get; private set; } /// <summary> /// Gets the user's last name /// </summary> public string FamilyName { get; private set; } /// <summary> /// Gets the user's display name /// </summary> public string Name { get; private set; } /// <summary> /// Gets the application ID for which token was issued /// </summary> public string AppId { get; private set; } /// <summary> /// /// </summary> public TimeSpan? PasswordExpiresIn { get; private set; } /// <summary> /// /// </summary> public string PasswordChangeUrl { get; private set; } /// <summary> /// Gets the <see cref="ClaimsIdentity"/> representing the user /// </summary> public ClaimsIdentity Identity { get; set; } /// <summary> /// Gets or sets a property bag for common authentication properties /// </summary> public AuthenticationProperties Properties { get; set; } private static string TryGetValue(JObject user, string propertyName) { JToken value; return user.TryGetValue(propertyName, out value) ? value.ToString() : null; } /// <summary> /// Based on http://tools.ietf.org/html/draft-ietf-jose-json-web-signature-08#appendix-C /// </summary> static string base64urldecode(string arg) { string s = arg; s = s.Replace('-', '+'); // 62nd char of encoding s = s.Replace('_', '/'); // 63rd char of encoding switch (s.Length % 4) // Pad with trailing '='s { case 0: break; // No pad chars in this case case 2: s += "=="; break; // Two pad chars case 3: s += "="; break; // One pad char default: throw new System.Exception("Illegal base64url string!"); } try { System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); return encoding.GetString(Convert.FromBase64String(s)); // Standard base64 decoder } catch (FormatException) { return null; } } } }
using OpenKh.Common; using OpenKh.Imaging; using System; using System.Collections.Generic; using System.IO; using System.Numerics; using Xe.BinaryMapper; using System.Linq; using System.Text; using OpenKh.Common.Utils; namespace OpenKh.Bbs { public class Pam { private const uint MagicCode = 0x4D4150; public class Header { [Data] public uint MagicCode { get; set; } [Data] public uint AnimationCount { get; set; } [Data(Count = 6)] public byte[] Padding { get; set; } [Data] public ushort Version { get; set; } } public class AnimationEntry { [Data] public uint AnimationOffset { get; set; } [Data(Count = 12)] public string AnimationName { get; set; } } public class AnimationHeader { [Data] public ushort Flag { get; set; } [Data] public byte Framerate { get; set; } [Data] public byte InterpFrameCount { get; set; } [Data] public ushort LoopFrame { get; set; } [Data] public byte BoneCount { get; set; } [Data] public byte Padding { get; set; } [Data] public ushort FrameCount { get; set; } [Data] public ushort ReturnFrame { get; set; } } public struct AnimationFlag { [Data] public bool TranslationX { get; set; } [Data] public bool TranslationY { get; set; } [Data] public bool TranslationZ { get; set; } [Data] public bool RotationX { get; set; } [Data] public bool RotationY { get; set; } [Data] public bool RotationZ { get; set; } [Data] public bool ScaleX { get; set; } [Data] public bool ScaleY { get; set; } [Data] public bool ScaleZ { get; set; } } public static AnimationFlag GetAnimFlags(ushort Flag) { AnimationFlag flag = new AnimationFlag(); flag.TranslationX = BitsUtil.Int.GetBit(Flag, 0); flag.TranslationY = BitsUtil.Int.GetBit(Flag, 1); flag.TranslationZ = BitsUtil.Int.GetBit(Flag, 2); flag.RotationX = BitsUtil.Int.GetBit(Flag, 3); flag.RotationY = BitsUtil.Int.GetBit(Flag, 4); flag.RotationZ = BitsUtil.Int.GetBit(Flag, 5); flag.ScaleX = BitsUtil.Int.GetBit(Flag, 6); flag.ScaleY = BitsUtil.Int.GetBit(Flag, 7); flag.ScaleZ = BitsUtil.Int.GetBit(Flag, 8); return flag; } public class ChannelHeader { [Data] public float MaxValue { get; set; } [Data] public float MinValue { get; set; } [Data] public byte KeyframeCount_8bits { get; set; } [Data] public ushort KeyframeCount_16bits { get; set; } } public class KeyframeEntry { [Data] public byte FrameID_8bits { get; set; } [Data] public ushort FrameID_16bits { get; set; } [Data] public ushort Value { get; set; } } public class AnimationData { [Data] public ChannelHeader Header { get; set; } [Data] public List<KeyframeEntry> Keyframes { get; set; } } public class BoneChannel { [Data] public AnimationData TranslationX { get; set; } [Data] public AnimationData TranslationY { get; set; } [Data] public AnimationData TranslationZ { get; set; } [Data] public AnimationData RotationX { get; set; } [Data] public AnimationData RotationY { get; set; } [Data] public AnimationData RotationZ { get; set; } [Data] public AnimationData ScaleX { get; set; } [Data] public AnimationData ScaleY { get; set; } [Data] public AnimationData ScaleZ { get; set; } } public class AnimationInfo { [Data] public List<ushort> ChannelFlags { get; set; } [Data] public AnimationEntry AnimEntry { get; set; } [Data] public AnimationHeader AnimHeader { get; set; } [Data] public List<BoneChannel> BoneChannels { get; set; } } public Header header = new Header(); public List<AnimationInfo> animList = new List<AnimationInfo>(); public static Pam Read(Stream stream) { Pam pam = new Pam(); pam.header = BinaryMapping.ReadObject<Header>(stream); pam.animList = new List<AnimationInfo>(); for(int i = 0; i < pam.header.AnimationCount; i++) { pam.animList.Add(new AnimationInfo()); pam.animList[i].AnimEntry = BinaryMapping.ReadObject<AnimationEntry>(stream); } // Get all anims in PAM pack. for(int j = 0; j < pam.animList.Count; j++) { stream.Seek(pam.animList[j].AnimEntry.AnimationOffset, SeekOrigin.Begin); pam.animList[j].AnimHeader = BinaryMapping.ReadObject<AnimationHeader>(stream); byte BoneNum = pam.animList[j].AnimHeader.BoneCount; ushort frameNum = pam.animList[j].AnimHeader.FrameCount; pam.animList[j].ChannelFlags = new List<ushort>(); // Channel Flags for (int k = 0; k < BoneNum; k++) { pam.animList[j].ChannelFlags.Add(stream.ReadUInt16()); } pam.animList[j].BoneChannels = new List<BoneChannel>(); // Channel Header & Data for (int l = 0; l < BoneNum; l++) { BoneChannel boneChannel = new BoneChannel(); AnimationFlag flg = GetAnimFlags(pam.animList[j].ChannelFlags[l]); ushort frameCnt = pam.animList[j].AnimHeader.FrameCount; /** TRANSLATION **/ if (flg.TranslationX) { ushort keyframeCnt = 0; boneChannel.TranslationX = new AnimationData(); boneChannel.TranslationX.Header = new ChannelHeader(); boneChannel.TranslationX.Header.MaxValue = stream.ReadFloat(); boneChannel.TranslationX.Header.MinValue = stream.ReadFloat(); if (frameCnt > 255) { keyframeCnt = boneChannel.TranslationX.Header.KeyframeCount_16bits = stream.ReadUInt16(); } else { keyframeCnt = boneChannel.TranslationX.Header.KeyframeCount_8bits = (byte)stream.ReadByte(); } if(keyframeCnt != 1) { boneChannel.TranslationX.Keyframes = new List<KeyframeEntry>(); for (ushort z = 0; z < keyframeCnt; z++) { KeyframeEntry ent = new KeyframeEntry(); if (keyframeCnt == frameCnt) { ent.FrameID_16bits = z; ent.Value = stream.ReadUInt16(); boneChannel.TranslationX.Keyframes.Add(ent); } else { if (frameCnt > 255) { ent.FrameID_16bits = stream.ReadUInt16(); } else { ent.FrameID_8bits = (byte)stream.ReadByte(); } ent.Value = stream.ReadUInt16(); boneChannel.TranslationX.Keyframes.Add(ent); } } } } if (flg.TranslationY) { ushort keyframeCnt = 0; boneChannel.TranslationY = new AnimationData(); boneChannel.TranslationY.Header = new ChannelHeader(); boneChannel.TranslationY.Header.MaxValue = stream.ReadFloat(); boneChannel.TranslationY.Header.MinValue = stream.ReadFloat(); if (frameCnt > 255) { keyframeCnt = boneChannel.TranslationY.Header.KeyframeCount_16bits = stream.ReadUInt16(); } else { keyframeCnt = boneChannel.TranslationY.Header.KeyframeCount_8bits = (byte)stream.ReadByte(); } if (keyframeCnt != 1) { boneChannel.TranslationY.Keyframes = new List<KeyframeEntry>(); for (ushort z = 0; z < keyframeCnt; z++) { KeyframeEntry ent = new KeyframeEntry(); if (keyframeCnt == frameCnt) { ent.FrameID_16bits = z; ent.Value = stream.ReadUInt16(); boneChannel.TranslationY.Keyframes.Add(ent); } else { if (frameCnt > 255) { ent.FrameID_16bits = stream.ReadUInt16(); } else { ent.FrameID_8bits = (byte)stream.ReadByte(); } ent.Value = stream.ReadUInt16(); boneChannel.TranslationY.Keyframes.Add(ent); } } } } if (flg.TranslationZ) { ushort keyframeCnt = 0; boneChannel.TranslationZ = new AnimationData(); boneChannel.TranslationZ.Header = new ChannelHeader(); boneChannel.TranslationZ.Header.MaxValue = stream.ReadFloat(); boneChannel.TranslationZ.Header.MinValue = stream.ReadFloat(); if (frameCnt > 255) { keyframeCnt = boneChannel.TranslationZ.Header.KeyframeCount_16bits = stream.ReadUInt16(); } else { keyframeCnt = boneChannel.TranslationZ.Header.KeyframeCount_8bits = (byte)stream.ReadByte(); } if (keyframeCnt != 1) { boneChannel.TranslationZ.Keyframes = new List<KeyframeEntry>(); for (ushort z = 0; z < keyframeCnt; z++) { KeyframeEntry ent = new KeyframeEntry(); if (keyframeCnt == frameCnt) { ent.FrameID_16bits = z; ent.Value = stream.ReadUInt16(); boneChannel.TranslationZ.Keyframes.Add(ent); } else { if (frameCnt > 255) { ent.FrameID_16bits = stream.ReadUInt16(); } else { ent.FrameID_8bits = (byte)stream.ReadByte(); } ent.Value = stream.ReadUInt16(); boneChannel.TranslationZ.Keyframes.Add(ent); } } } } /** ROTATION **/ if (flg.RotationX) { ushort keyframeCnt = 0; boneChannel.RotationX = new AnimationData(); boneChannel.RotationX.Header = new ChannelHeader(); boneChannel.RotationX.Header.MaxValue = stream.ReadFloat(); boneChannel.RotationX.Header.MinValue = stream.ReadFloat(); if (frameCnt > 255) { keyframeCnt = boneChannel.RotationX.Header.KeyframeCount_16bits = stream.ReadUInt16(); } else { keyframeCnt = boneChannel.RotationX.Header.KeyframeCount_8bits = (byte)stream.ReadByte(); } if (keyframeCnt != 1) { boneChannel.RotationX.Keyframes = new List<KeyframeEntry>(); for (ushort z = 0; z < keyframeCnt; z++) { KeyframeEntry ent = new KeyframeEntry(); if (keyframeCnt == frameCnt) { ent.FrameID_16bits = z; ent.Value = stream.ReadUInt16(); boneChannel.RotationX.Keyframes.Add(ent); } else { if (frameCnt > 255) { ent.FrameID_16bits = stream.ReadUInt16(); } else { ent.FrameID_8bits = (byte)stream.ReadByte(); } ent.Value = stream.ReadUInt16(); boneChannel.RotationX.Keyframes.Add(ent); } } } } if (flg.RotationY) { ushort keyframeCnt = 0; boneChannel.RotationY = new AnimationData(); boneChannel.RotationY.Header = new ChannelHeader(); boneChannel.RotationY.Header.MaxValue = stream.ReadFloat(); boneChannel.RotationY.Header.MinValue = stream.ReadFloat(); if (frameCnt > 255) { keyframeCnt = boneChannel.RotationY.Header.KeyframeCount_16bits = stream.ReadUInt16(); } else { keyframeCnt = boneChannel.RotationY.Header.KeyframeCount_8bits = (byte)stream.ReadByte(); } if (keyframeCnt != 1) { boneChannel.RotationY.Keyframes = new List<KeyframeEntry>(); for (ushort z = 0; z < keyframeCnt; z++) { KeyframeEntry ent = new KeyframeEntry(); if (keyframeCnt == frameCnt) { ent.FrameID_16bits = z; ent.Value = stream.ReadUInt16(); boneChannel.RotationY.Keyframes.Add(ent); } else { if (frameCnt > 255) { ent.FrameID_16bits = stream.ReadUInt16(); } else { ent.FrameID_8bits = (byte)stream.ReadByte(); } ent.Value = stream.ReadUInt16(); boneChannel.RotationY.Keyframes.Add(ent); } } } } if (flg.RotationZ) { ushort keyframeCnt = 0; boneChannel.RotationZ = new AnimationData(); boneChannel.RotationZ.Header = new ChannelHeader(); boneChannel.RotationZ.Header.MaxValue = stream.ReadFloat(); boneChannel.RotationZ.Header.MinValue = stream.ReadFloat(); if (frameCnt > 255) { keyframeCnt = boneChannel.RotationZ.Header.KeyframeCount_16bits = stream.ReadUInt16(); } else { keyframeCnt = boneChannel.RotationZ.Header.KeyframeCount_8bits = (byte)stream.ReadByte(); } if (keyframeCnt != 1) { boneChannel.RotationZ.Keyframes = new List<KeyframeEntry>(); for (ushort z = 0; z < keyframeCnt; z++) { KeyframeEntry ent = new KeyframeEntry(); if (keyframeCnt == frameCnt) { ent.FrameID_16bits = z; ent.Value = stream.ReadUInt16(); boneChannel.RotationZ.Keyframes.Add(ent); } else { if (frameCnt > 255) { ent.FrameID_16bits = stream.ReadUInt16(); } else { ent.FrameID_8bits = (byte)stream.ReadByte(); } ent.Value = stream.ReadUInt16(); boneChannel.RotationZ.Keyframes.Add(ent); } } } } /** SCALE **/ if (flg.ScaleX) { ushort keyframeCnt = 0; boneChannel.ScaleX = new AnimationData(); boneChannel.ScaleX.Header = new ChannelHeader(); boneChannel.ScaleX.Header.MaxValue = stream.ReadFloat(); boneChannel.ScaleX.Header.MinValue = stream.ReadFloat(); if (frameCnt > 255) { keyframeCnt = boneChannel.ScaleX.Header.KeyframeCount_16bits = stream.ReadUInt16(); } else { keyframeCnt = boneChannel.ScaleX.Header.KeyframeCount_8bits = (byte)stream.ReadByte(); } if (keyframeCnt != 1) { boneChannel.ScaleX.Keyframes = new List<KeyframeEntry>(); for (ushort z = 0; z < keyframeCnt; z++) { KeyframeEntry ent = new KeyframeEntry(); if (keyframeCnt == frameCnt) { ent.FrameID_16bits = z; ent.Value = stream.ReadUInt16(); boneChannel.ScaleX.Keyframes.Add(ent); } else { if (frameCnt > 255) { ent.FrameID_16bits = stream.ReadUInt16(); } else { ent.FrameID_8bits = (byte)stream.ReadByte(); } ent.Value = stream.ReadUInt16(); boneChannel.ScaleX.Keyframes.Add(ent); } } } } if (flg.ScaleY) { ushort keyframeCnt = 0; boneChannel.ScaleY = new AnimationData(); boneChannel.ScaleY.Header = new ChannelHeader(); boneChannel.ScaleY.Header.MaxValue = stream.ReadFloat(); boneChannel.ScaleY.Header.MinValue = stream.ReadFloat(); if (frameCnt > 255) { keyframeCnt = boneChannel.ScaleY.Header.KeyframeCount_16bits = stream.ReadUInt16(); } else { keyframeCnt = boneChannel.ScaleY.Header.KeyframeCount_8bits = (byte)stream.ReadByte(); } if (keyframeCnt != 1) { boneChannel.ScaleY.Keyframes = new List<KeyframeEntry>(); for (ushort z = 0; z < keyframeCnt; z++) { KeyframeEntry ent = new KeyframeEntry(); if (keyframeCnt == frameCnt) { ent.FrameID_16bits = z; ent.Value = stream.ReadUInt16(); boneChannel.ScaleY.Keyframes.Add(ent); } else { if (frameCnt > 255) { ent.FrameID_16bits = stream.ReadUInt16(); } else { ent.FrameID_8bits = (byte)stream.ReadByte(); } ent.Value = stream.ReadUInt16(); boneChannel.ScaleY.Keyframes.Add(ent); } } } } if (flg.ScaleZ) { ushort keyframeCnt = 0; boneChannel.ScaleZ = new AnimationData(); boneChannel.ScaleZ.Header = new ChannelHeader(); boneChannel.ScaleZ.Header.MaxValue = stream.ReadFloat(); boneChannel.ScaleZ.Header.MinValue = stream.ReadFloat(); if (frameCnt > 255) { keyframeCnt = boneChannel.ScaleZ.Header.KeyframeCount_16bits = stream.ReadUInt16(); } else { keyframeCnt = boneChannel.ScaleZ.Header.KeyframeCount_8bits = (byte)stream.ReadByte(); } if (keyframeCnt != 1) { boneChannel.ScaleZ.Keyframes = new List<KeyframeEntry>(); for (ushort z = 0; z < keyframeCnt; z++) { KeyframeEntry ent = new KeyframeEntry(); if (keyframeCnt == frameCnt) { ent.FrameID_16bits = z; ent.Value = stream.ReadUInt16(); boneChannel.ScaleZ.Keyframes.Add(ent); } else { if (frameCnt > 255) { ent.FrameID_16bits = stream.ReadUInt16(); } else { ent.FrameID_8bits = (byte)stream.ReadByte(); } ent.Value = stream.ReadUInt16(); boneChannel.ScaleZ.Keyframes.Add(ent); } } } } pam.animList[j].BoneChannels.Add(boneChannel); } } return pam; } } }
/* * 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.Collections; using System.Collections.Generic; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using LWAS.CustomControls; using LWAS.Extensible.Interfaces.Configuration; using LWAS.Extensible.Interfaces.DataBinding; using LWAS.Extensible.Interfaces.WebParts; using LWAS.Infrastructure; namespace LWAS.WebParts.Templating { public class ItemTemplate : TableTemplateBase { private static ItemTemplate _instance = new ItemTemplate(); public static ItemTemplate Instance { get { return ItemTemplate._instance; } } public override void Create(Control container, IConfigurationType config, ITemplatable templatable, IBinder binder, ITemplatingItem item, int itemIndex, WebPartManager manager) { if (null == container) { throw new ArgumentNullException("container"); } if (null == config) { throw new ArgumentNullException("config"); } if (!(config is IConfigurationSection)) { throw new ArgumentException("config must be an IConfigurationSection"); } IDictionary<string, IConfigurationElement> itemElements = (config as IConfigurationSection).Elements; Table table; if (container is Table) { table = (container as Table); } else { table = new Table(); } table.ApplyStyle(templatable.DetailsStyle); Panel statusPanel = new Panel(); HiddenField hiddenReadOnly = new HiddenField(); hiddenReadOnly.ID = itemIndex.ToString() + "-readOnly"; hiddenReadOnly.Value = item.IsReadOnly.ToString(); statusPanel.Controls.Add(hiddenReadOnly); HiddenField hiddenNew = new HiddenField(); hiddenNew.ID = itemIndex.ToString() + "-new"; hiddenNew.Value = item.IsNew.ToString(); statusPanel.Controls.Add(hiddenNew); HiddenField hiddenCurrent = new HiddenField(); hiddenCurrent.ID = itemIndex.ToString() + "-current"; hiddenCurrent.Value = item.IsCurrent.ToString(); statusPanel.Controls.Add(hiddenCurrent); HiddenField hiddenHasChanges = new HiddenField(); hiddenHasChanges.ID = itemIndex.ToString() + "-hasChanges"; hiddenHasChanges.Value = item.HasChanges.ToString(); statusPanel.Controls.Add(hiddenHasChanges); HiddenField hiddenIsValid = new HiddenField(); hiddenIsValid.ID = itemIndex.ToString() + "-isValid"; hiddenIsValid.Value = item.IsValid.ToString(); statusPanel.Controls.Add(hiddenIsValid); HiddenField hiddenInvalidMember = new HiddenField(); hiddenInvalidMember.ID = itemIndex.ToString() + "-invalidMember"; hiddenInvalidMember.Value = item.InvalidMember; statusPanel.Controls.Add(hiddenInvalidMember); if (null != item) { item.BoundControls.Clear(); } foreach (IConfigurationElement element in itemElements.Values) { if (!("selectors" == element.ConfigKey) && !("commanders" == element.ConfigKey) && !("filter" == element.ConfigKey) && !("header" == element.ConfigKey) && !("footer" == element.ConfigKey) && !("grouping" == element.ConfigKey) && !("totals" == element.ConfigKey)) { if (item.IsCurrent && !item.IsReadOnly) { this.DisplayItem(table, element, itemIndex.ToString(), binder, item, templatable.EditRowStyle, templatable.InvalidItemStyle, manager); } else { if (item.IsCurrent) { this.DisplayItem(table, element, itemIndex.ToString(), binder, item, templatable.SelectedRowStyle, templatable.InvalidItemStyle, manager); } else { if (itemIndex % 2 == 0) { this.DisplayItem(table, element, itemIndex.ToString(), binder, item, templatable.RowStyle, templatable.InvalidItemStyle, manager); } else { this.DisplayItem(table, element, itemIndex.ToString(), binder, item, templatable.AlternatingRowStyle, templatable.InvalidItemStyle, manager); } } } } } if (table.Rows.Count > 0) { if (!(table.Rows[0].Cells.Count > 0)) { TableCell firstcell = new TableCell(); firstcell.ID = table.Rows[0].ID + "firstcell"; table.Rows[0].Cells.Add(firstcell); } table.Rows[0].Cells[0].Controls.Add(statusPanel); } } public override void Extract(Control container, IConfigurationType config, ITemplatable templatable, IBinder binder, IEnumerable registry, ITemplatingItem item, int itemIndex, int itemsCount, WebPartManager manager) { if (null == container) { throw new ArgumentNullException("container"); } if (null == config) { throw new ArgumentNullException("config"); } if (!(config is IConfigurationSection)) { throw new ArgumentException("config must be an IConfigurationSection"); } if (!(registry is ITemplatingItemsCollection)) { throw new ArgumentException("registry must be ITemplatingItemsCollection"); } ITemplatingItemsCollection items = registry as ITemplatingItemsCollection; items.Clear(); IDictionary<string, IConfigurationElement> itemElements = (config as IConfigurationSection).Elements; for (int i = 0; i < itemsCount; i++) { item = new TemplatingItem(); Control hiddenReadOnly = ReflectionServices.FindControlEx(i.ToString() + "-readOnly", container); if (null != hiddenReadOnly) { bool isReadOnly = false; bool.TryParse(((HiddenField)hiddenReadOnly).Value, out isReadOnly); item.IsReadOnly = isReadOnly; } Control hiddenNew = ReflectionServices.FindControlEx(i.ToString() + "-new", container); if (null != hiddenNew) { bool isNew = false; bool.TryParse(((HiddenField)hiddenNew).Value, out isNew); item.IsNew = isNew; } Control hiddenCurrent = ReflectionServices.FindControlEx(i.ToString() + "-current", container); if (null != hiddenCurrent) { bool isCurrent = false; bool.TryParse(((HiddenField)hiddenCurrent).Value, out isCurrent); item.IsCurrent = isCurrent; } Control hiddenHasChanges = ReflectionServices.FindControlEx(i.ToString() + "-hasChanges", container); if (null != hiddenHasChanges) { bool hasChanges = false; bool.TryParse(((HiddenField)hiddenHasChanges).Value, out hasChanges); item.HasChanges = hasChanges; } Control hiddenIsValid = ReflectionServices.FindControlEx(i.ToString() + "-isValid", container); if (null != hiddenIsValid) { bool isValid = false; bool.TryParse(((HiddenField)hiddenIsValid).Value, out isValid); item.IsValid = isValid; } Control hiddenInvalidMember = ReflectionServices.FindControlEx(i.ToString() + "-invalidMember", container); if (null != hiddenInvalidMember) { item.InvalidMember = ((HiddenField)hiddenInvalidMember).Value; } this.PopulateItem(container, config, item, i.ToString()); items.Add(item); } } public virtual void PopulateItem(Control container, IConfigurationType config, ITemplatingItem item, string index) { if (null == container) { throw new ArgumentNullException("container"); } if (null == config) { throw new ArgumentNullException("config"); } if (!(config is IConfigurationSection)) { throw new ArgumentException("config must be an IConfigurationSection"); } item.Data = new Dictionary<string, object>(); Dictionary<string, object> data = item.Data as Dictionary<string, object>; IDictionary<string, IConfigurationElement> itemElements = (config as IConfigurationSection).Elements; foreach (IConfigurationElement element in itemElements.Values) { if (!("selectors" == element.ConfigKey) && !("commanders" == element.ConfigKey) && !("filter" == element.ConfigKey) && !("header" == element.ConfigKey) && !("footer" == element.ConfigKey)) { foreach (IConfigurationElement fieldElement in element.Elements.Values) { foreach (IConfigurationElement propertyElement in fieldElement.Elements.Values) { if (propertyElement.Attributes.ContainsKey("push")) { string propertyName = propertyElement.GetAttributeReference("member").Value.ToString(); string sourcePropertyName = propertyElement.GetAttributeReference("push").Value.ToString(); if (!data.ContainsKey(sourcePropertyName)) { data.Add(sourcePropertyName, null); } if (!string.IsNullOrEmpty(index)) { string id = string.Concat(new string[] { container.ID, "-", element.ConfigKey, "-", index, "-", fieldElement.ConfigKey, "-ctrl" }); Control fieldControl = ReflectionServices.FindControlEx(id, container); if (null != fieldControl) { object val = ReflectionServices.ExtractValue(fieldControl, propertyName); if (fieldControl is DateTextBox && val == null && propertyName == "Date") { val = ((DateTextBox)fieldControl).Text; } data[sourcePropertyName] = val; } } } } } } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Localization; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Localization; using OrchardCore.Data; using OrchardCore.DisplayManagement; using OrchardCore.DisplayManagement.Notify; using OrchardCore.Environment.Shell; using OrchardCore.Environment.Shell.Models; using OrchardCore.Modules; using OrchardCore.Navigation; using OrchardCore.Recipes.Services; using OrchardCore.Routing; using OrchardCore.Settings; using OrchardCore.Tenants.ViewModels; namespace OrchardCore.Tenants.Controllers { public class AdminController : Controller { private readonly IShellHost _shellHost; private readonly IShellSettingsManager _shellSettingsManager; private readonly IEnumerable<DatabaseProvider> _databaseProviders; private readonly IAuthorizationService _authorizationService; private readonly ShellSettings _currentShellSettings; private readonly IEnumerable<IRecipeHarvester> _recipeHarvesters; private readonly IDataProtectionProvider _dataProtectorProvider; private readonly IClock _clock; private readonly INotifier _notifier; private readonly ISiteService _siteService; private readonly dynamic New; private readonly IStringLocalizer S; private readonly IHtmlLocalizer H; public AdminController( IShellHost shellHost, IShellSettingsManager shellSettingsManager, IEnumerable<DatabaseProvider> databaseProviders, IAuthorizationService authorizationService, ShellSettings currentShellSettings, IEnumerable<IRecipeHarvester> recipeHarvesters, IDataProtectionProvider dataProtectorProvider, IClock clock, INotifier notifier, ISiteService siteService, IShapeFactory shapeFactory, IStringLocalizer<AdminController> stringLocalizer, IHtmlLocalizer<AdminController> htmlLocalizer) { _shellHost = shellHost; _authorizationService = authorizationService; _shellSettingsManager = shellSettingsManager; _databaseProviders = databaseProviders; _currentShellSettings = currentShellSettings; _dataProtectorProvider = dataProtectorProvider; _recipeHarvesters = recipeHarvesters; _clock = clock; _notifier = notifier; _siteService = siteService; New = shapeFactory; S = stringLocalizer; H = htmlLocalizer; } public async Task<IActionResult> Index(TenantIndexOptions options, PagerParameters pagerParameters) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants)) { return Forbid(); } if (!IsDefaultShell()) { return Forbid(); } var allSettings = _shellHost.GetAllSettings().OrderBy(s => s.Name); var dataProtector = _dataProtectorProvider.CreateProtector("Tokens").ToTimeLimitedDataProtector(); var siteSettings = await _siteService.GetSiteSettingsAsync(); var pager = new Pager(pagerParameters, siteSettings.PageSize); // default options if (options == null) { options = new TenantIndexOptions(); } var entries = allSettings.Select(x => { var entry = new ShellSettingsEntry { Description = x["Description"], Name = x.Name, ShellSettings = x, IsDefaultTenant = String.Equals(x.Name, ShellHelper.DefaultShellName, StringComparison.OrdinalIgnoreCase) }; if (x.State == TenantState.Uninitialized && !String.IsNullOrEmpty(x["Secret"])) { entry.Token = dataProtector.Protect(x["Secret"], _clock.UtcNow.Add(new TimeSpan(24, 0, 0))); } return entry; }).ToList(); if (!String.IsNullOrWhiteSpace(options.Search)) { entries = entries.Where(t => t.Name.IndexOf(options.Search, StringComparison.OrdinalIgnoreCase) > -1 || (t.ShellSettings != null && ((t.ShellSettings.RequestUrlHost != null && t.ShellSettings.RequestUrlHost.IndexOf(options.Search, StringComparison.OrdinalIgnoreCase) > -1) || (t.ShellSettings.RequestUrlPrefix != null && t.ShellSettings.RequestUrlPrefix.IndexOf(options.Search, StringComparison.OrdinalIgnoreCase) > -1)))).ToList(); } switch (options.Filter) { case TenantsFilter.Disabled: entries = entries.Where(t => t.ShellSettings.State == TenantState.Disabled).ToList(); break; case TenantsFilter.Running: entries = entries.Where(t => t.ShellSettings.State == TenantState.Running).ToList(); break; case TenantsFilter.Uninitialized: entries = entries.Where(t => t.ShellSettings.State == TenantState.Uninitialized).ToList(); break; } switch (options.OrderBy) { case TenantsOrder.Name: entries = entries.OrderBy(t => t.Name).ToList(); break; case TenantsOrder.State: entries = entries.OrderBy(t => t.ShellSettings?.State).ToList(); break; default: entries = entries.OrderByDescending(t => t.Name).ToList(); break; } var count = entries.Count(); var results = entries .Skip(pager.GetStartIndex()) .Take(pager.PageSize).ToList(); // Maintain previous route data when generating page links var routeData = new RouteData(); routeData.Values.Add("Options.Filter", options.Filter); routeData.Values.Add("Options.Search", options.Search); routeData.Values.Add("Options.OrderBy", options.OrderBy); var pagerShape = (await New.Pager(pager)).TotalItemCount(count).RouteData(routeData); var model = new AdminIndexViewModel { ShellSettingsEntries = results, Options = options, Pager = pagerShape }; // We populate the SelectLists model.Options.TenantsStates = new List<SelectListItem>() { new SelectListItem() { Text = S["All states"], Value = nameof(TenantsFilter.All) }, new SelectListItem() { Text = S["Running"], Value = nameof(TenantsFilter.Running) }, new SelectListItem() { Text = S["Disabled"], Value = nameof(TenantsFilter.Disabled) }, new SelectListItem() { Text = S["Uninitialized"], Value = nameof(TenantsFilter.Uninitialized) } }; model.Options.TenantsSorts = new List<SelectListItem>() { new SelectListItem() { Text = S["Name"], Value = nameof(TenantsOrder.Name) }, new SelectListItem() { Text = S["State"], Value = nameof(TenantsOrder.State) } }; model.Options.TenantsBulkAction = new List<SelectListItem>() { new SelectListItem() { Text = S["Disable"], Value = nameof(TenantsBulkAction.Disable) }, new SelectListItem() { Text = S["Enable"], Value = nameof(TenantsBulkAction.Enable) } }; return View(model); } [HttpPost, ActionName("Index")] [FormValueRequired("submit.Filter")] public ActionResult IndexFilterPOST(AdminIndexViewModel model) { return RedirectToAction("Index", new RouteValueDictionary { { "Options.Filter", model.Options.Filter }, { "Options.OrderBy", model.Options.OrderBy }, { "Options.Search", model.Options.Search }, { "Options.TenantsStates", model.Options.TenantsStates } }); } [HttpPost] [FormValueRequired("submit.BulkAction")] public async Task<IActionResult> Index(BulkActionViewModel model) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants)) { return Forbid(); } if (!IsDefaultShell()) { return Forbid(); } var allSettings = _shellHost.GetAllSettings(); foreach (var tenantName in model.TenantNames ?? Enumerable.Empty<string>()) { var shellSettings = allSettings .Where(x => String.Equals(x.Name, tenantName, StringComparison.OrdinalIgnoreCase)) .FirstOrDefault(); if (shellSettings == null) { break; } switch (model.BulkAction.ToString()) { case "Disable": if (String.Equals(shellSettings.Name, ShellHelper.DefaultShellName, StringComparison.OrdinalIgnoreCase)) { _notifier.Warning(H["You cannot disable the default tenant."]); } else if (shellSettings.State != TenantState.Running) { _notifier.Warning(H["The tenant '{0}' is already disabled.", shellSettings.Name]); } else { shellSettings.State = TenantState.Disabled; await _shellHost.UpdateShellSettingsAsync(shellSettings); } break; case "Enable": if (shellSettings.State != TenantState.Disabled) { _notifier.Warning(H["The tenant '{0}' is already enabled.", shellSettings.Name]); } else { shellSettings.State = TenantState.Running; await _shellHost.UpdateShellSettingsAsync(shellSettings); } break; default: break; } } return RedirectToAction(nameof(Index)); } public async Task<IActionResult> Create() { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants)) { return Forbid(); } if (!IsDefaultShell()) { return Forbid(); } var recipeCollections = await Task.WhenAll(_recipeHarvesters.Select(x => x.HarvestRecipesAsync())); var recipes = recipeCollections.SelectMany(x => x).Where(x => x.IsSetupRecipe).ToArray(); // Creates a default shell settings based on the configuration. var shellSettings = _shellSettingsManager.CreateDefaultSettings(); var model = new EditTenantViewModel { Recipes = recipes, RequestUrlHost = shellSettings.RequestUrlHost, RequestUrlPrefix = shellSettings.RequestUrlPrefix, DatabaseProvider = shellSettings["DatabaseProvider"], TablePrefix = shellSettings["TablePrefix"], ConnectionString = shellSettings["ConnectionString"], RecipeName = shellSettings["RecipeName"] }; model.Recipes = recipes; return View(model); } [HttpPost] public async Task<IActionResult> Create(EditTenantViewModel model) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants)) { return Forbid(); } if (!IsDefaultShell()) { return Forbid(); } if (ModelState.IsValid) { ValidateViewModel(model, true); } if (ModelState.IsValid) { // Creates a default shell settings based on the configuration. var shellSettings = _shellSettingsManager.CreateDefaultSettings(); shellSettings.Name = model.Name; shellSettings.RequestUrlHost = model.RequestUrlHost; shellSettings.RequestUrlPrefix = model.RequestUrlPrefix; shellSettings.State = TenantState.Uninitialized; shellSettings["Description"] = model.Description; shellSettings["ConnectionString"] = model.ConnectionString; shellSettings["TablePrefix"] = model.TablePrefix; shellSettings["DatabaseProvider"] = model.DatabaseProvider; shellSettings["Secret"] = Guid.NewGuid().ToString(); shellSettings["RecipeName"] = model.RecipeName; await _shellHost.UpdateShellSettingsAsync(shellSettings); return RedirectToAction(nameof(Index)); } var recipeCollections = await Task.WhenAll(_recipeHarvesters.Select(x => x.HarvestRecipesAsync())); var recipes = recipeCollections.SelectMany(x => x).Where(x => x.IsSetupRecipe).ToArray(); model.Recipes = recipes; // If we got this far, something failed, redisplay form return View(model); } public async Task<IActionResult> Edit(string id) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants)) { return Forbid(); } if (!IsDefaultShell()) { return Forbid(); } var shellSettings = _shellHost.GetAllSettings() .Where(x => String.Equals(x.Name, id, StringComparison.OrdinalIgnoreCase)) .FirstOrDefault(); if (shellSettings == null) { return NotFound(); } var model = new EditTenantViewModel { Description = shellSettings["Description"], Name = shellSettings.Name, RequestUrlHost = shellSettings.RequestUrlHost, RequestUrlPrefix = shellSettings.RequestUrlPrefix, }; // The user can change the 'preset' database information only if the // tenant has not been initialized yet if (shellSettings.State == TenantState.Uninitialized) { var recipeCollections = await Task.WhenAll(_recipeHarvesters.Select(x => x.HarvestRecipesAsync())); var recipes = recipeCollections.SelectMany(x => x).Where(x => x.IsSetupRecipe).ToArray(); model.Recipes = recipes; model.DatabaseProvider = shellSettings["DatabaseProvider"]; model.TablePrefix = shellSettings["TablePrefix"]; model.ConnectionString = shellSettings["ConnectionString"]; model.RecipeName = shellSettings["RecipeName"]; model.CanSetDatabasePresets = true; } return View(model); } [HttpPost] public async Task<IActionResult> Edit(EditTenantViewModel model) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants)) { return Forbid(); } if (!IsDefaultShell()) { return Forbid(); } if (ModelState.IsValid) { ValidateViewModel(model, false); } var shellSettings = _shellHost.GetAllSettings() .Where(x => String.Equals(x.Name, model.Name, StringComparison.OrdinalIgnoreCase)) .FirstOrDefault(); if (shellSettings == null) { return NotFound(); } if (ModelState.IsValid) { shellSettings["Description"] = model.Description; shellSettings.RequestUrlPrefix = model.RequestUrlPrefix; shellSettings.RequestUrlHost = model.RequestUrlHost; // The user can change the 'preset' database information only if the // tenant has not been initialized yet if (shellSettings.State == TenantState.Uninitialized) { shellSettings["DatabaseProvider"] = model.DatabaseProvider; shellSettings["TablePrefix"] = model.TablePrefix; shellSettings["ConnectionString"] = model.ConnectionString; shellSettings["RecipeName"] = model.RecipeName; shellSettings["Secret"] = Guid.NewGuid().ToString(); } await _shellHost.UpdateShellSettingsAsync(shellSettings); return RedirectToAction(nameof(Index)); } // The user can change the 'preset' database information only if the // tenant has not been initialized yet if (shellSettings.State == TenantState.Uninitialized) { model.DatabaseProvider = shellSettings["DatabaseProvider"]; model.TablePrefix = shellSettings["TablePrefix"]; model.ConnectionString = shellSettings["ConnectionString"]; model.RecipeName = shellSettings["RecipeName"]; model.CanSetDatabasePresets = true; } var recipeCollections = await Task.WhenAll(_recipeHarvesters.Select(x => x.HarvestRecipesAsync())); var recipes = recipeCollections.SelectMany(x => x).Where(x => x.IsSetupRecipe).ToArray(); model.Recipes = recipes; // If we got this far, something failed, redisplay form return View(model); } [HttpPost] public async Task<IActionResult> Disable(string id) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants)) { return Forbid(); } if (!IsDefaultShell()) { return Forbid(); } var shellSettings = _shellHost.GetAllSettings() .Where(s => String.Equals(s.Name, id, StringComparison.OrdinalIgnoreCase)) .FirstOrDefault(); if (shellSettings == null) { return NotFound(); } if (String.Equals(shellSettings.Name, ShellHelper.DefaultShellName, StringComparison.OrdinalIgnoreCase)) { _notifier.Error(H["You cannot disable the default tenant."]); return RedirectToAction(nameof(Index)); } if (shellSettings.State != TenantState.Running) { _notifier.Error(H["You can only disable an Enabled tenant."]); return RedirectToAction(nameof(Index)); } shellSettings.State = TenantState.Disabled; await _shellHost.UpdateShellSettingsAsync(shellSettings); return RedirectToAction(nameof(Index)); } [HttpPost] public async Task<IActionResult> Enable(string id) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants)) { return Forbid(); } if (!IsDefaultShell()) { return Forbid(); } var shellSettings = _shellHost.GetAllSettings() .Where(x => String.Equals(x.Name, id, StringComparison.OrdinalIgnoreCase)) .FirstOrDefault(); if (shellSettings == null) { return NotFound(); } if (shellSettings.State != TenantState.Disabled) { _notifier.Error(H["You can only enable a Disabled tenant."]); } shellSettings.State = TenantState.Running; await _shellHost.UpdateShellSettingsAsync(shellSettings); return RedirectToAction(nameof(Index)); } [HttpPost] public async Task<IActionResult> Reload(string id) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants)) { return Forbid(); } if (!IsDefaultShell()) { return Forbid(); } var shellSettings = _shellHost.GetAllSettings() .Where(x => String.Equals(x.Name, id, StringComparison.OrdinalIgnoreCase)) .FirstOrDefault(); if (shellSettings == null) { return NotFound(); } // Generating routes can fail while the tenant is recycled as routes can use services. // It could be fixed by waiting for the next request or the end of the current one // to actually release the tenant. Right now we render the url before recycling the tenant. var redirectUrl = Url.Action(nameof(Index)); await _shellHost.ReloadShellContextAsync(shellSettings); return Redirect(redirectUrl); } private void ValidateViewModel(EditTenantViewModel model, bool newTenant) { var selectedProvider = _databaseProviders.FirstOrDefault(x => x.Value == model.DatabaseProvider); if (selectedProvider != null && selectedProvider.HasConnectionString && String.IsNullOrWhiteSpace(model.ConnectionString)) { ModelState.AddModelError(nameof(EditTenantViewModel.ConnectionString), S["The connection string is mandatory for this provider."]); } if (String.IsNullOrWhiteSpace(model.Name)) { ModelState.AddModelError(nameof(EditTenantViewModel.Name), S["The tenant name is mandatory."]); } var allSettings = _shellHost.GetAllSettings(); if (newTenant && allSettings.Any(tenant => String.Equals(tenant.Name, model.Name, StringComparison.OrdinalIgnoreCase))) { ModelState.AddModelError(nameof(EditTenantViewModel.Name), S["A tenant with the same name already exists.", model.Name]); } if (!String.IsNullOrEmpty(model.Name) && !Regex.IsMatch(model.Name, @"^\w+$")) { ModelState.AddModelError(nameof(EditTenantViewModel.Name), S["Invalid tenant name. Must contain characters only and no spaces."]); } if (!IsDefaultShell() && String.IsNullOrWhiteSpace(model.RequestUrlHost) && String.IsNullOrWhiteSpace(model.RequestUrlPrefix)) { ModelState.AddModelError(nameof(EditTenantViewModel.RequestUrlPrefix), S["Host and url prefix can not be empty at the same time."]); } var allOtherShells = allSettings.Where(tenant => !string.Equals(tenant.Name, model.Name, StringComparison.OrdinalIgnoreCase)); if (allOtherShells.Any(tenant => String.Equals(tenant.RequestUrlPrefix, model.RequestUrlPrefix?.Trim(), StringComparison.OrdinalIgnoreCase) && String.Equals(tenant.RequestUrlHost, model.RequestUrlHost, StringComparison.OrdinalIgnoreCase))) { ModelState.AddModelError(nameof(EditTenantViewModel.RequestUrlPrefix), S["A tenant with the same host and prefix already exists.", model.Name]); } if (!String.IsNullOrWhiteSpace(model.RequestUrlPrefix)) { if (model.RequestUrlPrefix.Contains('/')) { ModelState.AddModelError(nameof(EditTenantViewModel.RequestUrlPrefix), S["The url prefix can not contain more than one segment."]); } } } private bool IsDefaultShell() { return String.Equals(_currentShellSettings.Name, ShellHelper.DefaultShellName, StringComparison.OrdinalIgnoreCase); } } }
// StreamManipulator.cs // // Copyright (C) 2001 Mike Krueger // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // 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; namespace PdfSharp.SharpZipLib.Zip.Compression.Streams { /// <summary> /// This class allows us to retrieve a specified number of bits from /// the input buffer, as well as copy big byte blocks. /// /// It uses an int buffer to store up to 31 bits for direct /// manipulation. This guarantees that we can get at least 16 bits, /// but we only need at most 15, so this is all safe. /// /// There are some optimizations in this class, for example, you must /// never peek more than 8 bits more than needed, and you must first /// peek bits before you may drop them. This is not a general purpose /// class but optimized for the behaviour of the Inflater. /// /// Authors of the original java version: John Leuner, Jochen Hoenicke /// </summary> internal class StreamManipulator { #region Constructors /// <summary> /// Constructs a default StreamManipulator with all buffers empty /// </summary> public StreamManipulator() { } #endregion /// <summary> /// Get the next sequence of bits but don't increase input pointer. bitCount must be /// less or equal 16 and if this call succeeds, you must drop /// at least n - 8 bits in the next call. /// </summary> /// <param name="bitCount">The number of bits to peek.</param> /// <returns> /// the value of the bits, or -1 if not enough bits available. */ /// </returns> public int PeekBits(int bitCount) { if (bitsInBuffer_ < bitCount) { if (windowStart_ == windowEnd_) { return -1; // ok } buffer_ |= (uint)((window_[windowStart_++] & 0xff | (window_[windowStart_++] & 0xff) << 8) << bitsInBuffer_); bitsInBuffer_ += 16; } return (int)(buffer_ & ((1 << bitCount) - 1)); } /// <summary> /// Drops the next n bits from the input. You should have called PeekBits /// with a bigger or equal n before, to make sure that enough bits are in /// the bit buffer. /// </summary> /// <param name="bitCount">The number of bits to drop.</param> public void DropBits(int bitCount) { buffer_ >>= bitCount; bitsInBuffer_ -= bitCount; } /// <summary> /// Gets the next n bits and increases input pointer. This is equivalent /// to <see cref="PeekBits"/> followed by <see cref="DropBits"/>, except for correct error handling. /// </summary> /// <param name="bitCount">The number of bits to retrieve.</param> /// <returns> /// the value of the bits, or -1 if not enough bits available. /// </returns> public int GetBits(int bitCount) { int bits = PeekBits(bitCount); if (bits >= 0) { DropBits(bitCount); } return bits; } /// <summary> /// Gets the number of bits available in the bit buffer. This must be /// only called when a previous PeekBits() returned -1. /// </summary> /// <returns> /// the number of bits available. /// </returns> public int AvailableBits { get { return bitsInBuffer_; } } /// <summary> /// Gets the number of bytes available. /// </summary> /// <returns> /// The number of bytes available. /// </returns> public int AvailableBytes { get { return windowEnd_ - windowStart_ + (bitsInBuffer_ >> 3); } } /// <summary> /// Skips to the next byte boundary. /// </summary> public void SkipToByteBoundary() { buffer_ >>= (bitsInBuffer_ & 7); bitsInBuffer_ &= ~7; } /// <summary> /// Returns true when SetInput can be called /// </summary> public bool IsNeedingInput { get { return windowStart_ == windowEnd_; } } /// <summary> /// Copies bytes from input buffer to output buffer starting /// at output[offset]. You have to make sure, that the buffer is /// byte aligned. If not enough bytes are available, copies fewer /// bytes. /// </summary> /// <param name="output"> /// The buffer to copy bytes to. /// </param> /// <param name="offset"> /// The offset in the buffer at which copying starts /// </param> /// <param name="length"> /// The length to copy, 0 is allowed. /// </param> /// <returns> /// The number of bytes copied, 0 if no bytes were available. /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// Length is less than zero /// </exception> /// <exception cref="InvalidOperationException"> /// Bit buffer isnt byte aligned /// </exception> public int CopyBytes(byte[] output, int offset, int length) { if (length < 0) { throw new ArgumentOutOfRangeException("length"); } if ((bitsInBuffer_ & 7) != 0) { // bits_in_buffer may only be 0 or a multiple of 8 throw new InvalidOperationException("Bit buffer is not byte aligned!"); } int count = 0; while ((bitsInBuffer_ > 0) && (length > 0)) { output[offset++] = (byte)buffer_; buffer_ >>= 8; bitsInBuffer_ -= 8; length--; count++; } if (length == 0) { return count; } int avail = windowEnd_ - windowStart_; if (length > avail) { length = avail; } System.Array.Copy(window_, windowStart_, output, offset, length); windowStart_ += length; if (((windowStart_ - windowEnd_) & 1) != 0) { // We always want an even number of bytes in input, see peekBits buffer_ = (uint)(window_[windowStart_++] & 0xff); bitsInBuffer_ = 8; } return count + length; } /// <summary> /// Resets state and empties internal buffers /// </summary> public void Reset() { buffer_ = 0; windowStart_ = windowEnd_ = bitsInBuffer_ = 0; } /// <summary> /// Add more input for consumption. /// Only call when IsNeedingInput returns true /// </summary> /// <param name="buffer">data to be input</param> /// <param name="offset">offset of first byte of input</param> /// <param name="count">number of bytes of input to add.</param> public void SetInput(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("offset"); #else throw new ArgumentOutOfRangeException("offset", "Cannot be negative"); #endif } if (count < 0) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("count"); #else throw new ArgumentOutOfRangeException("count", "Cannot be negative"); #endif } if (windowStart_ < windowEnd_) { throw new InvalidOperationException("Old input was not completely processed"); } int end = offset + count; // We want to throw an ArrayIndexOutOfBoundsException early. // Note the check also handles integer wrap around. if ((offset > end) || (end > buffer.Length)) { throw new ArgumentOutOfRangeException("count"); } if ((count & 1) != 0) { // We always want an even number of bytes in input, see PeekBits buffer_ |= (uint)((buffer[offset++] & 0xff) << bitsInBuffer_); bitsInBuffer_ += 8; } window_ = buffer; windowStart_ = offset; windowEnd_ = end; } #region Instance Fields private byte[] window_; private int windowStart_; private int windowEnd_; private uint buffer_; private int bitsInBuffer_; #endregion } }
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.IO; using System.Text; using Encog.App.Analyst.CSV.Basic; using Encog.App.Analyst.Missing; using Encog.App.Analyst.Script.Normalize; using Encog.App.Analyst.Util; using Encog.App.Quant; using Encog.Util.Arrayutil; using Encog.Util.CSV; using Encog.Util.Logging; namespace Encog.App.Analyst.CSV.Normalize { /// <summary> /// Normalize, or denormalize, a CSV file. /// </summary> public class AnalystNormalizeCSV : BasicFile { /// <summary> /// The analyst to use. /// </summary> private EncogAnalyst _analyst; /// <summary> /// THe headers. /// </summary> private CSVHeaders _analystHeaders; /// <summary> /// Used to process time series. /// </summary> private TimeSeriesUtil _series; /// <summary> /// Extract fields from a file into a numeric array for machine learning. /// </summary> /// <param name="analyst">The analyst to use.</param> /// <param name="headers">The headers for the input data.</param> /// <param name="csv">The CSV that holds the input data.</param> /// <param name="outputLength">The length of the returned array.</param> /// <param name="skipOutput">True if the output should be skipped.</param> /// <returns>The encoded data.</returns> public static double[] ExtractFields(EncogAnalyst analyst, CSVHeaders headers, ReadCSV csv, int outputLength, bool skipOutput) { var output = new double[outputLength]; int outputIndex = 0; foreach (AnalystField stat in analyst.Script.Normalize.NormalizedFields) { stat.Init(); if (stat.Action == NormalizationAction.Ignore) { continue; } if (stat.Output && skipOutput) { continue; } int index = headers.Find(stat.Name); String str = csv.Get(index); // is this an unknown value? if (str.Equals("?") || str.Length == 0) { IHandleMissingValues handler = analyst.Script.Normalize.MissingValues; double[] d = handler.HandleMissing(analyst, stat); // should we skip the entire row if (d == null) { return null; } // copy the returned values in place of the missing values for (int i = 0; i < d.Length; i++) { output[outputIndex++] = d[i]; } } else { // known value if (stat.Action == NormalizationAction.Normalize) { double d = csv.Format.Parse(str.Trim()); d = stat.Normalize(d); output[outputIndex++] = d; } else if (stat.Action == NormalizationAction.PassThrough) { double d = csv.Format.Parse(str); output[outputIndex++] = d; } else { double[] d = stat.Encode(str.Trim()); foreach (double element in d) { output[outputIndex++] = element; } } } } return output; } /// <summary> /// Analyze the file. /// </summary> /// <param name="inputFilename">The input file.</param> /// <param name="expectInputHeaders">True, if input headers are present.</param> /// <param name="inputFormat">The format.</param> /// <param name="theAnalyst">The analyst to use.</param> public void Analyze(FileInfo inputFilename, bool expectInputHeaders, CSVFormat inputFormat, EncogAnalyst theAnalyst) { InputFilename = inputFilename; Format = inputFormat; ExpectInputHeaders = expectInputHeaders; _analyst = theAnalyst; Analyzed = true; _analystHeaders = new CSVHeaders(inputFilename, expectInputHeaders, inputFormat); foreach (AnalystField field in _analyst.Script.Normalize.NormalizedFields) { field.Init(); } _series = new TimeSeriesUtil(_analyst, true, _analystHeaders.Headers); } /// <summary> /// Normalize the input file. Write to the specified file. /// </summary> /// <param name="file">The file to write to.</param> public void Normalize(FileInfo file) { if (_analyst == null) { throw new EncogError( "Can't normalize yet, file has not been analyzed."); } ReadCSV csv = null; StreamWriter tw = null; try { csv = new ReadCSV(InputFilename.ToString(), ExpectInputHeaders, Format); file.Delete(); tw = new StreamWriter(file.OpenWrite()); // write headers, if needed if (ProduceOutputHeaders) { WriteHeaders(tw); } ResetStatus(); int outputLength = _analyst.DetermineTotalColumns(); // write file contents while (csv.Next() && !ShouldStop()) { UpdateStatus(false); double[] output = ExtractFields( _analyst, _analystHeaders, csv, outputLength, false); if (_series.TotalDepth > 1) { output = _series.Process(output); } if (output != null) { var line = new StringBuilder(); NumberList.ToList(Format, line, output); tw.WriteLine(line); } } } catch (IOException e) { throw new QuantError(e); } finally { ReportDone(false); if (csv != null) { try { csv.Close(); } catch (Exception ex) { EncogLogging.Log(ex); } } if (tw != null) { try { tw.Close(); } catch (Exception ex) { EncogLogging.Log(ex); } } } } /// <summary> /// Set the source file. This is useful if you want to use pre-existing stats /// to normalize something and skip the analyze step. /// </summary> /// <param name="file">The file to use.</param> /// <param name="headers">True, if headers are to be expected.</param> /// <param name="format">The format of the CSV file.</param> public void SetSourceFile(FileInfo file, bool headers, CSVFormat format) { InputFilename = file; ExpectInputHeaders = headers; Format = format; } /// <summary> /// Write the headers. /// </summary> /// <param name="tw">The output stream.</param> private void WriteHeaders(StreamWriter tw) { var line = new StringBuilder(); foreach (AnalystField stat in _analyst.Script.Normalize.NormalizedFields) { int needed = stat.ColumnsNeeded; for (int i = 0; i < needed; i++) { AppendSeparator(line, Format); line.Append('\"'); line.Append(CSVHeaders.TagColumn(stat.Name, i, stat.TimeSlice, needed > 1)); line.Append('\"'); } } tw.WriteLine(line.ToString()); } } }
using UnityEngine; using System.Collections; public class GameController : MonoBehaviour { ///////////////////////////////////////////////////////////////////////////// // Main Game Logic ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // Configuration ////////////////////////////////////////////////////////////////////////// public GUISkin skin; public int pointsPerClick = 100; public float scoreMultiplier = 1.1f; public int lives = 3; ////////////////////////////////////////////////////////////////////////// // Game State ////////////////////////////////////////////////////////////////////////// private int bestStreak = 0, streak = 0, score = 0, livesLeft = 0; private bool newbestStreak = false, isStarted = false, isPaused = false; ////////////////////////////////////////////////////////////////////////// // Setup Code ////////////////////////////////////////////////////////////////////////// public void Awake() { useGUILayout = false; Time.timeScale = 0f; isStarted = false; isPaused = false; livesLeft = lives; score = 0; bestStreak = 0; streak = 0; } ////////////////////////////////////////////////////////////////////////// // External API ////////////////////////////////////////////////////////////////////////// public static GameController Instance { get { return ((GameController)GameObject.FindObjectOfType(typeof(GameController))).GetComponent<GameController>(); } } public bool IsStarted { get { return isStarted; } } public bool IsPaused { get { return isPaused; } } public void AddClick() { if(!enabled) return; if(!isStarted) return; streak++; if(streak > bestStreak) { bestStreak = streak; newbestStreak = true; } score += (int)(pointsPerClick * Mathf.Pow(scoreMultiplier, (streak - 1))); } public bool PlayerFailsSoHard() { if(!enabled) return false; streak = 0; if(newbestStreak) { // TODO: Some sort of award / recognition... } livesLeft--; if(livesLeft <= 0) { GetComponent<GameOverScreen>().Trigger(bestStreak, score); return true; } return false; } public void StartGame() { isStarted = true; Time.timeScale = 1f; } public void TogglePause() { isPaused = !isPaused; if(isPaused) Time.timeScale = 0f; else Time.timeScale = 1f; } ///////////////////////////////////////////////////////////////////////////// // Main Game GUI ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // Shared Caches ////////////////////////////////////////////////////////////////////////// private GUIStyle window = null, button = null, label = null, boldLabel = null, tightLabel = null, boldTightLabel = null; private GUISkin cachedSkin = null; private Color baseContentColor, baseBackgroundColor; ////////////////////////////////////////////////////////////////////////// // Input Handling ////////////////////////////////////////////////////////////////////////// public void Update() { if(isStarted) { if(Input.GetKeyDown(KeyCode.P)) TogglePause(); } else { if(Input.GetKeyDown(KeyCode.G)) StartGame(); } } ////////////////////////////////////////////////////////////////////////// // Instructions Window ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Local Caches ////////////////////////////////////////////////////////////////////// private int sWidth = 0, sHeight = 0; ////////////////////////////////////////////////////////////////////// // Internal State ////////////////////////////////////////////////////////////////////// private Vector2 scrollPos = Vector2.zero; private Rect windowRect = new Rect(0, 0, 370, 280); ////////////////////////////////////////////////////////////////////// // Static Configuration ////////////////////////////////////////////////////////////////////// private static Rect shortcutsRect = new Rect(10f, 20f, 350f, 36f), instructionsRect = new Rect(10f, 80f, 350f, 47f), playButtonRect = new Rect(10f, 151f, 350f, 21f), changesTitleRect = new Rect(10f, 196f, 350f, 21f), changesViewRect = new Rect(10f, 221f, 350f, 49f), changelogRect = new Rect(4f, 4f, 326f, 171f); private static GUIContent instructionsTitle = new GUIContent("How to Play..."), shortcutsMessage = new GUIContent("If you have trouble with keyboard shortcuts, right-click and choose full-screen!"), instructionsMessage = new GUIContent("Keep the ball in the air by clicking on it. You lose a life every time it hits the ground, and you get bonus points the more consecutive clicks you land."), playButton = new GUIContent("Ready to play? [G]o!"), changesTitle = new GUIContent("Changes:"), changelog = new GUIContent( "v1.1, 2012-12-16:\n" + " - Fix for inverted view on Windows.\n" + " - Visual tweaks for score window.\n" + " - Visual tweaks for SSAO, and bloom.\n" + " - Improve keyboard input handling.\n" + " - Show score panel before game begins.\n" + " - Add control panel for enabling/disabling various visual effects.\n" + "\n" + "v1.0, 2012-12-06:\n" + " - Initial version." ); private static Color instructionsBackgroundColor = new Color(1f, 0.75f, 0f) * 2f, instructionsContentColor = new Color(1f, 0.75f, 0f); ////////////////////////////////////////////////////////////////////// // Code ////////////////////////////////////////////////////////////////////// private void ShowInstructions() { if(sWidth != Screen.width || sHeight != Screen.height) { sWidth = Screen.width; sHeight = Screen.height; float w = windowRect.width, h = windowRect.height; windowRect.xMin = (sWidth - windowRect.width) / 2; windowRect.xMax = windowRect.xMin + w; windowRect.yMin = (sHeight - windowRect.height) / 2; windowRect.yMax = windowRect.yMin + h; } GUI.backgroundColor = instructionsBackgroundColor; GUI.contentColor = instructionsContentColor; GUI.BeginGroup(windowRect, instructionsTitle, window); GUI.Label(shortcutsRect, shortcutsMessage, boldLabel); GUI.Label(instructionsRect, instructionsMessage, tightLabel); if(GUI.Button(playButtonRect, playButton, button)) { StartGame(); } GUI.Label(changesTitleRect, changesTitle, label); scrollPos = GUI.BeginScrollView(changesViewRect, scrollPos, changelogRect); GUI.Label(changelogRect, changelog, label); GUI.EndScrollView(); GUI.EndGroup(); // Superfluous since we set it explicitly just after calling this method. //GUI.backgroundColor = baseBackgroundColor; //GUI.contentColor = baseContentColor; } ////////////////////////////////////////////////////////////////////////// // Main Game Window ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Local Caches ////////////////////////////////////////////////////////////////////// private int scoreCached = -1, streakCached = -1, bestStreakCached = -1, livesLeftCached = -1; private GUIContent scoreValue = new GUIContent(""), streakValue = new GUIContent(""), bestStreakValue = new GUIContent(""), livesLeftValue = new GUIContent(""); ////////////////////////////////////////////////////////////////////// // Static Configuration ////////////////////////////////////////////////////////////////////// private const float lineHeight = 17f, lineIncrement = 19f, labelWidth = 76f, labelLeft = 10f, valueWidth = 35f, valueLeft = 140f - valueWidth, initialHeight = 20f; private static Rect mainWindowRect = new Rect(5, 5, 150, 130), scoreLabelRect = new Rect(labelLeft, initialHeight + 0*lineIncrement, labelWidth, lineHeight), scoreValueRect = new Rect(valueLeft, initialHeight + 0*lineIncrement, valueWidth, lineHeight), streakLabelRect = new Rect(labelLeft, initialHeight + 1*lineIncrement, labelWidth, lineHeight), streakValueRect = new Rect(valueLeft, initialHeight + 1*lineIncrement, valueWidth, lineHeight), bestLabelRect = new Rect(labelLeft, initialHeight + 2*lineIncrement, labelWidth, lineHeight), bestValueRect = new Rect(valueLeft, initialHeight + 2*lineIncrement, valueWidth, lineHeight), livesLabelRect = new Rect(labelLeft, initialHeight + 3*lineIncrement, labelWidth, lineHeight), livesValueRect = new Rect(valueLeft, initialHeight + 3*lineIncrement, valueWidth, lineHeight), pauseButtonRect = new Rect(labelLeft, initialHeight + 4*lineIncrement + 2, 130f, 21f); private static GUIContent windowTitle = new GUIContent("BounceBouncy v1.1"), scoreLabel = new GUIContent("Score:"), streakLabel = new GUIContent("Clicks:"), bestStreakLabel = new GUIContent("Best Streak:"), livesLeftLabel = new GUIContent("Lives Left:"), pauseLabel = new GUIContent("[P]ause"), unpauseLabel = new GUIContent("Un[p]ause"); private static Color mainWindowBackgroundColor = Color.magenta, mainWindowContentColor = (((Vector4)Color.magenta) + ((Vector4)Color.red)) * 0.5f; ////////////////////////////////////////////////////////////////////// // Code ////////////////////////////////////////////////////////////////////// public void OnGUI() { if(skin != cachedSkin) { cachedSkin = skin; window = skin.window; button = skin.button; label = skin.label; boldLabel = skin.GetStyle("BoldLabel"); tightLabel = skin.GetStyle("TightLabel"); boldTightLabel = skin.GetStyle("BoldTightLabel"); baseContentColor = GUI.contentColor; baseBackgroundColor = GUI.backgroundColor; } if(score != scoreCached) { scoreCached = score; scoreValue.text = score.ToString(); } if(streak != streakCached) { streakCached = streak; streakValue.text = streak.ToString(); } if(bestStreak != bestStreakCached) { bestStreakCached = bestStreak; bestStreakValue.text = bestStreak.ToString(); } if(livesLeft != livesLeftCached) { livesLeftCached = livesLeft; livesLeftValue.text = livesLeft.ToString(); } if(!isStarted) { ShowInstructions(); } GUI.backgroundColor = mainWindowBackgroundColor; GUI.contentColor = mainWindowContentColor; GUI.BeginGroup(mainWindowRect, windowTitle, window); GUI.Label(scoreLabelRect, scoreLabel, boldTightLabel); GUI.Label(scoreValueRect, scoreValue, boldTightLabel); GUI.Label(streakLabelRect, streakLabel, boldTightLabel); GUI.Label(streakValueRect, streakValue, boldTightLabel); GUI.Label(bestLabelRect, bestStreakLabel, boldTightLabel); GUI.Label(bestValueRect, bestStreakValue, boldTightLabel); GUI.Label(livesLabelRect, livesLeftLabel, boldTightLabel); GUI.Label(livesValueRect, livesLeftValue, boldTightLabel); if(GUI.Button(pauseButtonRect, isPaused ? unpauseLabel : pauseLabel, button)) { TogglePause(); } GUI.EndGroup(); GUI.backgroundColor = baseBackgroundColor; GUI.contentColor = baseContentColor; } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Serialization; using Contracts.Crm; using Contracts.Location; using Export.DataModel; using iQuarc.DataAccess; namespace Export.Services.PageXmlDemo { public class PageXmlExport { private const string exportFolder = "c:\temp"; private readonly IRepository repository; public PageXmlExport(IRepository repository) { this.repository = repository; } public bool ExportCustomerPage(string fileNamePrefix, bool overwrite, string customerName, int maxSalesOrders, bool addCustomerDetails) { string fileName = string.Format("{0}-{1}.xml", fileNamePrefix, customerName); string filePath = Path.Combine(exportFolder, fileName); if (!overwrite && File.Exists(filePath)) return false; PageXml content = new PageXml {Customer = new CustomerXml {Name = customerName}}; if (maxSalesOrders > 0) { var orders = repository.GetEntities<Order>() .Where(o => o.Customer.CompanyName == content.Customer.Name) .OrderBy(o => o.OrderDate) .Take(maxSalesOrders); //enrich content with orders } if (addCustomerDetails) { var customer = repository.GetEntities<Customer>() .Where(c => c.CompanyName == customerName); // enrich content with customer data } XmlSerializer serializer = new XmlSerializer(typeof (PageXml)); using (StreamWriter sw = File.CreateText(filePath)) { serializer.Serialize(sw, content); } return true; } public bool ExportCustomerPageWithExternalData(string fileNamePrefix, bool overwrite, string customerName, int maxSalesOrders, bool addCustomerDetails, PageData externalData, ICrmService crmService, ILocationService locationService) { string fileName = string.Format("{0}-{1}.xml", fileNamePrefix, customerName); string filePath = Path.Combine(exportFolder, fileName); if (!overwrite && File.Exists(filePath)) return false; PageXml content = new PageXml {Customer = new CustomerXml {Name = customerName}}; if (externalData.CustomerData != null) { // enrich with externalData.CustomerData } else { CustomerInfo customerData = crmService.GetCustomerInfo(content.Customer.Name); } if (maxSalesOrders > 0) { var orders = repository.GetEntities<Order>() .Where(o => o.Customer.CompanyName == content.Customer.Name) .OrderBy(o => o.OrderDate) .Take(maxSalesOrders); //enrich content with orders } if (addCustomerDetails) { var customer = repository.GetEntities<Customer>() .Where(c => c.CompanyName == customerName); // enrich content with customer data } if (locationService != null) { foreach (var address in content.Customer.Addresses) { Coordinates coordinates = locationService.GetCoordinates(address.City, address.Street, address.Number); if (coordinates != null) address.Coordinates = string.Format("{0},{1}", coordinates.Latitude, coordinates.Longitude); } } XmlSerializer serializer = new XmlSerializer(typeof (PageXml)); using (StreamWriter sw = File.CreateText(filePath)) { serializer.Serialize(sw, content); } return true; } public bool ExportOrders(int maxSalesOrders, string customerName) { string fileName = string.Format("CustomerOrders-{0}-{1}.xml", customerName, DateTime.Now); string filePath = Path.Combine(exportFolder, fileName); PageXml content = new PageXml {Customer = new CustomerXml {Name = customerName}}; var orders = repository.GetEntities<Order>() .Where(o => o.Customer.CompanyName == content.Customer.Name) .OrderBy(o => o.OrderDate) .Take(maxSalesOrders); //enrich content with orders XmlSerializer serializer = new XmlSerializer(typeof (PageXml)); using (StreamWriter sw = File.CreateText(filePath)) { serializer.Serialize(sw, content); } return true; } public PageXml GetPageForOrders(IEnumerable<Order> orders, ICrmService crmService, ILocationService locationService) { string customerName = GetCustomerNameFromFirstOrder(); PageXml content = new PageXml {Customer = new CustomerXml {Name = customerName}}; if (crmService != null) { CustomerInfo customerData = crmService.GetCustomerInfo(content.Customer.Name); //enrich with data from crm } //enrich content with orders if (locationService != null) { foreach (var address in content.Customer.Addresses) { Coordinates coordinates = locationService.GetCoordinates(address.City, address.Street, address.Number); if (coordinates != null) address.Coordinates = string.Format("{0},{1}", coordinates.Latitude, coordinates.Longitude); } } return content; } private string GetCustomerNameFromFirstOrder() { throw new NotImplementedException(); } #region Old Samle // public void ExportOrders(IEnumerable<Order> orders, ICrmService crmService, ILocationService locationService) // { // string currentCustomer = string.Empty; // string curretFilePath = string.Empty; // PageXml currentPage = null; // foreach (var order in orders.OrderBy(o => o.Customer.Name)) // { // if (currentCustomer != order.Customer.Name) // { // if (currentPage != null) // { // XmlSerializer serializer = new XmlSerializer(typeof (PageXml)); // using (StreamWriter sw = File.CreateText(curretFilePath)) // { // serializer.Serialize(sw, currentPage); // } // } // string fileName = string.Format("CustomerOrders-{0}-{1}.xml", currentCustomer, DateTime.Now); // curretFilePath = Path.Combine(exportFolder, fileName); // currentPage = new PageXml {Customer = new CustomerXml {Name = currentCustomer}}; // } // AddOrderToPage(currentPage, order); // } // } // private void AddOrdersToPage(PageXml page, IEnumerable<Order> orders) // { // foreach (var o in orders) // { // AddOrderToPage(page, o); // } // } // private void AddOrderToPage(PageXml currentPage, Order order) // { // //TODO: implement this // } #endregion } }
using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Text; namespace Kent.Boogaart.HelperTrinity { /// <summary> /// Provides helper methods for raising events. /// </summary> /// <remarks> /// <para> /// The <c>EventHelper</c> class provides methods that can be used to raise events. It avoids the need for explicitly /// checking event sinks for <see langword="null"/> before raising the event. /// </para> /// </remarks> /// <example> /// The following example shows how a non-generic event can be raised: /// <code> /// internal event EventHandler Changed; /// /// protected void OnChanged() /// { /// EventHelper.Raise(Changed, this); /// } /// </code> /// </example> /// <example> /// The following example shows how a non-generic event can be raised where the event type requires a specific /// <c>EventArgs</c> subclass: /// <code> /// internal event PropertyChangedEventHandler PropertyChanged; /// /// protected void OnPropertyChanged(PropertyChangedEventArgs e) /// { /// EventHelper.Raise(PropertyChanged, this, e); /// } /// </code> /// </example> /// <example> /// The following example shows how a generic event can be raised: /// <code> /// internal event EventHandler&lt;EventArgs&gt; Changed; /// /// protected void OnChanged() /// { /// EventHelper.Raise(Changed, this, EventArgs.Empty); /// } /// </code> /// </example> /// <example> /// The following example shows how a generic event with custom event arguments can be raised: /// <code> /// internal event EventHandler&lt;MyEventArgs&gt; MyEvent; /// /// protected void OnMyEvent(MyEventArgs e) /// { /// EventHelper.Raise(MyEventArgs, this, e); /// } /// </code> /// </example> /// <example> /// The following example raises a generic event, but does not create the event arguments unless there is at least one /// handler for the event: /// <code> /// internal event EventHandler&lt;MyEventArgs&gt; MyEvent; /// /// protected void OnMyEvent(int someData) /// { /// EventHelper.Raise(MyEvent, this, delegate /// { /// return new MyEventArgs(someData); /// }); /// } /// </code> /// </example> internal static class EventHelper { [SuppressMessage("Microsoft.Design", "CA1030", Justification = "False positive - the Raise method overloads are supposed to raise an event on behalf of a client, not on behalf of its declaring class.")] [DebuggerHidden] internal static void BeginRaise(EventHandler handler, object sender, AsyncCallback callback, object asyncState) { if (handler != null) { #if DEBUG BeginRaiseWithDiagnostics(handler, callback, asyncState, sender, EventArgs.Empty); #else new Raise_EventHandler_Object_Handler(Raise).BeginInvoke(handler, sender, callback, asyncState); #endif } } private delegate void Raise_EventHandler_Object_Handler(EventHandler hander, object sender); [SuppressMessage("Microsoft.Design", "CA1030", Justification = "False positive - the Raise method overloads are supposed to raise an event on behalf of a client, not on behalf of its declaring class.")] [DebuggerHidden] internal static void Raise(EventHandler handler, object sender) { if (handler != null) { #if DEBUG RaiseWithDiagnostics(handler, sender, EventArgs.Empty); #else handler(sender, EventArgs.Empty); #endif } } [SuppressMessage("Microsoft.Design", "CA1030", Justification = "False positive - the Raise method overloads are supposed to raise an event on behalf of a client, not on behalf of its declaring class.")] [DebuggerHidden] internal static void BeginRaise(Delegate handler, object sender, EventArgs e, AsyncCallback callback, object asyncState) { if (handler != null) { #if DEBUG BeginRaiseWithDiagnostics(handler, callback, asyncState, sender, e); #else new Raise_Delegate_Object_EventArgs_Handler(Raise).BeginInvoke(handler, sender, e, callback, asyncState); #endif } } private delegate void Raise_Delegate_Object_EventArgs_Handler(Delegate handler, object sender, EventArgs e); [SuppressMessage("Microsoft.Design", "CA1030", Justification = "False positive - the Raise method overloads are supposed to raise an event on behalf of a client, not on behalf of its declaring class.")] [DebuggerHidden] internal static void Raise(Delegate handler, object sender, EventArgs e) { if (handler != null) { #if DEBUG RaiseWithDiagnostics(handler, sender, e); #else handler.DynamicInvoke(sender, e); #endif } } [SuppressMessage("Microsoft.Design", "CA1030", Justification = "False positive - the Raise method overloads are supposed to raise an event on behalf of a client, not on behalf of its declaring class.")] [DebuggerHidden] internal static void BeginRaise<T>(EventHandler<T> handler, object sender, T e, AsyncCallback callback, object asyncState) where T : EventArgs { if (handler != null) { #if DEBUG BeginRaiseWithDiagnostics(handler, callback, asyncState, sender, e); #else new Raise_GenericEventHandler_Object_EventArgs_Handler<T>(Raise).BeginInvoke(handler, sender, e, callback, asyncState); #endif } } private delegate void Raise_GenericEventHandler_Object_EventArgs_Handler<T>(EventHandler<T> handler, object sender, T e) where T : EventArgs; [SuppressMessage("Microsoft.Design", "CA1030", Justification = "False positive - the Raise method overloads are supposed to raise an event on behalf of a client, not on behalf of its declaring class.")] [DebuggerHidden] internal static void Raise<T>(EventHandler<T> handler, object sender, T e) where T : EventArgs { if (handler != null) { #if DEBUG RaiseWithDiagnostics(handler, sender, e); #else handler(sender, e); #endif } } [SuppressMessage("Microsoft.Design", "CA1030", Justification = "False positive - the Raise method overloads are supposed to raise an event on behalf of a client, not on behalf of its declaring class.")] [DebuggerHidden] internal static void BeginRaise<T>(EventHandler<T> handler, object sender, CreateEventArguments<T> createEventArguments, AsyncCallback callback, object asyncState) where T : EventArgs { ArgumentHelper.AssertNotNull(createEventArguments, "createEventArguments"); if (handler != null) { #if DEBUG BeginRaiseWithDiagnostics(handler, callback, asyncState, sender, createEventArguments()); #else new Raise_GenericEventHandler_Object_GenericCreateEventArguments_Handler<T>(Raise).BeginInvoke(handler, sender, createEventArguments, callback, asyncState); #endif } } private delegate void Raise_GenericEventHandler_Object_GenericCreateEventArguments_Handler<T>(EventHandler<T> handler, object sender, CreateEventArguments<T> createEventArguments) where T : EventArgs; [SuppressMessage("Microsoft.Design", "CA1030", Justification = "False positive - the Raise method overloads are supposed to raise an event on behalf of a client, not on behalf of its declaring class.")] [DebuggerHidden] internal static void Raise<T>(EventHandler<T> handler, object sender, CreateEventArguments<T> createEventArguments) where T : EventArgs { ArgumentHelper.AssertNotNull(createEventArguments, "createEventArguments"); if (handler != null) { #if DEBUG RaiseWithDiagnostics(handler, sender, createEventArguments()); #else handler(sender, createEventArguments()); #endif } } #if DEBUG private delegate void RaiseWithDiagnosticsHandler(Delegate handler, params object[] parameters); private static void BeginRaiseWithDiagnostics(Delegate handler, AsyncCallback callback, object asyncState, params object[] parameters) { new RaiseWithDiagnosticsHandler(RaiseWithDiagnostics).BeginInvoke(handler, parameters, callback, asyncState); } /// <summary> /// A method used by debug builds to raise events and log diagnostic information in the process. /// </summary> /// <remarks> /// This method is only called in debug builds. It logs details about raised events and any exceptions thrown by event /// handlers. /// </remarks> /// <param name="handler"> /// The event handler. /// </param> /// <param name="parameters"> /// Parameters to the event handler. /// </param> private static void RaiseWithDiagnostics(Delegate handler, params object[] parameters) { Debug.Assert(handler != null); //var threadName = System.Threading.Thread.CurrentThread.Name; //Debug.WriteLine(string.Format("Event being raised by thread '{0}'.", threadName)); foreach (var del in handler.GetInvocationList()) { try { //Debug.WriteLine(string.Format(" Calling method '{0}.{1}'.", del.Method.DeclaringType.FullName, del.Method.Name)); del.DynamicInvoke(parameters); } catch (Exception ex) { var sb = new StringBuilder(); sb.AppendLine(" An exception occurred in the event handler:"); while (ex != null) { sb.Append(" ").AppendLine(ex.Message); sb.AppendLine(ex.StackTrace); ex = ex.InnerException; if (ex != null) { sb.AppendLine("--- INNER EXCEPTION ---"); } } Debug.WriteLine(sb.ToString()); //the exception isn't swallowed - just logged throw; } } //Debug.WriteLine(string.Format("Finished raising event by thread '{0}'.", threadName)); } #endif /// <summary> /// A handler used to create an event arguments instance for the /// <see cref="Raise{T}(EventHandler{T}, object, CreateEventArguments{T})"/> method. /// </summary> /// <remarks> /// This delegate is invoked by the /// <see cref="Raise{T}(EventHandler{T}, object, CreateEventArguments{T})"/> method to create the /// event arguments instance. The handler should create the instance and return it. /// </remarks> /// <typeparam name="T"> /// The event arguments type. /// </typeparam> /// <returns> /// The event arguments instance. /// </returns> internal delegate T CreateEventArguments<T>() where T : EventArgs; } }
using NUnit.Framework; namespace DotSpatial.Projections.Tests.Projected { /// <summary> /// This class contains all the tests for the WorldSpheroid category of Projected coordinate systems /// </summary> [TestFixture] public class WorldSpheroid { /// <summary> /// Creates a new instance of the Africa Class /// </summary> [SetUp] public void Initialize() { } [Test] [Ignore("")] public void Aitoffsphere() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.WorldSpheroid.Aitoffsphere; Tester.TestProjection(pStart); } [Test] [Ignore("")] public void Behrmannsphere() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.WorldSpheroid.Behrmannsphere; Tester.TestProjection(pStart); } [Test] public void Bonnesphere() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.WorldSpheroid.Bonnesphere; Tester.TestProjection(pStart); } [Test] [Ignore("")] public void CrasterParabolicsphere() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.WorldSpheroid.CrasterParabolicsphere; Tester.TestProjection(pStart); } [Test] public void CylindricalEqualAreasphere() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.WorldSpheroid.CylindricalEqualAreasphere; Tester.TestProjection(pStart); } [Test] [Ignore("")] public void EckertIIIsphere() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.WorldSpheroid.EckertIIIsphere; Tester.TestProjection(pStart); } [Test] [Ignore("")] public void EckertIIsphere() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.WorldSpheroid.EckertIIsphere; Tester.TestProjection(pStart); } [Test] [Ignore("")] public void EckertIsphere() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.WorldSpheroid.EckertIsphere; Tester.TestProjection(pStart); } [Test] public void EckertIVsphere() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.WorldSpheroid.EckertIVsphere; Tester.TestProjection(pStart); } [Test] [Ignore("")] public void EckertVIsphere() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.WorldSpheroid.EckertVIsphere; Tester.TestProjection(pStart); } [Test] [Ignore("")] public void EckertVsphere() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.WorldSpheroid.EckertVsphere; Tester.TestProjection(pStart); } [Test] public void EquidistantConicsphere() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.WorldSpheroid.EquidistantConicsphere; Tester.TestProjection(pStart); } [Test] public void EquidistantCylindricalsphere() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.WorldSpheroid.EquidistantCylindricalsphere; Tester.TestProjection(pStart); } [Test] [Ignore("")] public void FlatPolarQuarticsphere() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.WorldSpheroid.FlatPolarQuarticsphere; Tester.TestProjection(pStart); } [Test] public void GallStereographicsphere() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.WorldSpheroid.GallStereographicsphere; Tester.TestProjection(pStart); } [Test] [Ignore("")] public void HammerAitoffsphere() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.WorldSpheroid.HammerAitoffsphere; Tester.TestProjection(pStart); } [Test] [Ignore("")] public void Loximuthalsphere() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.WorldSpheroid.Loximuthalsphere; Tester.TestProjection(pStart); } [Test] public void Mercatorsphere() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.WorldSpheroid.Mercatorsphere; Tester.TestProjection(pStart); } [Test] public void MillerCylindricalsphere() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.WorldSpheroid.MillerCylindricalsphere; Tester.TestProjection(pStart); } [Test] public void Mollweidesphere() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.WorldSpheroid.Mollweidesphere; Tester.TestProjection(pStart); } [Test] [Ignore("")] public void PlateCarreesphere() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.WorldSpheroid.PlateCarreesphere; Tester.TestProjection(pStart); } [Test] public void Polyconicsphere() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.WorldSpheroid.Polyconicsphere; Tester.TestProjection(pStart); } [Test] [Ignore("")] public void QuarticAuthalicsphere() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.WorldSpheroid.QuarticAuthalicsphere; Tester.TestProjection(pStart); } [Test] public void Robinsonsphere() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.WorldSpheroid.Robinsonsphere; Tester.TestProjection(pStart); } [Test] public void Sinusoidalsphere() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.WorldSpheroid.Sinusoidalsphere; Tester.TestProjection(pStart); } [Test] [Ignore("")] public void Timessphere() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.WorldSpheroid.Timessphere; Tester.TestProjection(pStart); } [Test] public void VanderGrintenIsphere() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.WorldSpheroid.VanderGrintenIsphere; Tester.TestProjection(pStart); } [Test] [Ignore("")] public void VerticalPerspectivesphere() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.WorldSpheroid.VerticalPerspectivesphere; Tester.TestProjection(pStart); } [Test] [Ignore("")] public void WinkelIIsphere() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.WorldSpheroid.WinkelIIsphere; Tester.TestProjection(pStart); } [Test] [Ignore("")] public void WinkelIsphere() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.WorldSpheroid.WinkelIsphere; Tester.TestProjection(pStart); } [Test] [Ignore("")] public void WinkelTripelNGSsphere() { ProjectionInfo pStart = KnownCoordinateSystems.Projected.WorldSpheroid.WinkelTripelNGSsphere; Tester.TestProjection(pStart); } } }
// 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 code is from Roslyn/Source/Compilers/Core/CvtRes.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using DWORD = System.UInt32; using WCHAR = System.Char; using WORD = System.UInt16; namespace GenFacades { internal class VersionResourceSerializer { private readonly string _commentsContents; private readonly string _companyNameContents; private readonly string _fileDescriptionContents; private readonly string _fileVersionContents; private readonly string _internalNameContents; private readonly string _legalCopyrightContents; private readonly string _legalTrademarksContents; private readonly string _originalFileNameContents; private readonly string _productNameContents; private readonly string _productVersionContents; private readonly Version _assemblyVersionContents; private const string vsVersionInfoKey = "VS_VERSION_INFO"; private const string varFileInfoKey = "VarFileInfo"; private const string translationKey = "Translation"; private const string stringFileInfoKey = "StringFileInfo"; private readonly string _langIdAndCodePageKey; //should be 8 characters private const DWORD CP_WINUNICODE = 1200; private const ushort sizeVS_FIXEDFILEINFO = sizeof(DWORD) * 13; private readonly bool _isDll; internal VersionResourceSerializer(bool isDll, string comments, string companyName, string fileDescription, string fileVersion, string internalName, string legalCopyright, string legalTrademark, string originalFileName, string productName, string productVersion, Version assemblyVersion) { _isDll = isDll; _commentsContents = comments; _companyNameContents = companyName; _fileDescriptionContents = fileDescription; _fileVersionContents = fileVersion; _internalNameContents = internalName; _legalCopyrightContents = legalCopyright; _legalTrademarksContents = legalTrademark; _originalFileNameContents = originalFileName; _productNameContents = productName; _productVersionContents = productVersion; _assemblyVersionContents = assemblyVersion; _langIdAndCodePageKey = System.String.Format("{0:x4}{1:x4}", 0 /*langId*/, CP_WINUNICODE /*codepage*/); } private const uint VFT_APP = 0x00000001; private const uint VFT_DLL = 0x00000002; private IEnumerable<KeyValuePair<string, string>> GetVerStrings() { if (_commentsContents != null) yield return new KeyValuePair<string, string>("Comments", _commentsContents); if (_companyNameContents != null) yield return new KeyValuePair<string, string>("CompanyName", _companyNameContents); if (_fileDescriptionContents != null) yield return new KeyValuePair<string, string>("FileDescription", _fileDescriptionContents); if (_fileVersionContents != null) yield return new KeyValuePair<string, string>("FileVersion", _fileVersionContents); if (_internalNameContents != null) yield return new KeyValuePair<string, string>("InternalName", _internalNameContents); if (_legalCopyrightContents != null) yield return new KeyValuePair<string, string>("LegalCopyright", _legalCopyrightContents); if (_legalTrademarksContents != null) yield return new KeyValuePair<string, string>("LegalTrademarks", _legalTrademarksContents); if (_originalFileNameContents != null) yield return new KeyValuePair<string, string>("OriginalFilename", _originalFileNameContents); if (_productNameContents != null) yield return new KeyValuePair<string, string>("ProductName", _productNameContents); if (_productVersionContents != null) yield return new KeyValuePair<string, string>("ProductVersion", _productVersionContents); if (_assemblyVersionContents != null) yield return new KeyValuePair<string, string>("Assembly Version", _assemblyVersionContents.ToString()); } private uint FileType { get { return (_isDll) ? VFT_DLL : VFT_APP; } } private void WriteVSFixedFileInfo(BinaryWriter writer) { //There's nothing guaranteeing that these are n.n.n.n format. //The documentation says that if they're not that format the behavior is undefined. Version fileVersion; if (!Version.TryParse(_fileVersionContents, out fileVersion)) fileVersion = new Version(0, 0); Version productVersion; if (!Version.TryParse(_productVersionContents, out productVersion)) productVersion = new Version(0, 0); writer.Write((DWORD)0xFEEF04BD); writer.Write((DWORD)0x00010000); writer.Write((DWORD)(fileVersion.Major << 16) | (uint)fileVersion.Minor); writer.Write((DWORD)(fileVersion.Build << 16) | (uint)fileVersion.Revision); writer.Write((DWORD)(productVersion.Major << 16) | (uint)productVersion.Minor); writer.Write((DWORD)(productVersion.Build << 16) | (uint)productVersion.Revision); writer.Write((DWORD)0x0000003F); //VS_FFI_FILEFLAGSMASK (EDMAURER) really? all these bits are valid? writer.Write((DWORD)0); //file flags writer.Write((DWORD)0x00000004); //VOS__WINDOWS32 writer.Write((DWORD)this.FileType); writer.Write((DWORD)0); //file subtype writer.Write((DWORD)0); //date most sig writer.Write((DWORD)0); //date least sig } /// <summary> /// Assume that 3 WORDs preceded this string and that the they began 32-bit aligned. /// Given the string length compute the number of bytes that should be written to end /// the buffer on a 32-bit boundary</summary> /// <param name="cb"></param> /// <returns></returns> private static int PadKeyLen(int cb) { //add previously written 3 WORDS, round up, then subtract the 3 WORDS. return PadToDword(cb + 3 * sizeof(WORD)) - 3 * sizeof(WORD); } /// <summary> /// assuming the length of bytes submitted began on a 32-bit boundary, /// round up this length as necessary so that it ends at a 32-bit boundary. /// </summary> /// <param name="cb"></param> /// <returns></returns> private static int PadToDword(int cb) { return (cb + 3) & ~3; } private const int HDRSIZE = 3 * sizeof(ushort); private static ushort SizeofVerString(string lpszKey, string lpszValue) { int cbKey, cbValue; cbKey = (lpszKey.Length + 1) * 2; // Make room for the NULL cbValue = (lpszValue.Length + 1) * 2; if (cbKey + cbValue >= 0xFFF0) return 0xFFFF; return (ushort)(PadKeyLen(cbKey) + // key, 0 padded to DWORD boundary PadToDword(cbValue) + // value, 0 padded to dword boundary HDRSIZE); // block header. } private static void WriteVersionString(KeyValuePair<string, string> keyValuePair, BinaryWriter writer) { System.Diagnostics.Debug.Assert(keyValuePair.Value != null); ushort cbBlock = SizeofVerString(keyValuePair.Key, keyValuePair.Value); int cbKey = (keyValuePair.Key.Length + 1) * 2; // includes terminating NUL int cbVal = (keyValuePair.Value.Length + 1) * 2; // includes terminating NUL var startPos = writer.BaseStream.Position; writer.Write((WORD)cbBlock); writer.Write((WORD)(keyValuePair.Value.Length + 1)); //add 1 for nul writer.Write((WORD)1); writer.Write(keyValuePair.Key.ToCharArray()); writer.Write((WORD)'\0'); writer.Write(new byte[PadKeyLen(cbKey) - cbKey]); writer.Write(keyValuePair.Value.ToCharArray()); writer.Write((WORD)'\0'); writer.Write(new byte[PadToDword(cbVal) - cbVal]); System.Diagnostics.Debug.Assert(cbBlock == writer.BaseStream.Position - startPos); } /// <summary> /// compute number of chars needed to end up on a 32-bit boundary assuming that three /// WORDS preceded this string. /// </summary> /// <param name="sz"></param> /// <returns></returns> private static int KEYSIZE(string sz) { return PadKeyLen((sz.Length + 1) * sizeof(WCHAR)) / sizeof(WCHAR); } private static int KEYBYTES(string sz) { return KEYSIZE(sz) * sizeof(WCHAR); } private int GetStringsSize() { return GetVerStrings().Aggregate(0, (curSum, pair) => SizeofVerString(pair.Key, pair.Value) + curSum); } internal int GetDataSize() { int sizeEXEVERRESOURCE = sizeof(WORD) * 3 * 5 + 2 * sizeof(WORD) + //five headers + two words for CP and lang KEYBYTES(vsVersionInfoKey) + KEYBYTES(varFileInfoKey) + KEYBYTES(translationKey) + KEYBYTES(stringFileInfoKey) + KEYBYTES(_langIdAndCodePageKey) + sizeVS_FIXEDFILEINFO; return GetStringsSize() + sizeEXEVERRESOURCE; } internal void WriteVerResource(BinaryWriter writer) { /* must be assumed to start on a 32-bit boundary. * * the sub-elements of the VS_VERSIONINFO consist of a header (3 WORDS) a string * and then beginning on the next 32-bit boundary, the elements children struct VS_VERSIONINFO { WORD cbRootBlock; // size of whole resource WORD cbRootValue; // size of VS_FIXEDFILEINFO structure WORD fRootText; // root is text? WCHAR szRootKey[KEYSIZE("VS_VERSION_INFO")]; // Holds "VS_VERSION_INFO" VS_FIXEDFILEINFO vsFixed; // fixed information. WORD cbVarBlock; // size of VarFileInfo block WORD cbVarValue; // always 0 WORD fVarText; // VarFileInfo is text? WCHAR szVarKey[KEYSIZE("VarFileInfo")]; // Holds "VarFileInfo" WORD cbTransBlock; // size of Translation block WORD cbTransValue; // size of Translation value WORD fTransText; // Translation is text? WCHAR szTransKey[KEYSIZE("Translation")]; // Holds "Translation" WORD langid; // language id WORD codepage; // codepage id WORD cbStringBlock; // size of StringFileInfo block WORD cbStringValue; // always 0 WORD fStringText; // StringFileInfo is text? WCHAR szStringKey[KEYSIZE("StringFileInfo")]; // Holds "StringFileInfo" WORD cbLangCpBlock; // size of language/codepage block WORD cbLangCpValue; // always 0 WORD fLangCpText; // LangCp is text? WCHAR szLangCpKey[KEYSIZE("12345678")]; // Holds hex version of language/codepage // followed by strings }; */ var debugPos = writer.BaseStream.Position; var dataSize = GetDataSize(); writer.Write((WORD)dataSize); writer.Write((WORD)sizeVS_FIXEDFILEINFO); writer.Write((WORD)0); writer.Write(vsVersionInfoKey.ToCharArray()); writer.Write(new byte[KEYBYTES(vsVersionInfoKey) - vsVersionInfoKey.Length * 2]); System.Diagnostics.Debug.Assert((writer.BaseStream.Position & 3) == 0); WriteVSFixedFileInfo(writer); writer.Write((WORD)(sizeof(WORD) * 2 + 2 * HDRSIZE + KEYBYTES(varFileInfoKey) + KEYBYTES(translationKey))); writer.Write((WORD)0); writer.Write((WORD)1); writer.Write(varFileInfoKey.ToCharArray()); writer.Write(new byte[KEYBYTES(varFileInfoKey) - varFileInfoKey.Length * 2]); //padding System.Diagnostics.Debug.Assert((writer.BaseStream.Position & 3) == 0); writer.Write((WORD)(sizeof(WORD) * 2 + HDRSIZE + KEYBYTES(translationKey))); writer.Write((WORD)(sizeof(WORD) * 2)); writer.Write((WORD)0); writer.Write(translationKey.ToCharArray()); writer.Write(new byte[KEYBYTES(translationKey) - translationKey.Length * 2]); //padding System.Diagnostics.Debug.Assert((writer.BaseStream.Position & 3) == 0); writer.Write((WORD)0); //langId; MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL)) = 0 writer.Write((WORD)CP_WINUNICODE); //codepage; 1200 = CP_WINUNICODE System.Diagnostics.Debug.Assert((writer.BaseStream.Position & 3) == 0); writer.Write((WORD)(2 * HDRSIZE + KEYBYTES(stringFileInfoKey) + KEYBYTES(_langIdAndCodePageKey) + GetStringsSize())); writer.Write((WORD)0); writer.Write((WORD)1); writer.Write(stringFileInfoKey.ToCharArray()); //actually preceded by 5 WORDS so not consistent with the //assumptions of KEYBYTES, but equivalent. writer.Write(new byte[KEYBYTES(stringFileInfoKey) - stringFileInfoKey.Length * 2]); //padding. System.Diagnostics.Debug.Assert((writer.BaseStream.Position & 3) == 0); writer.Write((WORD)(HDRSIZE + KEYBYTES(_langIdAndCodePageKey) + GetStringsSize())); writer.Write((WORD)0); writer.Write((WORD)1); writer.Write(_langIdAndCodePageKey.ToCharArray()); writer.Write(new byte[KEYBYTES(_langIdAndCodePageKey) - _langIdAndCodePageKey.Length * 2]); //padding System.Diagnostics.Debug.Assert((writer.BaseStream.Position & 3) == 0); System.Diagnostics.Debug.Assert(writer.BaseStream.Position - debugPos == dataSize - GetStringsSize()); debugPos = writer.BaseStream.Position; foreach (var entry in GetVerStrings()) { System.Diagnostics.Debug.Assert(entry.Value != null); WriteVersionString(entry, writer); } System.Diagnostics.Debug.Assert(writer.BaseStream.Position - debugPos == GetStringsSize()); } } }
// 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; namespace System.Xml { internal partial class ReadContentAsBinaryHelper { // Private enums enum State { None, InReadContent, InReadElementContent, } // Fields private XmlReader _reader; private State _state; private int _valueOffset; private bool _isEnd; private bool _canReadValueChunk; private char[] _valueChunk; private int _valueChunkLength; private IncrementalReadDecoder _decoder; private Base64Decoder _base64Decoder; private BinHexDecoder _binHexDecoder; // Constants private const int ChunkSize = 256; // Constructor internal ReadContentAsBinaryHelper(XmlReader reader) { _reader = reader; _canReadValueChunk = reader.CanReadValueChunk; if (_canReadValueChunk) { _valueChunk = new char[ChunkSize]; } } // Static methods internal static ReadContentAsBinaryHelper CreateOrReset(ReadContentAsBinaryHelper helper, XmlReader reader) { if (helper == null) { return new ReadContentAsBinaryHelper(reader); } else { helper.Reset(); return helper; } } // Internal methods internal int ReadContentAsBase64(byte[] buffer, int index, int count) { // check arguments if (buffer == null) { throw new ArgumentNullException("buffer"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (index < 0) { throw new ArgumentOutOfRangeException("index"); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException("count"); } switch (_state) { case State.None: if (!_reader.CanReadContentAs()) { throw _reader.CreateReadContentAsException("ReadContentAsBase64"); } if (!Init()) { return 0; } break; case State.InReadContent: // if we have a correct decoder, go read if (_decoder == _base64Decoder) { // read more binary data return ReadContentAsBinary(buffer, index, count); } break; case State.InReadElementContent: throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods); default: Debug.Assert(false); return 0; } Debug.Assert(_state == State.InReadContent); // setup base64 decoder InitBase64Decoder(); // read more binary data return ReadContentAsBinary(buffer, index, count); } internal int ReadContentAsBinHex(byte[] buffer, int index, int count) { // check arguments if (buffer == null) { throw new ArgumentNullException("buffer"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (index < 0) { throw new ArgumentOutOfRangeException("index"); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException("count"); } switch (_state) { case State.None: if (!_reader.CanReadContentAs()) { throw _reader.CreateReadContentAsException("ReadContentAsBinHex"); } if (!Init()) { return 0; } break; case State.InReadContent: // if we have a correct decoder, go read if (_decoder == _binHexDecoder) { // read more binary data return ReadContentAsBinary(buffer, index, count); } break; case State.InReadElementContent: throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods); default: Debug.Assert(false); return 0; } Debug.Assert(_state == State.InReadContent); // setup binhex decoder InitBinHexDecoder(); // read more binary data return ReadContentAsBinary(buffer, index, count); } internal int ReadElementContentAsBase64(byte[] buffer, int index, int count) { // check arguments if (buffer == null) { throw new ArgumentNullException("buffer"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (index < 0) { throw new ArgumentOutOfRangeException("index"); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException("count"); } switch (_state) { case State.None: if (_reader.NodeType != XmlNodeType.Element) { throw _reader.CreateReadElementContentAsException("ReadElementContentAsBase64"); } if (!InitOnElement()) { return 0; } break; case State.InReadContent: throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods); case State.InReadElementContent: // if we have a correct decoder, go read if (_decoder == _base64Decoder) { // read more binary data return ReadElementContentAsBinary(buffer, index, count); } break; default: Debug.Assert(false); return 0; } Debug.Assert(_state == State.InReadElementContent); // setup base64 decoder InitBase64Decoder(); // read more binary data return ReadElementContentAsBinary(buffer, index, count); } internal int ReadElementContentAsBinHex(byte[] buffer, int index, int count) { // check arguments if (buffer == null) { throw new ArgumentNullException("buffer"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (index < 0) { throw new ArgumentOutOfRangeException("index"); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException("count"); } switch (_state) { case State.None: if (_reader.NodeType != XmlNodeType.Element) { throw _reader.CreateReadElementContentAsException("ReadElementContentAsBinHex"); } if (!InitOnElement()) { return 0; } break; case State.InReadContent: throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods); case State.InReadElementContent: // if we have a correct decoder, go read if (_decoder == _binHexDecoder) { // read more binary data return ReadElementContentAsBinary(buffer, index, count); } break; default: Debug.Assert(false); return 0; } Debug.Assert(_state == State.InReadElementContent); // setup binhex decoder InitBinHexDecoder(); // read more binary data return ReadElementContentAsBinary(buffer, index, count); } internal void Finish() { if (_state != State.None) { while (MoveToNextContentNode(true)) ; if (_state == State.InReadElementContent) { if (_reader.NodeType != XmlNodeType.EndElement) { throw new XPath.XPathException(SR.Xml_InvalidNodeType, _reader.NodeType.ToString(), _reader as IXmlLineInfo); } // move off the EndElement _reader.Read(); } } Reset(); } internal void Reset() { _state = State.None; _isEnd = false; _valueOffset = 0; } // Private methods private bool Init() { // make sure we are on a content node if (!MoveToNextContentNode(false)) { return false; } _state = State.InReadContent; _isEnd = false; return true; } private bool InitOnElement() { Debug.Assert(_reader.NodeType == XmlNodeType.Element); bool isEmpty = _reader.IsEmptyElement; // move to content or off the empty element _reader.Read(); if (isEmpty) { return false; } // make sure we are on a content node if (!MoveToNextContentNode(false)) { if (_reader.NodeType != XmlNodeType.EndElement) { throw new XPath.XPathException(SR.Xml_InvalidNodeType, _reader.NodeType.ToString(), _reader as IXmlLineInfo); } // move off end element _reader.Read(); return false; } _state = State.InReadElementContent; _isEnd = false; return true; } private void InitBase64Decoder() { if (_base64Decoder == null) { _base64Decoder = new Base64Decoder(); } else { _base64Decoder.Reset(); } _decoder = _base64Decoder; } private void InitBinHexDecoder() { if (_binHexDecoder == null) { _binHexDecoder = new BinHexDecoder(); } else { _binHexDecoder.Reset(); } _decoder = _binHexDecoder; } private int ReadContentAsBinary(byte[] buffer, int index, int count) { Debug.Assert(_decoder != null); if (_isEnd) { Reset(); return 0; } _decoder.SetNextOutputBuffer(buffer, index, count); for (; ;) { // use streaming ReadValueChunk if the reader supports it if (_canReadValueChunk) { for (; ;) { if (_valueOffset < _valueChunkLength) { int decodedCharsCount = _decoder.Decode(_valueChunk, _valueOffset, _valueChunkLength - _valueOffset); _valueOffset += decodedCharsCount; } if (_decoder.IsFull) { return _decoder.DecodedCount; } Debug.Assert(_valueOffset == _valueChunkLength); if ((_valueChunkLength = _reader.ReadValueChunk(_valueChunk, 0, ChunkSize)) == 0) { break; } _valueOffset = 0; } } else { // read what is reader.Value string value = _reader.Value; int decodedCharsCount = _decoder.Decode(value, _valueOffset, value.Length - _valueOffset); _valueOffset += decodedCharsCount; if (_decoder.IsFull) { return _decoder.DecodedCount; } } _valueOffset = 0; // move to next textual node in the element content; throw on sub elements if (!MoveToNextContentNode(true)) { _isEnd = true; return _decoder.DecodedCount; } } } private int ReadElementContentAsBinary(byte[] buffer, int index, int count) { if (count == 0) { return 0; } // read binary int decoded = ReadContentAsBinary(buffer, index, count); if (decoded > 0) { return decoded; } // if 0 bytes returned check if we are on a closing EndElement, throw exception if not if (_reader.NodeType != XmlNodeType.EndElement) { throw new XPath.XPathException(SR.Xml_InvalidNodeType, _reader.NodeType.ToString(), _reader as IXmlLineInfo); } // move off the EndElement _reader.Read(); _state = State.None; return 0; } bool MoveToNextContentNode(bool moveIfOnContentNode) { do { switch (_reader.NodeType) { case XmlNodeType.Attribute: return !moveIfOnContentNode; case XmlNodeType.Text: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.CDATA: if (!moveIfOnContentNode) { return true; } break; case XmlNodeType.ProcessingInstruction: case XmlNodeType.Comment: case XmlNodeType.EndEntity: // skip comments, pis and end entity nodes break; case XmlNodeType.EntityReference: if (_reader.CanResolveEntity) { _reader.ResolveEntity(); break; } goto default; default: return false; } moveIfOnContentNode = false; } while (_reader.Read()); return false; } } }
using System; using System.Linq; using AutoMapper; using Moq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Services; using Umbraco.Tests.TestHelpers.Entities; using Umbraco.Tests.Testing; using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.Models.Mapping; using Umbraco.Web.PropertyEditors; namespace Umbraco.Tests.Models.Mapping { [TestFixture] [UmbracoTest(WithApplication = true)] public class ContentTypeModelMappingTests : UmbracoTestBase { // mocks of services that can be setup on a test by test basis to return whatever we want private readonly Mock<IContentTypeService> _contentTypeService = new Mock<IContentTypeService>(); private readonly Mock<IContentService> _contentService = new Mock<IContentService>(); private readonly Mock<IDataTypeService> _dataTypeService = new Mock<IDataTypeService>(); private readonly Mock<IEntityService> _entityService = new Mock<IEntityService>(); private readonly Mock<IFileService> _fileService = new Mock<IFileService>(); private Mock<PropertyEditorCollection> _editorsMock; public override void SetUp() { base.SetUp(); // fixme - are we initializing mappers that... have already been? Mapper.Reset(); Mapper.Initialize(configuration => { //initialize our content type mapper var profile1 = new ContentTypeMapperProfile(_editorsMock.Object, _dataTypeService.Object, _fileService.Object, _contentTypeService.Object, Mock.Of<IMediaTypeService>()); configuration.AddProfile(profile1); var profile2 = new EntityMapperProfile(); configuration.AddProfile(profile2); }); } protected override void Compose() { base.Compose(); // create and register a fake property editor collection to return fake property editors var editors = new DataEditor[] { new TextboxPropertyEditor(Mock.Of<ILogger>()), }; var dataEditors = new DataEditorCollection(editors); _editorsMock = new Mock<PropertyEditorCollection>(dataEditors); _editorsMock.Setup(x => x[It.IsAny<string>()]).Returns(editors[0]); Composition.RegisterUnique(f => _editorsMock.Object); Composition.RegisterUnique(_ => _contentTypeService.Object); Composition.RegisterUnique(_ => _contentService.Object); Composition.RegisterUnique(_ => _dataTypeService.Object); Composition.RegisterUnique(_ => _entityService.Object); Composition.RegisterUnique(_ => _fileService.Object); } [Test] public void MemberTypeSave_To_IMemberType() { //Arrange // setup the mocks to return the data we want to test against... _dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>())) .Returns(Mock.Of<IDataType>( definition => definition.Id == 555 && definition.EditorAlias == "myPropertyType" && definition.DatabaseType == ValueStorageType.Nvarchar)); var display = CreateMemberTypeSave(); //Act var result = Mapper.Map<IMemberType>(display); //Assert Assert.AreEqual(display.Alias, result.Alias); Assert.AreEqual(display.Description, result.Description); Assert.AreEqual(display.Icon, result.Icon); Assert.AreEqual(display.Id, result.Id); Assert.AreEqual(display.Name, result.Name); Assert.AreEqual(display.ParentId, result.ParentId); Assert.AreEqual(display.Path, result.Path); Assert.AreEqual(display.Thumbnail, result.Thumbnail); Assert.AreEqual(display.IsContainer, result.IsContainer); Assert.AreEqual(display.AllowAsRoot, result.AllowedAsRoot); Assert.AreEqual(display.CreateDate, result.CreateDate); Assert.AreEqual(display.UpdateDate, result.UpdateDate); //TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(display.Groups.Count(), result.PropertyGroups.Count); for (var i = 0; i < display.Groups.Count(); i++) { Assert.AreEqual(display.Groups.ElementAt(i).Id, result.PropertyGroups.ElementAt(i).Id); Assert.AreEqual(display.Groups.ElementAt(i).Name, result.PropertyGroups.ElementAt(i).Name); var propTypes = display.Groups.ElementAt(i).Properties; Assert.AreEqual(propTypes.Count(), result.PropertyTypes.Count()); for (var j = 0; j < propTypes.Count(); j++) { Assert.AreEqual(propTypes.ElementAt(j).Id, result.PropertyTypes.ElementAt(j).Id); Assert.AreEqual(propTypes.ElementAt(j).DataTypeId, result.PropertyTypes.ElementAt(j).DataTypeId); Assert.AreEqual(propTypes.ElementAt(j).MemberCanViewProperty, result.MemberCanViewProperty(result.PropertyTypes.ElementAt(j).Alias)); Assert.AreEqual(propTypes.ElementAt(j).MemberCanEditProperty, result.MemberCanEditProperty(result.PropertyTypes.ElementAt(j).Alias)); Assert.AreEqual(propTypes.ElementAt(j).IsSensitiveData, result.IsSensitiveProperty(result.PropertyTypes.ElementAt(j).Alias)); } } Assert.AreEqual(display.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); for (var i = 0; i < display.AllowedContentTypes.Count(); i++) { Assert.AreEqual(display.AllowedContentTypes.ElementAt(i), result.AllowedContentTypes.ElementAt(i).Id.Value); } } [Test] public void MediaTypeSave_To_IMediaType() { //Arrange // setup the mocks to return the data we want to test against... _dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>())) .Returns(Mock.Of<IDataType>( definition => definition.Id == 555 && definition.EditorAlias == "myPropertyType" && definition.DatabaseType == ValueStorageType.Nvarchar)); var display = CreateMediaTypeSave(); //Act var result = Mapper.Map<IMediaType>(display); //Assert Assert.AreEqual(display.Alias, result.Alias); Assert.AreEqual(display.Description, result.Description); Assert.AreEqual(display.Icon, result.Icon); Assert.AreEqual(display.Id, result.Id); Assert.AreEqual(display.Name, result.Name); Assert.AreEqual(display.ParentId, result.ParentId); Assert.AreEqual(display.Path, result.Path); Assert.AreEqual(display.Thumbnail, result.Thumbnail); Assert.AreEqual(display.IsContainer, result.IsContainer); Assert.AreEqual(display.AllowAsRoot, result.AllowedAsRoot); Assert.AreEqual(display.CreateDate, result.CreateDate); Assert.AreEqual(display.UpdateDate, result.UpdateDate); //TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(display.Groups.Count(), result.PropertyGroups.Count); for (var i = 0; i < display.Groups.Count(); i++) { Assert.AreEqual(display.Groups.ElementAt(i).Id, result.PropertyGroups.ElementAt(i).Id); Assert.AreEqual(display.Groups.ElementAt(i).Name, result.PropertyGroups.ElementAt(i).Name); var propTypes = display.Groups.ElementAt(i).Properties; Assert.AreEqual(propTypes.Count(), result.PropertyTypes.Count()); for (var j = 0; j < propTypes.Count(); j++) { Assert.AreEqual(propTypes.ElementAt(j).Id, result.PropertyTypes.ElementAt(j).Id); Assert.AreEqual(propTypes.ElementAt(j).DataTypeId, result.PropertyTypes.ElementAt(j).DataTypeId); } } Assert.AreEqual(display.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); for (var i = 0; i < display.AllowedContentTypes.Count(); i++) { Assert.AreEqual(display.AllowedContentTypes.ElementAt(i), result.AllowedContentTypes.ElementAt(i).Id.Value); } } [Test] public void ContentTypeSave_To_IContentType() { //Arrange // setup the mocks to return the data we want to test against... _dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>())) .Returns(Mock.Of<IDataType>( definition => definition.Id == 555 && definition.EditorAlias == "myPropertyType" && definition.DatabaseType == ValueStorageType.Nvarchar)); _fileService.Setup(x => x.GetTemplate(It.IsAny<string>())) .Returns((string alias) => Mock.Of<ITemplate>( definition => definition.Id == alias.GetHashCode() && definition.Alias == alias)); var display = CreateContentTypeSave(); //Act var result = Mapper.Map<IContentType>(display); //Assert Assert.AreEqual(display.Alias, result.Alias); Assert.AreEqual(display.Description, result.Description); Assert.AreEqual(display.Icon, result.Icon); Assert.AreEqual(display.Id, result.Id); Assert.AreEqual(display.Name, result.Name); Assert.AreEqual(display.ParentId, result.ParentId); Assert.AreEqual(display.Path, result.Path); Assert.AreEqual(display.Thumbnail, result.Thumbnail); Assert.AreEqual(display.IsContainer, result.IsContainer); Assert.AreEqual(display.AllowAsRoot, result.AllowedAsRoot); Assert.AreEqual(display.CreateDate, result.CreateDate); Assert.AreEqual(display.UpdateDate, result.UpdateDate); //TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(display.Groups.Count(), result.PropertyGroups.Count); for (var i = 0; i < display.Groups.Count(); i++) { Assert.AreEqual(display.Groups.ElementAt(i).Id, result.PropertyGroups.ElementAt(i).Id); Assert.AreEqual(display.Groups.ElementAt(i).Name, result.PropertyGroups.ElementAt(i).Name); var propTypes = display.Groups.ElementAt(i).Properties; Assert.AreEqual(propTypes.Count(), result.PropertyTypes.Count()); for (var j = 0; j < propTypes.Count(); j++) { Assert.AreEqual(propTypes.ElementAt(j).Id, result.PropertyTypes.ElementAt(j).Id); Assert.AreEqual(propTypes.ElementAt(j).DataTypeId, result.PropertyTypes.ElementAt(j).DataTypeId); } } var allowedTemplateAliases = display.AllowedTemplates .Concat(new[] {display.DefaultTemplate}) .Distinct(); Assert.AreEqual(allowedTemplateAliases.Count(), result.AllowedTemplates.Count()); for (var i = 0; i < display.AllowedTemplates.Count(); i++) { Assert.AreEqual(display.AllowedTemplates.ElementAt(i), result.AllowedTemplates.ElementAt(i).Alias); } Assert.AreEqual(display.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); for (var i = 0; i < display.AllowedContentTypes.Count(); i++) { Assert.AreEqual(display.AllowedContentTypes.ElementAt(i), result.AllowedContentTypes.ElementAt(i).Id.Value); } } [Test] public void MediaTypeSave_With_Composition_To_IMediaType() { //Arrange // setup the mocks to return the data we want to test against... _dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>())) .Returns(Mock.Of<IDataType>( definition => definition.Id == 555 && definition.EditorAlias == "myPropertyType" && definition.DatabaseType == ValueStorageType.Nvarchar)); var display = CreateCompositionMediaTypeSave(); //Act var result = Mapper.Map<IMediaType>(display); //Assert //TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(display.Groups.Count(x => x.Inherited == false), result.PropertyGroups.Count); } [Test] public void ContentTypeSave_With_Composition_To_IContentType() { //Arrange // setup the mocks to return the data we want to test against... _dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>())) .Returns(Mock.Of<IDataType>( definition => definition.Id == 555 && definition.EditorAlias == "myPropertyType" && definition.DatabaseType == ValueStorageType.Nvarchar)); var display = CreateCompositionContentTypeSave(); //Act var result = Mapper.Map<IContentType>(display); //Assert //TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(display.Groups.Count(x => x.Inherited == false), result.PropertyGroups.Count); } [Test] public void IMemberType_To_MemberTypeDisplay() { //Arrange // setup the mocks to return the data we want to test against... var memberType = MockedContentTypes.CreateSimpleMemberType(); memberType.MemberTypePropertyTypes[memberType.PropertyTypes.Last().Alias] = new MemberTypePropertyProfileAccess(true, true, true); MockedContentTypes.EnsureAllIds(memberType, 8888); //Act var result = Mapper.Map<MemberTypeDisplay>(memberType); //Assert Assert.AreEqual(memberType.Alias, result.Alias); Assert.AreEqual(memberType.Description, result.Description); Assert.AreEqual(memberType.Icon, result.Icon); Assert.AreEqual(memberType.Id, result.Id); Assert.AreEqual(memberType.Name, result.Name); Assert.AreEqual(memberType.ParentId, result.ParentId); Assert.AreEqual(memberType.Path, result.Path); Assert.AreEqual(memberType.Thumbnail, result.Thumbnail); Assert.AreEqual(memberType.IsContainer, result.IsContainer); Assert.AreEqual(memberType.CreateDate, result.CreateDate); Assert.AreEqual(memberType.UpdateDate, result.UpdateDate); //TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(memberType.PropertyGroups.Count(), result.Groups.Count()); for (var i = 0; i < memberType.PropertyGroups.Count(); i++) { Assert.AreEqual(memberType.PropertyGroups.ElementAt(i).Id, result.Groups.ElementAt(i).Id); Assert.AreEqual(memberType.PropertyGroups.ElementAt(i).Name, result.Groups.ElementAt(i).Name); var propTypes = memberType.PropertyGroups.ElementAt(i).PropertyTypes; Assert.AreEqual(propTypes.Count(), result.Groups.ElementAt(i).Properties.Count()); for (var j = 0; j < propTypes.Count(); j++) { Assert.AreEqual(propTypes.ElementAt(j).Id, result.Groups.ElementAt(i).Properties.ElementAt(j).Id); Assert.AreEqual(propTypes.ElementAt(j).DataTypeId, result.Groups.ElementAt(i).Properties.ElementAt(j).DataTypeId); Assert.AreEqual(memberType.MemberCanViewProperty(propTypes.ElementAt(j).Alias), result.Groups.ElementAt(i).Properties.ElementAt(j).MemberCanViewProperty); Assert.AreEqual(memberType.MemberCanEditProperty(propTypes.ElementAt(j).Alias), result.Groups.ElementAt(i).Properties.ElementAt(j).MemberCanEditProperty); } } Assert.AreEqual(memberType.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); for (var i = 0; i < memberType.AllowedContentTypes.Count(); i++) { Assert.AreEqual(memberType.AllowedContentTypes.ElementAt(i).Id.Value, result.AllowedContentTypes.ElementAt(i)); } } [Test] public void IMediaType_To_MediaTypeDisplay() { //Arrange // setup the mocks to return the data we want to test against... var mediaType = MockedContentTypes.CreateImageMediaType(); MockedContentTypes.EnsureAllIds(mediaType, 8888); //Act var result = Mapper.Map<MediaTypeDisplay>(mediaType); //Assert Assert.AreEqual(mediaType.Alias, result.Alias); Assert.AreEqual(mediaType.Description, result.Description); Assert.AreEqual(mediaType.Icon, result.Icon); Assert.AreEqual(mediaType.Id, result.Id); Assert.AreEqual(mediaType.Name, result.Name); Assert.AreEqual(mediaType.ParentId, result.ParentId); Assert.AreEqual(mediaType.Path, result.Path); Assert.AreEqual(mediaType.Thumbnail, result.Thumbnail); Assert.AreEqual(mediaType.IsContainer, result.IsContainer); Assert.AreEqual(mediaType.CreateDate, result.CreateDate); Assert.AreEqual(mediaType.UpdateDate, result.UpdateDate); //TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(mediaType.PropertyGroups.Count(), result.Groups.Count()); for (var i = 0; i < mediaType.PropertyGroups.Count(); i++) { Assert.AreEqual(mediaType.PropertyGroups.ElementAt(i).Id, result.Groups.ElementAt(i).Id); Assert.AreEqual(mediaType.PropertyGroups.ElementAt(i).Name, result.Groups.ElementAt(i).Name); var propTypes = mediaType.PropertyGroups.ElementAt(i).PropertyTypes; Assert.AreEqual(propTypes.Count(), result.Groups.ElementAt(i).Properties.Count()); for (var j = 0; j < propTypes.Count(); j++) { Assert.AreEqual(propTypes.ElementAt(j).Id, result.Groups.ElementAt(i).Properties.ElementAt(j).Id); Assert.AreEqual(propTypes.ElementAt(j).DataTypeId, result.Groups.ElementAt(i).Properties.ElementAt(j).DataTypeId); } } Assert.AreEqual(mediaType.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); for (var i = 0; i < mediaType.AllowedContentTypes.Count(); i++) { Assert.AreEqual(mediaType.AllowedContentTypes.ElementAt(i).Id.Value, result.AllowedContentTypes.ElementAt(i)); } } [Test] public void IContentType_To_ContentTypeDisplay() { //Arrange // setup the mocks to return the data we want to test against... var contentType = MockedContentTypes.CreateTextPageContentType(); MockedContentTypes.EnsureAllIds(contentType, 8888); //Act var result = Mapper.Map<DocumentTypeDisplay>(contentType); //Assert Assert.AreEqual(contentType.Alias, result.Alias); Assert.AreEqual(contentType.Description, result.Description); Assert.AreEqual(contentType.Icon, result.Icon); Assert.AreEqual(contentType.Id, result.Id); Assert.AreEqual(contentType.Name, result.Name); Assert.AreEqual(contentType.ParentId, result.ParentId); Assert.AreEqual(contentType.Path, result.Path); Assert.AreEqual(contentType.Thumbnail, result.Thumbnail); Assert.AreEqual(contentType.IsContainer, result.IsContainer); Assert.AreEqual(contentType.CreateDate, result.CreateDate); Assert.AreEqual(contentType.UpdateDate, result.UpdateDate); Assert.AreEqual(contentType.DefaultTemplate.Alias, result.DefaultTemplate.Alias); //TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(contentType.PropertyGroups.Count, result.Groups.Count()); for (var i = 0; i < contentType.PropertyGroups.Count; i++) { Assert.AreEqual(contentType.PropertyGroups[i].Id, result.Groups.ElementAt(i).Id); Assert.AreEqual(contentType.PropertyGroups[i].Name, result.Groups.ElementAt(i).Name); var propTypes = contentType.PropertyGroups[i].PropertyTypes; Assert.AreEqual(propTypes.Count, result.Groups.ElementAt(i).Properties.Count()); for (var j = 0; j < propTypes.Count; j++) { Assert.AreEqual(propTypes[j].Id, result.Groups.ElementAt(i).Properties.ElementAt(j).Id); Assert.AreEqual(propTypes[j].DataTypeId, result.Groups.ElementAt(i).Properties.ElementAt(j).DataTypeId); } } Assert.AreEqual(contentType.AllowedTemplates.Count(), result.AllowedTemplates.Count()); for (var i = 0; i < contentType.AllowedTemplates.Count(); i++) { Assert.AreEqual(contentType.AllowedTemplates.ElementAt(i).Id, result.AllowedTemplates.ElementAt(i).Id); } Assert.AreEqual(contentType.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); for (var i = 0; i < contentType.AllowedContentTypes.Count(); i++) { Assert.AreEqual(contentType.AllowedContentTypes.ElementAt(i).Id.Value, result.AllowedContentTypes.ElementAt(i)); } } [Test] public void MemberPropertyGroupBasic_To_MemberPropertyGroup() { _dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>())) .Returns(new DataType(new VoidEditor(Mock.Of<ILogger>()))); var basic = new PropertyGroupBasic<MemberPropertyTypeBasic> { Id = 222, Name = "Group 1", SortOrder = 1, Properties = new[] { new MemberPropertyTypeBasic() { MemberCanEditProperty = true, MemberCanViewProperty = true, IsSensitiveData = true, Id = 33, SortOrder = 1, Alias = "prop1", Description = "property 1", DataTypeId = 99, GroupId = 222, Label = "Prop 1", Validation = new PropertyTypeValidation() { Mandatory = true, Pattern = null } }, new MemberPropertyTypeBasic() { MemberCanViewProperty = false, MemberCanEditProperty = false, IsSensitiveData = false, Id = 34, SortOrder = 2, Alias = "prop2", Description = "property 2", DataTypeId = 99, GroupId = 222, Label = "Prop 2", Validation = new PropertyTypeValidation() { Mandatory = false, Pattern = null } }, } }; var contentType = new MemberTypeSave { Id = 0, ParentId = -1, Alias = "alias", Groups = new[] { basic } }; // proper group properties mapping takes place when mapping the content type, // not when mapping the group - because of inherited properties and such //var result = Mapper.Map<PropertyGroup>(basic); var result = Mapper.Map<IMemberType>(contentType).PropertyGroups[0]; Assert.AreEqual(basic.Name, result.Name); Assert.AreEqual(basic.Id, result.Id); Assert.AreEqual(basic.SortOrder, result.SortOrder); Assert.AreEqual(basic.Properties.Count(), result.PropertyTypes.Count()); } [Test] public void PropertyGroupBasic_To_PropertyGroup() { _dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>())) .Returns(new DataType(new VoidEditor(Mock.Of<ILogger>()))); var basic = new PropertyGroupBasic<PropertyTypeBasic> { Id = 222, Name = "Group 1", SortOrder = 1, Properties = new[] { new PropertyTypeBasic() { Id = 33, SortOrder = 1, Alias = "prop1", Description = "property 1", DataTypeId = 99, GroupId = 222, Label = "Prop 1", Validation = new PropertyTypeValidation() { Mandatory = true, Pattern = null } }, new PropertyTypeBasic() { Id = 34, SortOrder = 2, Alias = "prop2", Description = "property 2", DataTypeId = 99, GroupId = 222, Label = "Prop 2", Validation = new PropertyTypeValidation() { Mandatory = false, Pattern = null } }, } }; var contentType = new DocumentTypeSave { Id = 0, ParentId = -1, Alias = "alias", AllowedTemplates = Enumerable.Empty<string>(), Groups = new[] { basic } }; // proper group properties mapping takes place when mapping the content type, // not when mapping the group - because of inherited properties and such //var result = Mapper.Map<PropertyGroup>(basic); var result = Mapper.Map<IContentType>(contentType).PropertyGroups[0]; Assert.AreEqual(basic.Name, result.Name); Assert.AreEqual(basic.Id, result.Id); Assert.AreEqual(basic.SortOrder, result.SortOrder); Assert.AreEqual(basic.Properties.Count(), result.PropertyTypes.Count()); } [Test] public void MemberPropertyTypeBasic_To_PropertyType() { _dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>())) .Returns(new DataType(new VoidEditor(Mock.Of<ILogger>()))); var basic = new MemberPropertyTypeBasic() { Id = 33, SortOrder = 1, Alias = "prop1", Description = "property 1", DataTypeId = 99, GroupId = 222, Label = "Prop 1", Validation = new PropertyTypeValidation() { Mandatory = true, Pattern = "xyz" } }; var result = Mapper.Map<PropertyType>(basic); Assert.AreEqual(basic.Id, result.Id); Assert.AreEqual(basic.SortOrder, result.SortOrder); Assert.AreEqual(basic.Alias, result.Alias); Assert.AreEqual(basic.Description, result.Description); Assert.AreEqual(basic.DataTypeId, result.DataTypeId); Assert.AreEqual(basic.Label, result.Name); Assert.AreEqual(basic.Validation.Mandatory, result.Mandatory); Assert.AreEqual(basic.Validation.Pattern, result.ValidationRegExp); } [Test] public void PropertyTypeBasic_To_PropertyType() { _dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>())) .Returns(new DataType(new VoidEditor(Mock.Of<ILogger>()))); var basic = new PropertyTypeBasic() { Id = 33, SortOrder = 1, Alias = "prop1", Description = "property 1", DataTypeId = 99, GroupId = 222, Label = "Prop 1", Validation = new PropertyTypeValidation() { Mandatory = true, Pattern = "xyz" } }; var result = Mapper.Map<PropertyType>(basic); Assert.AreEqual(basic.Id, result.Id); Assert.AreEqual(basic.SortOrder, result.SortOrder); Assert.AreEqual(basic.Alias, result.Alias); Assert.AreEqual(basic.Description, result.Description); Assert.AreEqual(basic.DataTypeId, result.DataTypeId); Assert.AreEqual(basic.Label, result.Name); Assert.AreEqual(basic.Validation.Mandatory, result.Mandatory); Assert.AreEqual(basic.Validation.Pattern, result.ValidationRegExp); } [Test] public void IMediaTypeComposition_To_MediaTypeDisplay() { //Arrange // setup the mocks to return the data we want to test against... _entityService.Setup(x => x.GetObjectType(It.IsAny<int>())) .Returns(UmbracoObjectTypes.DocumentType); var ctMain = MockedContentTypes.CreateSimpleMediaType("parent", "Parent"); //not assigned to tab ctMain.AddPropertyType(new PropertyType(Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) { Alias = "umbracoUrlName", Name = "Slug", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 }); MockedContentTypes.EnsureAllIds(ctMain, 8888); var ctChild1 = MockedContentTypes.CreateSimpleMediaType("child1", "Child 1", ctMain, true); ctChild1.AddPropertyType(new PropertyType(Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) { Alias = "someProperty", Name = "Some Property", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 }, "Another tab"); MockedContentTypes.EnsureAllIds(ctChild1, 7777); var contentType = MockedContentTypes.CreateSimpleMediaType("child2", "Child 2", ctChild1, true, "CustomGroup"); //not assigned to tab contentType.AddPropertyType(new PropertyType(Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) { Alias = "umbracoUrlAlias", Name = "AltUrl", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 }); MockedContentTypes.EnsureAllIds(contentType, 6666); //Act var result = Mapper.Map<MediaTypeDisplay>(contentType); //Assert Assert.AreEqual(contentType.Alias, result.Alias); Assert.AreEqual(contentType.Description, result.Description); Assert.AreEqual(contentType.Icon, result.Icon); Assert.AreEqual(contentType.Id, result.Id); Assert.AreEqual(contentType.Name, result.Name); Assert.AreEqual(contentType.ParentId, result.ParentId); Assert.AreEqual(contentType.Path, result.Path); Assert.AreEqual(contentType.Thumbnail, result.Thumbnail); Assert.AreEqual(contentType.IsContainer, result.IsContainer); Assert.AreEqual(contentType.CreateDate, result.CreateDate); Assert.AreEqual(contentType.UpdateDate, result.UpdateDate); //TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(contentType.CompositionPropertyGroups.Select(x => x.Name).Distinct().Count(), result.Groups.Count(x => x.IsGenericProperties == false)); Assert.AreEqual(1, result.Groups.Count(x => x.IsGenericProperties)); Assert.AreEqual(contentType.PropertyGroups.Count(), result.Groups.Count(x => x.Inherited == false && x.IsGenericProperties == false)); var allPropertiesMapped = result.Groups.SelectMany(x => x.Properties).ToArray(); var allPropertyIdsMapped = allPropertiesMapped.Select(x => x.Id).ToArray(); var allSourcePropertyIds = contentType.CompositionPropertyTypes.Select(x => x.Id).ToArray(); Assert.AreEqual(contentType.PropertyTypes.Count(), allPropertiesMapped.Count(x => x.Inherited == false)); Assert.AreEqual(allPropertyIdsMapped.Count(), allSourcePropertyIds.Count()); Assert.IsTrue(allPropertyIdsMapped.ContainsAll(allSourcePropertyIds)); Assert.AreEqual(2, result.Groups.Count(x => x.ParentTabContentTypes.Any())); Assert.IsTrue(result.Groups.SelectMany(x => x.ParentTabContentTypes).ContainsAll(new[] { ctMain.Id, ctChild1.Id })); Assert.AreEqual(contentType.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); for (var i = 0; i < contentType.AllowedContentTypes.Count(); i++) { Assert.AreEqual(contentType.AllowedContentTypes.ElementAt(i).Id.Value, result.AllowedContentTypes.ElementAt(i)); } } [Test] public void IContentTypeComposition_To_ContentTypeDisplay() { //Arrange // setup the mocks to return the data we want to test against... _entityService.Setup(x => x.GetObjectType(It.IsAny<int>())) .Returns(UmbracoObjectTypes.DocumentType); var ctMain = MockedContentTypes.CreateSimpleContentType(); //not assigned to tab ctMain.AddPropertyType(new PropertyType(Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) { Alias = "umbracoUrlName", Name = "Slug", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 }); MockedContentTypes.EnsureAllIds(ctMain, 8888); var ctChild1 = MockedContentTypes.CreateSimpleContentType("child1", "Child 1", ctMain, true); ctChild1.AddPropertyType(new PropertyType(Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) { Alias = "someProperty", Name = "Some Property", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 }, "Another tab"); MockedContentTypes.EnsureAllIds(ctChild1, 7777); var contentType = MockedContentTypes.CreateSimpleContentType("child2", "Child 2", ctChild1, true, "CustomGroup"); //not assigned to tab contentType.AddPropertyType(new PropertyType(Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) { Alias = "umbracoUrlAlias", Name = "AltUrl", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 }); MockedContentTypes.EnsureAllIds(contentType, 6666); //Act var result = Mapper.Map<DocumentTypeDisplay>(contentType); //Assert Assert.AreEqual(contentType.Alias, result.Alias); Assert.AreEqual(contentType.Description, result.Description); Assert.AreEqual(contentType.Icon, result.Icon); Assert.AreEqual(contentType.Id, result.Id); Assert.AreEqual(contentType.Name, result.Name); Assert.AreEqual(contentType.ParentId, result.ParentId); Assert.AreEqual(contentType.Path, result.Path); Assert.AreEqual(contentType.Thumbnail, result.Thumbnail); Assert.AreEqual(contentType.IsContainer, result.IsContainer); Assert.AreEqual(contentType.CreateDate, result.CreateDate); Assert.AreEqual(contentType.UpdateDate, result.UpdateDate); Assert.AreEqual(contentType.DefaultTemplate.Alias, result.DefaultTemplate.Alias); //TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(contentType.CompositionPropertyGroups.Select(x => x.Name).Distinct().Count(), result.Groups.Count(x => x.IsGenericProperties == false)); Assert.AreEqual(1, result.Groups.Count(x => x.IsGenericProperties)); Assert.AreEqual(contentType.PropertyGroups.Count(), result.Groups.Count(x => x.Inherited == false && x.IsGenericProperties == false)); var allPropertiesMapped = result.Groups.SelectMany(x => x.Properties).ToArray(); var allPropertyIdsMapped = allPropertiesMapped.Select(x => x.Id).ToArray(); var allSourcePropertyIds = contentType.CompositionPropertyTypes.Select(x => x.Id).ToArray(); Assert.AreEqual(contentType.PropertyTypes.Count(), allPropertiesMapped.Count(x => x.Inherited == false)); Assert.AreEqual(allPropertyIdsMapped.Count(), allSourcePropertyIds.Count()); Assert.IsTrue(allPropertyIdsMapped.ContainsAll(allSourcePropertyIds)); Assert.AreEqual(2, result.Groups.Count(x => x.ParentTabContentTypes.Any())); Assert.IsTrue(result.Groups.SelectMany(x => x.ParentTabContentTypes).ContainsAll(new[] {ctMain.Id, ctChild1.Id})); Assert.AreEqual(contentType.AllowedTemplates.Count(), result.AllowedTemplates.Count()); for (var i = 0; i < contentType.AllowedTemplates.Count(); i++) { Assert.AreEqual(contentType.AllowedTemplates.ElementAt(i).Id, result.AllowedTemplates.ElementAt(i).Id); } Assert.AreEqual(contentType.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); for (var i = 0; i < contentType.AllowedContentTypes.Count(); i++) { Assert.AreEqual(contentType.AllowedContentTypes.ElementAt(i).Id.Value, result.AllowedContentTypes.ElementAt(i)); } } [Test] public void MemberPropertyTypeBasic_To_MemberPropertyTypeDisplay() { _dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>())) .Returns(new DataType(new VoidEditor(Mock.Of<ILogger>()))); var basic = new MemberPropertyTypeBasic() { Id = 33, SortOrder = 1, Alias = "prop1", Description = "property 1", DataTypeId = 99, GroupId = 222, Label = "Prop 1", MemberCanViewProperty = true, MemberCanEditProperty = true, IsSensitiveData = true, Validation = new PropertyTypeValidation() { Mandatory = true, Pattern = "xyz" } }; var result = Mapper.Map<MemberPropertyTypeDisplay>(basic); Assert.AreEqual(basic.Id, result.Id); Assert.AreEqual(basic.SortOrder, result.SortOrder); Assert.AreEqual(basic.Alias, result.Alias); Assert.AreEqual(basic.Description, result.Description); Assert.AreEqual(basic.GroupId, result.GroupId); Assert.AreEqual(basic.Inherited, result.Inherited); Assert.AreEqual(basic.Label, result.Label); Assert.AreEqual(basic.Validation, result.Validation); Assert.AreEqual(basic.MemberCanViewProperty, result.MemberCanViewProperty); Assert.AreEqual(basic.MemberCanEditProperty, result.MemberCanEditProperty); Assert.AreEqual(basic.IsSensitiveData, result.IsSensitiveData); } [Test] public void PropertyTypeBasic_To_PropertyTypeDisplay() { _dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>())) .Returns(new DataType(new VoidEditor(Mock.Of<ILogger>()))); var basic = new PropertyTypeBasic() { Id = 33, SortOrder = 1, Alias = "prop1", Description = "property 1", DataTypeId = 99, GroupId = 222, Label = "Prop 1", Validation = new PropertyTypeValidation() { Mandatory = true, Pattern = "xyz" } }; var result = Mapper.Map<PropertyTypeDisplay>(basic); Assert.AreEqual(basic.Id, result.Id); Assert.AreEqual(basic.SortOrder, result.SortOrder); Assert.AreEqual(basic.Alias, result.Alias); Assert.AreEqual(basic.Description, result.Description); Assert.AreEqual(basic.GroupId, result.GroupId); Assert.AreEqual(basic.Inherited, result.Inherited); Assert.AreEqual(basic.Label, result.Label); Assert.AreEqual(basic.Validation, result.Validation); } private MemberTypeSave CreateMemberTypeSave() { return new MemberTypeSave { Alias = "test", AllowAsRoot = true, AllowedContentTypes = new[] { 666, 667 }, Description = "hello world", Icon = "tree-icon", Id = 1234, Key = new Guid("8A60656B-3866-46AB-824A-48AE85083070"), Name = "My content type", Path = "-1,1234", ParentId = -1, Thumbnail = "tree-thumb", IsContainer = true, Groups = new[] { new PropertyGroupBasic<MemberPropertyTypeBasic>() { Id = 987, Name = "Tab 1", SortOrder = 0, Inherited = false, Properties = new [] { new MemberPropertyTypeBasic { MemberCanEditProperty = true, MemberCanViewProperty = true, IsSensitiveData = true, Alias = "property1", Description = "this is property 1", Inherited = false, Label = "Property 1", Validation = new PropertyTypeValidation { Mandatory = false, Pattern = "" }, SortOrder = 0, DataTypeId = 555 } } } } }; } private MediaTypeSave CreateMediaTypeSave() { return new MediaTypeSave { Alias = "test", AllowAsRoot = true, AllowedContentTypes = new[] { 666, 667 }, Description = "hello world", Icon = "tree-icon", Id = 1234, Key = new Guid("8A60656B-3866-46AB-824A-48AE85083070"), Name = "My content type", Path = "-1,1234", ParentId = -1, Thumbnail = "tree-thumb", IsContainer = true, Groups = new[] { new PropertyGroupBasic<PropertyTypeBasic>() { Id = 987, Name = "Tab 1", SortOrder = 0, Inherited = false, Properties = new [] { new PropertyTypeBasic { Alias = "property1", Description = "this is property 1", Inherited = false, Label = "Property 1", Validation = new PropertyTypeValidation { Mandatory = false, Pattern = "" }, SortOrder = 0, DataTypeId = 555 } } } } }; } private DocumentTypeSave CreateContentTypeSave() { return new DocumentTypeSave { Alias = "test", AllowAsRoot = true, AllowedTemplates = new [] { "template1", "template2" }, AllowedContentTypes = new [] {666, 667}, DefaultTemplate = "test", Description = "hello world", Icon = "tree-icon", Id = 1234, Key = new Guid("8A60656B-3866-46AB-824A-48AE85083070"), Name = "My content type", Path = "-1,1234", ParentId = -1, Thumbnail = "tree-thumb", IsContainer = true, Groups = new [] { new PropertyGroupBasic<PropertyTypeBasic>() { Id = 987, Name = "Tab 1", SortOrder = 0, Inherited = false, Properties = new [] { new PropertyTypeBasic { Alias = "property1", Description = "this is property 1", Inherited = false, Label = "Property 1", Validation = new PropertyTypeValidation { Mandatory = false, Pattern = "" }, SortOrder = 0, DataTypeId = 555 } } } } }; } private MediaTypeSave CreateCompositionMediaTypeSave() { return new MediaTypeSave { Alias = "test", AllowAsRoot = true, AllowedContentTypes = new[] { 666, 667 }, Description = "hello world", Icon = "tree-icon", Id = 1234, Key = new Guid("8A60656B-3866-46AB-824A-48AE85083070"), Name = "My content type", Path = "-1,1234", ParentId = -1, Thumbnail = "tree-thumb", IsContainer = true, Groups = new[] { new PropertyGroupBasic<PropertyTypeBasic>() { Id = 987, Name = "Tab 1", SortOrder = 0, Inherited = false, Properties = new[] { new PropertyTypeBasic { Alias = "property1", Description = "this is property 1", Inherited = false, Label = "Property 1", Validation = new PropertyTypeValidation { Mandatory = false, Pattern = "" }, SortOrder = 0, DataTypeId = 555 } } }, new PropertyGroupBasic<PropertyTypeBasic>() { Id = 894, Name = "Tab 2", SortOrder = 0, Inherited = true, Properties = new[] { new PropertyTypeBasic { Alias = "parentProperty", Description = "this is a property from the parent", Inherited = true, Label = "Parent property", Validation = new PropertyTypeValidation { Mandatory = false, Pattern = "" }, SortOrder = 0, DataTypeId = 555 } } } } }; } private DocumentTypeSave CreateCompositionContentTypeSave() { return new DocumentTypeSave { Alias = "test", AllowAsRoot = true, AllowedTemplates = new[] { "template1", "template2" }, AllowedContentTypes = new[] { 666, 667 }, DefaultTemplate = "test", Description = "hello world", Icon = "tree-icon", Id = 1234, Key = new Guid("8A60656B-3866-46AB-824A-48AE85083070"), Name = "My content type", Path = "-1,1234", ParentId = -1, Thumbnail = "tree-thumb", IsContainer = true, Groups = new[] { new PropertyGroupBasic<PropertyTypeBasic>() { Id = 987, Name = "Tab 1", SortOrder = 0, Inherited = false, Properties = new[] { new PropertyTypeBasic { Alias = "property1", Description = "this is property 1", Inherited = false, Label = "Property 1", Validation = new PropertyTypeValidation { Mandatory = false, Pattern = "" }, SortOrder = 0, DataTypeId = 555 } } }, new PropertyGroupBasic<PropertyTypeBasic>() { Id = 894, Name = "Tab 2", SortOrder = 0, Inherited = true, Properties = new[] { new PropertyTypeBasic { Alias = "parentProperty", Description = "this is a property from the parent", Inherited = true, Label = "Parent property", Validation = new PropertyTypeValidation { Mandatory = false, Pattern = "" }, SortOrder = 0, DataTypeId = 555 } } } } }; } } }
using Server; using System; using Server.Misc; using Server.Mobiles; namespace Server.Items { public class AncientFarmersKasa : Kasa { public override int LabelNumber{ get{ return 1070922; } } // Ancient Farmer's Kasa public override int BaseColdResistance { get { return 19; } } public override int InitMinHits{ get{ return 255; } } public override int InitMaxHits{ get { return 255; } } [Constructable] public AncientFarmersKasa() : base() { Attributes.BonusStr = 5; Attributes.BonusStam = 5; Attributes.RegenStam = 5; SkillBonuses.SetValues( 0, SkillName.AnimalLore, 5.0 ); } public AncientFarmersKasa( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 2 ); } public override void Deserialize(GenericReader reader) { base.Deserialize( reader ); int version = reader.ReadInt(); if ( version <= 1 ) { MaxHitPoints = 255; HitPoints = 255; } if( version == 0 ) SkillBonuses.SetValues( 0, SkillName.AnimalLore, 5.0 ); } } public class AncientSamuraiDo : PlateDo { public override int LabelNumber { get { return 1070926; } } // Ancient Samurai Do public override int BasePhysicalResistance { get { return 15; } } public override int BaseFireResistance { get { return 12; } } public override int BaseColdResistance { get { return 10; } } public override int BasePoisonResistance { get { return 11; } } public override int BaseEnergyResistance { get { return 8; } } [Constructable] public AncientSamuraiDo() : base() { ArmorAttributes.LowerStatReq = 100; ArmorAttributes.MageArmor = 1; SkillBonuses.SetValues( 0, SkillName.Parry, 10.0 ); } public AncientSamuraiDo( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int)0 ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } public override int InitMinHits { get { return 255; } } public override int InitMaxHits { get { return 255; } } } public class ArmsOfTacticalExcellence : LeatherHiroSode { public override int LabelNumber { get { return 1070921; } } // Arms of Tactical Excellence public override int BaseFireResistance { get { return 9; } } public override int BaseColdResistance { get { return 13; } } public override int BasePoisonResistance { get { return 8; } } [Constructable] public ArmsOfTacticalExcellence() : base() { Attributes.BonusDex = 5; SkillBonuses.SetValues( 0, SkillName.Tactics, 12.0 ); } public ArmsOfTacticalExcellence( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int)0 ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } public override int InitMinHits { get { return 255; } } public override int InitMaxHits { get { return 255; } } } public class BlackLotusHood : ClothNinjaHood { public override int LabelNumber { get { return 1070919; } } // Black Lotus Hood public override int BasePhysicalResistance { get { return 0; } } public override int BaseFireResistance { get { return 11; } } public override int BaseColdResistance { get { return 15; } } public override int BasePoisonResistance { get { return 11; } } public override int BaseEnergyResistance { get { return 11; } } public override int InitMinHits { get { return 255; } } public override int InitMaxHits { get { return 255; } } [Constructable] public BlackLotusHood() : base() { Attributes.LowerManaCost = 6; Attributes.AttackChance = 6; ClothingAttributes.SelfRepair = 5; } public BlackLotusHood( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int)1 ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); if ( version == 0 ) { MaxHitPoints = 255; HitPoints = 255; } } } public class DaimyosHelm : PlateBattleKabuto { public override int LabelNumber { get { return 1070920; } } // Daimyo's Helm public override int BaseColdResistance { get { return 10; } } [Constructable] public DaimyosHelm() : base() { ArmorAttributes.LowerStatReq = 100; ArmorAttributes.MageArmor = 1; ArmorAttributes.SelfRepair = 3; Attributes.WeaponSpeed = 10; } public DaimyosHelm( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int)0 ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } public override int InitMinHits { get { return 255; } } public override int InitMaxHits { get { return 255; } } } public class DemonForks : Sai { public override int LabelNumber{ get{ return 1070917; } } // Demon Forks [Constructable] public DemonForks() : base() { WeaponAttributes.ResistFireBonus = 10; WeaponAttributes.ResistPoisonBonus = 10; Attributes.ReflectPhysical = 10; Attributes.WeaponDamage = 35; Attributes.DefendChance = 10; } public DemonForks( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int)0 ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } public override int InitMinHits { get { return 255; } } public override int InitMaxHits { get { return 255; } } } public class DragonNunchaku : Nunchaku { public override int LabelNumber{ get{ return 1070914; } } // Dragon Nunchaku [Constructable] public DragonNunchaku() : base() { WeaponAttributes.ResistFireBonus = 5; WeaponAttributes.SelfRepair = 3; WeaponAttributes.HitFireball = 50; Attributes.WeaponDamage = 40; Attributes.WeaponSpeed = 20; } public DragonNunchaku( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int)0 ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } public override int InitMinHits { get { return 255; } } public override int InitMaxHits { get { return 255; } } } public class Exiler : Tetsubo { public override int LabelNumber{ get{ return 1070913; } } // Exiler [Constructable] public Exiler() : base() { WeaponAttributes.HitDispel = 33; Slayer = SlayerName.Exorcism; Attributes.WeaponDamage = 40; Attributes.WeaponSpeed = 20; } public override void GetDamageTypes( Mobile wielder, out int phys, out int fire, out int cold, out int pois, out int nrgy, out int chaos, out int direct ) { phys = fire = cold = pois = chaos = direct = 0; nrgy = 100; } public Exiler( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int)0 ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } public override int InitMinHits { get { return 255; } } public override int InitMaxHits { get { return 255; } } } public class GlovesOfTheSun : LeatherNinjaMitts { public override int LabelNumber { get { return 1070924; } } // Gloves of the Sun public override int BaseFireResistance { get { return 24; } } [Constructable] public GlovesOfTheSun() : base() { Attributes.RegenHits = 2; Attributes.NightSight = 1; Attributes.LowerManaCost = 5; Attributes.LowerRegCost = 18; } public GlovesOfTheSun( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int)0 ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } public override int InitMinHits { get { return 255; } } public override int InitMaxHits { get { return 255; } } } public class HanzosBow : Yumi { public override int LabelNumber { get { return 1070918; } } // Hanzo's Bow [Constructable] public HanzosBow() : base() { WeaponAttributes.HitLeechHits = 40; WeaponAttributes.SelfRepair = 3; Attributes.WeaponDamage = 50; SkillBonuses.SetValues( 0, SkillName.Ninjitsu, 10 ); } public HanzosBow( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int)0 ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } public override int InitMinHits { get { return 255; } } public override int InitMaxHits { get { return 255; } } } public class LegsOfStability : PlateSuneate { public override int LabelNumber { get { return 1070925; } } // Legs of Stability public override int BasePhysicalResistance { get { return 20; } } public override int BasePoisonResistance { get { return 18; } } [Constructable] public LegsOfStability() : base() { Attributes.BonusStam = 5; ArmorAttributes.SelfRepair = 3; ArmorAttributes.LowerStatReq = 100; ArmorAttributes.MageArmor = 1; } public LegsOfStability( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int)0 ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } public override int InitMinHits { get { return 255; } } public override int InitMaxHits { get { return 255; } } } public class PeasantsBokuto : Bokuto { public override int LabelNumber { get { return 1070912; } } // Peasant's Bokuto [Constructable] public PeasantsBokuto() : base() { WeaponAttributes.SelfRepair = 3; WeaponAttributes.HitLowerDefend = 30; Attributes.WeaponDamage = 35; Attributes.WeaponSpeed = 10; Slayer = SlayerName.SnakesBane; } public PeasantsBokuto( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int)0 ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } public override int InitMinHits { get { return 255; } } public override int InitMaxHits { get { return 255; } } } public class PilferedDancerFans : Tessen { public override int LabelNumber { get { return 1070916; } } // Pilfered Dancer Fans [Constructable] public PilferedDancerFans() : base() { Attributes.WeaponDamage = 20; Attributes.WeaponSpeed = 20; Attributes.CastRecovery = 2; Attributes.DefendChance = 5; Attributes.SpellChanneling = 1; } public PilferedDancerFans( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int)0 ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } public override int InitMinHits { get { return 255; } } public override int InitMaxHits { get { return 255; } } } public class TheDestroyer : NoDachi { public override int LabelNumber { get { return 1070915; } } // The Destroyer [Constructable] public TheDestroyer() : base() { WeaponAttributes.HitLeechStam = 40; Attributes.BonusStr = 6; Attributes.AttackChance = 10; Attributes.WeaponDamage = 50; } public TheDestroyer( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int)0 ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } public override int InitMinHits { get { return 255; } } public override int InitMaxHits { get { return 255; } } } public class TomeOfEnlightenment : Spellbook { public override int LabelNumber { get { return 1070934; } } // Tome of Enlightenment [Constructable] public TomeOfEnlightenment() : base() { LootType = LootType.Regular; Hue = 0x455; Attributes.BonusInt = 5; Attributes.SpellDamage = 10; Attributes.CastSpeed = 1; } public TomeOfEnlightenment( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int)0 ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } public class LeurociansMempoOfFortune : LeatherMempo { public override int LabelNumber { get { return 1071460; } } // Leurocian's mempo of fortune public override int BasePhysicalResistance{ get{ return 15; } } public override int BaseFireResistance{ get{ return 10; } } public override int BaseColdResistance{ get{ return 10; } } public override int BasePoisonResistance{ get{ return 10; } } public override int BaseEnergyResistance{ get{ return 15; } } [Constructable] public LeurociansMempoOfFortune() : base() { LootType = LootType.Regular; Hue = 0x501; Attributes.Luck = 300; Attributes.RegenMana = 1; } public LeurociansMempoOfFortune( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int)0 ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } public override int InitMinHits { get { return 255; } } public override int InitMaxHits { get { return 255; } } } //Non weapon/armor ones: public class AncientUrn : Item { private static string[] m_Names = new string[] { "Akira", "Avaniaga", "Aya", "Chie", "Emiko", "Fumiyo", "Gennai", "Gennosuke", "Genjo", "Hamato", "Harumi", "Ikuyo", "Juri", "Kaori", "Kaoru", "Kiyomori", "Mayako", "Motoki", "Musashi", "Nami", "Nobukazu", "Roku", "Romi", "Ryo", "Sanzo", "Sakamae", "Satoshi", "Takamori", "Takuro", "Teruyo", "Toshiro", "Yago", "Yeijiro", "Yoshi", "Zeshin" }; public static string[] Names { get { return m_Names; } } private string m_UrnName; [CommandProperty( AccessLevel.GameMaster )] public string UrnName { get { return m_UrnName; } set { m_UrnName = value; } } public override int LabelNumber { get { return 1071014; } } // Ancient Urn [Constructable] public AncientUrn( string urnName ) : base( 0x241D ) { m_UrnName = urnName; Weight = 1.0; } [Constructable] public AncientUrn() : this( m_Names[Utility.Random( m_Names.Length )] ) { } public AncientUrn( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int)0 ); writer.Write( m_UrnName ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); m_UrnName = reader.ReadString(); Utility.Intern( ref m_UrnName ); } public override void AddNameProperty( ObjectPropertyList list ) { list.Add( 1070935, m_UrnName ); // Ancient Urn of ~1_name~ } public override void OnSingleClick( Mobile from ) { LabelTo( from, 1070935, m_UrnName ); // Ancient Urn of ~1_name~ } } public class HonorableSwords : Item { private string m_SwordsName; [CommandProperty( AccessLevel.GameMaster )] public string SwordsName { get { return m_SwordsName; } set { m_SwordsName = value; } } public override int LabelNumber { get { return 1071015; } } // Honorable Swords [Constructable] public HonorableSwords( string swordsName ) : base( 0x2853 ) { m_SwordsName = swordsName; Weight = 5.0; } [Constructable] public HonorableSwords() : this( AncientUrn.Names[Utility.Random( AncientUrn.Names.Length )] ) { } public HonorableSwords( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int)0 ); writer.Write( m_SwordsName ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); m_SwordsName = reader.ReadString(); Utility.Intern( ref m_SwordsName ); } public override void AddNameProperty( ObjectPropertyList list ) { list.Add( 1070936, m_SwordsName ); // Honorable Swords of ~1_name~ } public override void OnSingleClick( Mobile from ) { LabelTo( from, 1070936, m_SwordsName ); // Honorable Swords of ~1_name~ } } [Flipable( 0x2811, 0x2812 )] public class ChestOfHeirlooms : LockableContainer { public override int LabelNumber{ get{ return 1070937; } } // Chest of heirlooms [Constructable] public ChestOfHeirlooms() : base( 0x2811 ) { Locked = true; LockLevel = 95; MaxLockLevel = 140; RequiredSkill = 95; TrapType = TrapType.ExplosionTrap; TrapLevel = 10; TrapPower = 100; GumpID = 0x10B; for ( int i = 0; i < 10; ++i ) { Item item = Loot.ChestOfHeirloomsContains(); int attributeCount = Utility.RandomMinMax( 1, 5 ); int min = 20; int max = 80; if ( item is BaseWeapon ) { BaseWeapon weapon = (BaseWeapon)item; if ( Core.AOS ) BaseRunicTool.ApplyAttributesTo( weapon, attributeCount, min, max ); else { weapon.DamageLevel = (WeaponDamageLevel)Utility.Random( 6 ); weapon.AccuracyLevel = (WeaponAccuracyLevel)Utility.Random( 6 ); weapon.DurabilityLevel = (WeaponDurabilityLevel)Utility.Random( 6 ); } } else if ( item is BaseArmor ) { BaseArmor armor = (BaseArmor)item; if ( Core.AOS ) BaseRunicTool.ApplyAttributesTo( armor, attributeCount, min, max ); else { armor.ProtectionLevel = (ArmorProtectionLevel)Utility.Random( 6 ); armor.Durability = (ArmorDurabilityLevel)Utility.Random( 6 ); } } else if( item is BaseHat && Core.AOS ) BaseRunicTool.ApplyAttributesTo( (BaseHat)item, attributeCount, min, max ); else if( item is BaseJewel && Core.AOS ) BaseRunicTool.ApplyAttributesTo( (BaseJewel)item, attributeCount, min, max ); DropItem( item ); } } public ChestOfHeirlooms( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } public class FluteOfRenewal : BambooFlute { public override int LabelNumber { get { return 1070927; } } // Flute of Renewal [Constructable] public FluteOfRenewal() : base() { Slayer = SlayerGroup.Groups[Utility.Random( SlayerGroup.Groups.Length - 1 )].Super.Name; //-1 to exclude Fey slayer. Try to confrim no fey slayer on this on OSI ReplenishesCharges = true; } public override int InitMinUses { get { return 300; } } public override int InitMaxUses { get { return 300; } } public FluteOfRenewal( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 1 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); if( version == 0 && Slayer == SlayerName.Fey ) Slayer = SlayerGroup.Groups[Utility.Random( SlayerGroup.Groups.Length - 1 )].Super.Name; } } public enum LesserPigmentType { None, PaleOrange, FreshRose, ChaosBlue, Silver, NobleGold, LightGreen, PaleBlue, FreshPlum, DeepBrown, BurntBrown } public class LesserPigmentsOfTokuno : BasePigmentsOfTokuno { private static int[][] m_Table = new int[][] { // Hue, Label new int[]{ /*PigmentType.None,*/ 0, -1 }, new int[]{ /*PigmentType.PaleOrange,*/ 0x02E, 1071458 }, new int[]{ /*PigmentType.FreshRose,*/ 0x4B9, 1071455 }, new int[]{ /*PigmentType.ChaosBlue,*/ 0x005, 1071459 }, new int[]{ /*PigmentType.Silver,*/ 0x3E9, 1071451 }, new int[]{ /*PigmentType.NobleGold,*/ 0x227, 1071457 }, new int[]{ /*PigmentType.LightGreen,*/ 0x1C8, 1071454 }, new int[]{ /*PigmentType.PaleBlue,*/ 0x24F, 1071456 }, new int[]{ /*PigmentType.FreshPlum,*/ 0x145, 1071450 }, new int[]{ /*PigmentType.DeepBrown,*/ 0x3F0, 1071452 }, new int[]{ /*PigmentType.BurntBrown,*/ 0x41A, 1071453 } }; public static int[] GetInfo( LesserPigmentType type ) { int v = (int)type; if( v < 0 || v >= m_Table.Length ) v = 0; return m_Table[v]; } private LesserPigmentType m_Type; [CommandProperty( AccessLevel.GameMaster )] public LesserPigmentType Type { get { return m_Type; } set { m_Type = value; int v = (int)m_Type; if ( v >= 0 && v < m_Table.Length ) { Hue = m_Table[v][0]; Label = m_Table[v][1]; } else { Hue = 0; Label = -1; } } } [Constructable] public LesserPigmentsOfTokuno() : this( (LesserPigmentType)Utility.Random(0,11) ) { } [Constructable] public LesserPigmentsOfTokuno( LesserPigmentType type ) : base( 1 ) { Weight = 1.0; Type = type; } public LesserPigmentsOfTokuno( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int)1 ); writer.WriteEncodedInt( (int)m_Type ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = ( InheritsItem ? 0 : reader.ReadInt() ); // Required for BasePigmentsOfTokuno insertion switch ( version ) { case 1: Type = (LesserPigmentType)reader.ReadEncodedInt(); break; case 0: break; } } } public class MetalPigmentsOfTokuno : BasePigmentsOfTokuno { [Constructable] public MetalPigmentsOfTokuno() : base( 1 ) { RandomHue(); Label = -1; } public MetalPigmentsOfTokuno( Serial serial ) : base( serial ) { } public void RandomHue() { int a = Utility.Random(0,30); if ( a != 0 ) Hue = a + 0x960; else Hue = 0; } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int)0 ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = ( InheritsItem ? 0 : reader.ReadInt() ); // Required for BasePigmentsOfTokuno insertion } } }
/****************************************************************************/ /* */ /* The Mondo Libraries */ /* */ /* Namespace: Mondo.Database */ /* File: Database.cs */ /* Class(es): Database */ /* Purpose: A connection to a database */ /* */ /* Original Author: Jim Lightfoot */ /* Creation Date: 12 Sep 2001 */ /* */ /* Copyright (c) 2001-2017 - Jim Lightfoot, All rights reserved */ /* */ /* Licensed under the MIT license: */ /* http://www.opensource.org/licenses/mit-license.php */ /* */ /****************************************************************************/ using Mondo.Common; using Mondo.Xml; using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.IO; using System.Security; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Xml.XPath; namespace Mondo.Database { /****************************************************************************/ /****************************************************************************/ /// <summary> /// A connection string for a database /// </summary> public class ConnectionString { private string _connectionString; private string _type = ""; /****************************************************************************/ public ConnectionString(string connectionString, string type) { _connectionString = connectionString; _type = type; } /****************************************************************************/ public ConnectionString(string connectionString) { _connectionString = connectionString; } /****************************************************************************/ public static string Format(IConfig config, string connectionString, bool bLookup) { if (connectionString.Normalized() == "") { connectionString = "ConnectionString"; bLookup = true; } if (bLookup) connectionString = Lookup(config, connectionString); return (connectionString); } /****************************************************************************/ public static string Normalize(string connectionString) { connectionString = connectionString.Replace("mondo=oledb", ""); connectionString = connectionString.Replace("mondo=odbc", ""); connectionString = connectionString.Replace(";;", ";"); if (connectionString.StartsWith(";")) connectionString = connectionString.Substring(1); return connectionString; } /*************************************************************************/ /// <summary> /// Lookup the actual connection string in the web.config /// </summary> /// <param name="connectionStringParam"></param> public static string Lookup(IConfig config, string connectionStringParam) { return config.GetConnectionString(connectionStringParam); } /****************************************************************************/ public string Type { get { return (_type); } } /****************************************************************************/ public override string ToString() { return _connectionString; } } /****************************************************************************/ /****************************************************************************/ /// <summary> /// A connection to a database /// </summary> public abstract class Database : Openable { protected string _connectionString = ""; private DbConnection _connection = null; private DbTransaction _transaction = null; private readonly DbProviderFactory _factory; private readonly RetryPolicy _retryPolicy = new DatabaseRetryPolicy(); private static string[] _aOLEDBProviders = new string[] { "msdaora", "oledb", "sqlncl", "mysqlprov" }; private static string[] _aODBCProviders = new string[] { "odbc", "sql server native client", "sql native client", "driver={mysql}", "orahome92" }; /*************************************************************************/ /// <summary> /// Construct the database with a static connection string. /// </summary> protected Database(DbProviderFactory factory, IConfig config) : this(factory, config, "", true) { } /*************************************************************************/ /// <summary> /// Construct the database with the given connection string name. /// </summary> /// <param name="connectionString">The name of the connection string. The actual connection string is in the ConnectionStrings config section in the web.config. (if bLookup is true)</param> /// <param name="bLookup">If true then connectionString is alias to a value in the web.config, otherwise it's the actual connection string</param> protected Database(DbProviderFactory factory, IConfig config, string connectionString, bool bLookup) { _factory = factory; _connectionString = ConnectionString.Format(config, connectionString, bLookup); this.CommandTimeout = config.Get<int>("CommandTimeout", 60); } /*************************************************************************/ public int CommandTimeout { set; get; } /*************************************************************************/ public RetryPolicy RetryPolicy { get { return _retryPolicy; } } /*************************************************************************/ public static Database Create(IConfig config = null) { return Create("", true, config); } /*************************************************************************/ public static Database Create(string connectionString, IConfig config = null) { return Create(connectionString, false, config); } /*************************************************************************/ public static Database Create(string connectionString, bool bLookup, IConfig config = null) { if (config == null) config = new AppConfig(); connectionString = ConnectionString.Format(config, connectionString, bLookup); if (IsIn(connectionString, _aOLEDBProviders)) return new OleDbDatabase(config, connectionString, false); if (IsIn(connectionString, _aODBCProviders)) return (new OdbcDatabase(config, connectionString, false)); return new SqlDatabase(config, connectionString, false); } /****************************************************************************/ public override void Open() { try { if (!IsOpen) { _connection = _factory.CreateConnection(); try { _connection.ConnectionString = _connectionString; } catch (Exception ex) { throw new DatabaseException("Invalid connection string format", ex); } _connection.Open(); } base.Open(); } catch (Exception ex) { throw ex; } } /****************************************************************************/ public async override Task OpenAsync() { try { if (!IsOpen) { _connection = _factory.CreateConnection(); try { _connection.ConnectionString = _connectionString; } catch (Exception ex) { throw new DatabaseException("Invalid connection string format", ex); } await _connection.OpenAsync(); } await base.OpenAsync(); } catch (Exception ex) { throw ex; } } /****************************************************************************/ public override void Close() { base.Close(); if (!IsOpen) { try { Rollback(); _connection.Close(); _connection.Dispose(); _connection = null; } catch { } } } /****************************************************************************/ public DbConnection Connection { get { return _connection; } } /*************************************************************************/ public DbTransaction Transaction { get { return _transaction; } } /*************************************************************************/ public void BeginTransaction() { _transaction = _connection.BeginTransaction(); } /*************************************************************************/ public void Commit() { if (_transaction != null) { _transaction.Commit(); _transaction.Dispose(); _transaction = null; } } /*************************************************************************/ public void Rollback() { if (_transaction != null) { _transaction.Rollback(); _transaction.Dispose(); _transaction = null; } } /*************************************************************************/ public StoredProc CreateStoredProc(string strName) { return new StoredProc(this, strName); } /*************************************************************************/ public StoredProc StoredProc(string strName) { return new StoredProc(this, strName); } /****************************************************************************/ public DbCommand MakeSelectCommand(string strSelect) { DbCommand command = MakeCommand(); command.CommandText = strSelect; command.CommandType = CommandType.Text; return command; } /****************************************************************************/ public DbCommand MakeCommand(StoredProc sp) { DbCommand command = MakeCommand(); command.CommandText = sp.Name; command.CommandType = CommandType.StoredProcedure; command.CommandTimeout = this.CommandTimeout; return command; } /****************************************************************************/ public DbCommand MakeCommand() { DbCommand command = _factory.CreateCommand(); if (_transaction != null) command.Transaction = _transaction; return command; } #region CreateParameter /****************************************************************************/ public DbParameter CreateParameter(string parameterName, DbType dbType, int size, ParameterDirection direction, bool isNullable, byte precision, byte scale, string sourceColumn, DataRowVersion sourceVersion, object value) { DbParameter parameter = _factory.CreateParameter(); parameter.ParameterName = parameterName; parameter.DbType = dbType; parameter.Direction = direction; parameter.SourceColumnNullMapping = isNullable; parameter.SourceColumn = sourceColumn; parameter.SourceVersion = sourceVersion; parameter.Value = value; if (size > 0) parameter.Size = size; return parameter; } /****************************************************************************/ public DbParameter CreateParameter(string parameterName, DbType dbType) { DbParameter parameter = _factory.CreateParameter(); parameter.ParameterName = parameterName; parameter.DbType = dbType; parameter.Direction = ParameterDirection.Input; parameter.SourceColumnNullMapping = true; parameter.SourceVersion = DataRowVersion.Default; return parameter; } /****************************************************************************/ public DbParameter CreateParameter(string parameterName, object data) { DbParameter parameter = _factory.CreateParameter(); parameter.ParameterName = parameterName; parameter.Value = data; return parameter; } #endregion #region ExecuteSelect /****************************************************************************/ public DbDataReader ExecuteSelect(string strSelect, CommandBehavior eBehavior = CommandBehavior.Default) { DbCommand objCommand = MakeSelectCommand(strSelect); return (ExecuteSelect(objCommand, eBehavior)); } /************************************************************************/ public async Task<DbDataReader> ExecuteSelectAsync(string strSelect, CommandBehavior eBehavior = CommandBehavior.Default) { DbCommand objCommand = MakeSelectCommand(strSelect); return await ExecuteSelectAsync(objCommand, eBehavior); } /****************************************************************************/ public async Task<DbDataReader> ExecuteSelectAsync(DbCommand cmd, CommandBehavior eBehavior = CommandBehavior.Default) { return await ExecuteAsync(cmd, async (dbCommand) => { return await dbCommand.ExecuteReaderAsync(eBehavior); }); } /****************************************************************************/ public DbDataReader ExecuteSelect(DbCommand cmd, CommandBehavior eBehavior = CommandBehavior.Default) { return Execute<DbDataReader>(cmd, (dbCommand) => { return dbCommand.ExecuteReader(eBehavior); }); } #endregion #region ExecuteDataSet /****************************************************************************/ public DataSet ExecuteDataSet(string strSelect) { using (DbCommand cmd = MakeSelectCommand(strSelect)) { return ExecuteDataSet(cmd); } } /****************************************************************************/ public DataSet ExecuteDataSet(Operation sp) { return ExecuteDataSet(sp.Command); } /****************************************************************************/ public DataSet ExecuteDataSet(DbCommand cmd) { return Execute<DataSet>(cmd, (dbCommand) => { DataSet dataSet = null; using (DbDataAdapter objAdapter = _factory.CreateDataAdapter()) { objAdapter.SelectCommand = dbCommand; dataSet = new DataSet("_data"); dataSet.EnforceConstraints = false; objAdapter.Fill(dataSet); } return dataSet; }); } #endregion #region ExecuteForXml /****************************************************************************/ public XmlDocument ExecuteForXml(Operation sp) { return ExecuteForXml(sp.Command); } /****************************************************************************/ public XmlDocument ExecuteForXml(DbCommand cmd) { return Execute<XmlDocument>(cmd, (dbCommand) => { using (XmlReader objReader = (dbCommand as SqlCommand).ExecuteXmlReader()) { while (objReader.Read()) return XmlDoc.Load(objReader); } return null; }); } #endregion /****************************************************************************/ public DBRow ExecuteSingleRow(string strSelect) { return new DBRow(ExecuteDataTable(strSelect)); } /****************************************************************************/ public DBRow ExecuteSingleRow(DbCommand cmd) { return new DBRow(ExecuteDataTable(cmd)); } /****************************************************************************/ public DBRow ExecuteSingleRow(Operation sp) { return new DBRow(ExecuteDataTable(sp)); } /****************************************************************************/ public void ExecuteNonQuery(DbCommand cmd) { DoTask(cmd); } /****************************************************************************/ public void ExecuteNonQuery(Operation sp) { DoTask(sp); } /****************************************************************************/ public void ExecuteNonQuery(string strSQL) { DoTask(strSQL); } #region ExecuteDataSourceList Methods /****************************************************************************/ public DataSourceList ExecuteDataSourceList(string strSelect) { return new DBRowList(ExecuteDataTable(strSelect)); } /****************************************************************************/ public DataSourceList ExecuteDataSourceList(Operation sp) { return new DBRowList(ExecuteDataTable(sp)); } /****************************************************************************/ public DataSourceList ExecuteDataSourceList(DbCommand objCommand) { return new DBRowList(ExecuteDataTable(objCommand)); } #endregion ExecuteDataSourceList Methods #region ExecuteDataTable /****************************************************************************/ public DataTable ExecuteDataTable(string strSelect) { using (DbCommand objCommand = MakeSelectCommand(strSelect)) { return ExecuteDataTable(objCommand); } } /****************************************************************************/ public DataTable ExecuteDataTable(Operation sp) { return ExecuteDataTable(sp.Command); } /****************************************************************************/ public DataTable ExecuteDataTable(DbCommand cmd) { return Execute<DataTable>(cmd, (dbCommand) => { DataTable dataTable = null; using (DbDataAdapter objAdapter = _factory.CreateDataAdapter()) { objAdapter.SelectCommand = dbCommand; dataTable = new DataTable("_data"); objAdapter.Fill(dataTable); } return dataTable; }); } #endregion ExecuteDataTable #region ExecuteList Methods /****************************************************************************/ public IList<T> ExecuteList<T>(string strSelect) where T : new() { return ExecuteDataTable(strSelect).ToList<T>(); } /****************************************************************************/ public IList<T> ExecuteList<T>(Operation sp) where T : new() { return ExecuteDataTable(sp).ToList<T>(); } /****************************************************************************/ public IList<T> ExecuteList<T>(DbCommand objCommand) where T : new() { return ExecuteDataTable(objCommand).ToList<T>(); } #endregion ExecuteList Methods #region Dictionary Methods /****************************************************************************/ public Dictionary<string, string> ExecuteDictionary(string strSelect, string idKeyField, string idValueField, IDictionary<string, string> map = null) { using (DataTable dt = this.ExecuteDataTable(strSelect)) { return ToDictionary(dt, idKeyField, idValueField, map); } } /****************************************************************************/ public Dictionary<string, string> ExecuteDictionary(Operation op, string idKeyField, string idValueField, IDictionary<string, string> map = null) { using (DataTable dt = this.ExecuteDataTable(op)) { return ToDictionary(dt, idKeyField, idValueField, map); } } /**********************************************************************/ public async Task<IDictionary<string, object>> ExecuteSingleRecordDictionaryAsync(Operation op, IDictionary<string, string> map = null) { return await ExecuteSingleRecordDictionaryAsync(op.Command, map); } /**********************************************************************/ public async Task<IDictionary<string, object>> ExecuteSingleRecordDictionaryAsync(DbCommand cmd, IDictionary<string, string> map = null) { return await ExecuteAsync<IDictionary<string, object>>(cmd, async (dbCommand) => { using (DbDataReader reader = await this.ExecuteSelectAsync(cmd)) { IDictionary<string, object> result = await ToSingleRecordDictionaryAsync(reader, map); return result; } }); } /****************************************************************************/ public IDictionary<string, object> ExecuteSingleRecordDictionary(Operation op, IDictionary<string, string> map = null) { return ExecuteSingleRecordDictionary(op.Command, map); } /****************************************************************************/ public IDictionary<string, object> ExecuteSingleRecordDictionary(DbCommand cmd, IDictionary<string, string> map = null) { return Execute<IDictionary<string, object>>(cmd, (dbCommand) => { using (DbDataReader reader = this.ExecuteSelect(cmd)) { IDictionary<string, object> result = ToSingleRecordDictionary(reader, map); return result; } }); } /****************************************************************************/ public static async Task<IDictionary<string, object>> ToSingleRecordDictionaryAsync(DbDataReader reader, IDictionary<string, string> map = null) { var values = new Dictionary<string, object>(); if (await reader.ReadAsync()) { int nFields = reader.FieldCount; for (int i = 0; i < nFields; ++i) { var isNull = await reader.IsDBNullAsync(i); var name = reader.GetName(i); if (map != null && map.ContainsKey(name)) name = map[name]; values.Add(name, isNull ? null : reader[i]); } } return values; } /****************************************************************************/ public static IDictionary<string, object> ToSingleRecordDictionary(DbDataReader reader, IDictionary<string, string> map = null) { var values = new Dictionary<string, object>(); if (reader.Read()) { int nFields = reader.FieldCount; for (int i = 0; i < nFields; ++i) { bool isNull = reader.IsDBNull(i); string name = reader.GetName(i); if (map != null && map.ContainsKey(name)) name = map[name]; values.Add(name, isNull ? null : reader[i]); } } return values; } /****************************************************************************/ public static Dictionary<string, string> ToDictionary(DataTable dt, string idKeyField, string idValueField, IDictionary<string, string> map = null) { var dict = new Dictionary<string, string>(137); var aRows = new DBRowList(dt); foreach (IDataObjectSource row in aRows) { string name = row.Get(idKeyField); if (map != null && map.ContainsKey(name)) name = map[name]; dict.Add(name, row.Get(idValueField)); } return dict; } #endregion Dictionary Methods #region DoTask /********************************************************************/ public async Task DoTaskAsync(string strSelect) { using (DbCommand objCommand = MakeSelectCommand(strSelect)) { await DoTaskAsync(objCommand); } return; } /********************************************************************/ public async Task DoTaskAsync(Operation objProc) { await DoTaskAsync(objProc.Command); } /********************************************************************/ public async Task DoTaskAsync(DbCommand objCommand) { if (this.IsOpen) { objCommand.Connection = this.Connection; await Retry.RunAsync(async () => { await objCommand.ExecuteNonQueryAsync(); }, this.RetryPolicy); } else { using (Acquire o = await this.AcquireAsync()) await DoTaskAsync(objCommand); } return; } /****************************************************************************/ public void DoTask(string strSelect) { using (DbCommand objCommand = MakeSelectCommand(strSelect)) { DoTask(objCommand); } return; } /****************************************************************************/ public void DoTask(Operation objProc) { DoTask(objProc.Command); } /****************************************************************************/ public void DoTask(DbCommand objCommand) { if (this.IsOpen) { objCommand.Connection = this.Connection; Retry.Run(() => { objCommand.ExecuteNonQuery(); }, this.RetryPolicy); } else { using (Acquire o = new Acquire(this)) DoTask(objCommand); } return; } #endregion DoTask #region ExecuteXml /****************************************************************************/ public XmlDocument ExecuteXml(string strSelect) { using (DbCommand cmd = MakeSelectCommand(strSelect)) { return ExecuteXml(cmd); } } /****************************************************************************/ public XmlDocument ExecuteXml(Operation objProc) { return ExecuteXml(objProc.Command); } /****************************************************************************/ public XmlDocument ExecuteXml(DbCommand objCommand) { if (this.IsOpen) return XmlDoc.LoadXml(ExecuteDataSet(objCommand).GetXml()); using (Acquire o = new Acquire(this)) return ExecuteXml(objCommand); } /****************************************************************************/ public XmlDocument ExecuteXml(Operation objProc, string strDBName, IEnumerable aNames) { return ExecuteXml(objProc.Command, strDBName, aNames); } /****************************************************************************/ public XmlDocument ExecuteXml(Operation objProc, IEnumerable aNames) { return ExecuteXml(objProc.Command, "", aNames); } /****************************************************************************/ public XmlDocument ExecuteXml(DbCommand objCommand, string strDBName, IEnumerable aNames) { if (this.IsOpen) { using (DataSet dsData = ExecuteDataSet(objCommand)) { LabelDataSet(dsData, strDBName, aNames); return XmlDoc.LoadXml(dsData.GetXml()); } } using (Acquire o = new Acquire(this)) return ExecuteXml(objCommand, strDBName, aNames); } /****************************************************************************/ public async Task<string> ExecuteXmlAsync(Operation objProc, string dbName, IList<string> aNames) { return await ExecuteXmlAsync(objProc.Command, dbName, aNames); } /****************************************************************************/ public async Task<string> ExecuteXmlAsync(Operation objProc, IList<string> aNames) { return await ExecuteXmlAsync(objProc.Command, "", aNames); } /****************************************************************************/ public async Task<string> ExecuteXmlAsync(DbCommand cmd, string dbName, IList<string> aNames) { return await ExecuteAsync<string>(cmd, async (dbCommand) => { using (DbDataReader reader = await this.ExecuteSelectAsync(cmd)) { return await ToXmlAsync(reader, dbName, aNames); } }); } /****************************************************************************/ public int ExecuteXml(string strSelect, cXMLWriter writer, string type, bool bAttributes) { using (DbCommand cmd = MakeSelectCommand(strSelect)) { return ExecuteXml(cmd, writer, type, bAttributes); } } /****************************************************************************/ public int ExecuteXml(Operation objProc, cXMLWriter writer, string type, bool bAttributes) { return ExecuteXml(objProc.Command, writer, type, bAttributes); } /****************************************************************************/ public int ExecuteXml(DbCommand objCommand, cXMLWriter writer, string type, bool bAttributes) { if (this.IsOpen) return ToXml(ExecuteSelect(objCommand), writer, type, bAttributes); using (Acquire o = new Acquire(this)) return ExecuteXml(objCommand, writer, type, bAttributes); } /****************************************************************************/ public int ExecuteXml(string strSelect, cXMLWriter writer, string type) { return ExecuteXml(strSelect, writer, type, false); } #endregion ExecuteXml #region ExecuteXPath /****************************************************************************/ public IXPathNavigable ExecuteXPath(Operation objProc, IList<string> aNames) { return (ExecuteXPath(objProc, "", aNames)); } /****************************************************************************/ public IXPathNavigable ExecuteXPath(Operation objProc, string dbName, IList<string> aNames) { try { return (ExecuteXPath(objProc.Command, dbName, aNames)); } catch (Exception ex) { throw new StoredProcException(objProc, ex); } } /****************************************************************************/ public IXPathNavigable ExecuteXPath(DbCommand objCommand, string strDBName, IList<string> aNames) { if (this.IsOpen) { using (DbDataReader dbReader = ExecuteSelect(objCommand)) { using (XmlReader xmlReader = new DbXmlReader(dbReader, strDBName, aNames)) { return new XPathDocument(xmlReader); } } } using (Acquire o = new Acquire(this)) return ExecuteXPath(objCommand, strDBName, aNames); } /****************************************************************************/ private static XPathDocument XPathDocFromString(string strXml) { using (StringReader objReader = new StringReader(strXml)) { return new XPathDocument(objReader); } } #endregion ExecuteXPath #region Secure String Methods /****************************************************************************/ public SecureString QuerySecureString(DbCommand cmd) { byte[] aData = QueryBinary(cmd); // If the data isn't binary then this won't work if (aData == null) return (null); try { char[] aChars = Encoding.UTF8.GetChars(aData, 0, aData.Length); try { return (ToSecureString(aChars)); } finally { aChars.Clear(); } } finally { aData.Clear(); } } /****************************************************************************/ unsafe private static SecureString ToSecureString(char[] aChars) { SecureString str; fixed (char* pChars = aChars) { str = new SecureString(pChars, aChars.Length); } str.MakeReadOnly(); return (str); } /****************************************************************************/ public SecureString QuerySecureString(Operation objProc) { return (QuerySecureString(objProc.Command)); } #endregion Secure String Methods #region QueryBinary /****************************************************************************/ public byte[] QueryBinary(string strSelect) { using (DbCommand cmd = MakeSelectCommand(strSelect)) { return (QueryBinary(cmd)); } } /****************************************************************************/ public byte[] QueryBinary(Operation objProc) { return (QueryBinary(objProc.Command)); } /****************************************************************************/ public byte[] QueryBinary(DbCommand cmd) { object objResult = ExecuteScalar(cmd); return (objResult as byte[]); } /****************************************************************************/ public async Task<byte[]> QueryBinaryAsync(Operation objProc) { return await QueryBinaryAsync(objProc.Command); } /****************************************************************************/ public async Task<byte[]> QueryBinaryAsync(DbCommand cmd) { object objResult = await ExecuteScalarAsync(cmd); return (objResult as byte[]); } #endregion QueryBinary #region ExecuteScalar /****************************************************************************/ public object ExecuteScalar(string strSelect) { using (DbCommand cmd = MakeSelectCommand(strSelect)) { return (ExecuteScalar(cmd)); } } /****************************************************************************/ public object ExecuteScalar(Operation objProc) { return (ExecuteScalar(objProc.Command)); } /****************************************************************************/ public object ExecuteScalar(DbCommand cmd) { object objReturn = Execute<object>(cmd, (dbCommand) => { return dbCommand.ExecuteScalar(); }); if (objReturn == null) throw new NoValueException(); return (objReturn); } /****************************************************************************/ public T ExecuteScalar<T>(string strSelect) where T : struct { return Utility.Convert<T>(ExecuteScalar(strSelect)); } /****************************************************************************/ public T ExecuteScalar<T>(DbCommand cmd) where T : struct { return Utility.Convert<T>(ExecuteScalar(cmd)); } /****************************************************************************/ public T ExecuteScalar<T>(Operation objProc) where T : struct { return Utility.Convert<T>(ExecuteScalar(objProc)); } /****************************************************************************/ public async Task<object> ExecuteScalarAsync(string strSelect) { using (DbCommand cmd = MakeSelectCommand(strSelect)) { return await ExecuteScalarAsync(cmd); } } /****************************************************************************/ public async Task<T> ExecuteScalarAsync<T>(string strSelect) where T : struct { using (DbCommand cmd = MakeSelectCommand(strSelect)) { return await ExecuteScalarAsync<T>(cmd); } } /****************************************************************************/ public async Task<object> ExecuteScalarAsync(Operation objProc) { return await ExecuteScalarAsync(objProc.Command); } /****************************************************************************/ public async Task<T> ExecuteScalarAsync<T>(Operation objProc) where T : struct { return await ExecuteScalarAsync<T>(objProc.Command); } /****************************************************************************/ public async Task<object> ExecuteScalarAsync(DbCommand cmd) { return await ExecuteAsync(cmd, async (dbCommand) => { return await dbCommand.ExecuteScalarAsync(); }); } /****************************************************************************/ public async Task<T> ExecuteScalarAsync<T>(DbCommand cmd) where T : struct { return await ExecuteAsync(cmd, async (dbCommand) => { object val = await dbCommand.ExecuteScalarAsync(); return Utility.Convert<T>(val); }); } #endregion ExecuteScalar #region Exceptions /****************************************************************************/ /****************************************************************************/ public class DatabaseException : Exception { /****************************************************************************/ public DatabaseException(string msg) : base(msg) { } /****************************************************************************/ public DatabaseException(string msg, Exception ex) : base(msg, ex) { } } /****************************************************************************/ /****************************************************************************/ public class StoredProcException : DatabaseException { /****************************************************************************/ public StoredProcException(Operation op, Exception ex) : base("Failure executing stored proc: " + op.Name, ex) { } } /****************************************************************************/ /****************************************************************************/ public class NoValueException : DatabaseException { /****************************************************************************/ public NoValueException() : base("Unable to retrieve value from database") { } } #endregion Exceptions #region Utility Methods /****************************************************************************/ public static string Encode(string strData) { return (SubstituteList(strData, _encodeChars, _decodeChars, 8)); } /****************************************************************************/ public static string Decode(string strData) { return (SubstituteList(strData, _decodeChars, _encodeChars, 8)); } /****************************************************************************/ public static async Task<string> ToXmlAsync(DbDataReader reader, string dbName, IList<string> tableNames) { var writer = new cXMLWriter(); writer.WriteStartDocument(); { writer.WriteStartElement(dbName); { int index = -1; do { ++index; int nFields = -1; var tableName = tableNames[index]; while (await reader.ReadAsync()) { if (nFields == -1) nFields = reader.FieldCount; writer.WriteStartElement(tableName); { for (int i = 0; i < nFields; ++i) { bool isNull = await reader.IsDBNullAsync(i); if (!isNull) { string name = reader.GetName(i); object val = reader[i]; writer.WriteElementString(name, val.ToString().Trim()); } } } writer.WriteEndElement(); } } while (await reader.NextResultAsync()); } writer.WriteEndElement(); } writer.WriteEndDocument(); return writer.ToString(); } /****************************************************************************/ public static int ToXml(DbDataReader data, cXMLWriter writer, string type, bool bAttributes) { int nFields = data.FieldCount; int nRecords = 0; if (nFields == 0) { data.Close(); data = null; throw new DatabaseException("Database.ToXmlNodes: There are no fields in the results"); } while (data.Read()) { if (bAttributes) { writer.WriteStartElement(type); } else { writer.WriteStartElement("object"); writer.WriteAttributeString("type", type); } try { if (bAttributes) { for (int i = 0; i < nFields; ++i) writer.WriteAttributeString(data.GetName(i).ToLower(), string.Copy(data[i].ToString()).Trim(), true); } else { for (int i = 0; i < nFields; ++i) writer.WriteElementString(data.GetName(i).ToLower(), string.Copy(data[i].ToString()).Trim(), true); } } catch (Exception) { } ++nRecords; writer.WriteEndElement(); } data.Close(); data = null; return (nRecords); } /****************************************************************************/ public static string ToString(DbDataReader data) { int nFields = data.FieldCount; if (nFields == 0) { data.Close(); data = null; throw new DatabaseException("Database::ToString: There are no fields in the results"); } StringBuilder results = new StringBuilder(); while (data.Read()) { try { for (int i = 0; i < nFields; ++i) results.Append(data[i].ToString()); } catch (Exception) { } } data.Close(); data = null; return results.ToString(); } /****************************************************************************/ public static void LabelDataSet(DataSet ds, IEnumerable aNames) { LabelDataSet(ds, "", aNames); } /****************************************************************************/ public static void LabelDataSet(DataSet ds, string strDataSetName, IEnumerable aNames) { if (strDataSetName != "") ds.DataSetName = strDataSetName; if (aNames != null) { int iIndex = 0; int nTables = ds.Tables.Count; foreach (string strName in aNames) { if (iIndex == 0 && strDataSetName == "") { ds.DataSetName = strDataSetName = strName; continue; } if (nTables <= iIndex) break; ds.Tables[iIndex++].TableName = strName; } } } #endregion Utility Methods #region Private Methods private delegate Task<T> AsyncDelegate<T>(DbCommand objCommand); /****************************************************************************/ private async Task<T> ExecuteAsync<T>(DbCommand cmd, AsyncDelegate<T> fn) { if (this.IsOpen) { cmd.Connection = this.Connection; T obj = default(T); await Retry.RunAsync(async () => { obj = await fn(cmd); }, this.RetryPolicy); return obj; } else { using (Acquire o = await this.AcquireAsync()) return await ExecuteAsync<T>(cmd, fn); } } private delegate T SyncDelegate<T>(DbCommand objCommand); /****************************************************************************/ private T Execute<T>(DbCommand cmd, SyncDelegate<T> fn) { if (this.IsOpen) { cmd.Connection = this.Connection; T obj = default(T); Retry.Run(() => { obj = fn(cmd); }, this.RetryPolicy); return obj; } else { using (Acquire o = this.Acquire) return Execute<T>(cmd, fn); } } /****************************************************************************/ private static string[] _encodeChars = { "\'", "\"", ",", ".", ";", "\r", "\n", "<", ">", "(", ")" }; private static string[] _decodeChars = { "%27", "%22", "%2C", "%2E", "%3B", "%0D", "%0A", "%3C", "%3E", "%28", "%29" }; /****************************************************************************/ private static string SubstituteList(string strData, string[] strFind, string[] strReplace, uint nItems) { for (uint i = 0; i < nItems; ++i) strData = strData.Replace(strFind[i], strReplace[i]); return (strData); } /*************************************************************************/ private static bool IsIn(string connectionString, IEnumerable aList) { connectionString = connectionString.ToLower(); foreach (string strItem in aList) if (connectionString.Contains(strItem)) return (true); return (false); } /*************************************************************************/ /*************************************************************************/ private class DatabaseRetryPolicy : RetryPolicy { /*************************************************************************/ public DatabaseRetryPolicy(int iMaxRetries = RetryPolicy.kDefault, int iStartRetryWait = RetryPolicy.kDefault, double dRetryWaitIncrementFactor = RetryPolicy.kDefault) { } /*************************************************************************/ public override bool ShouldRetry(Exception ex) { string strMessage = ex.Message.ToLower(); if (strMessage.Contains("chosen as the deadlock victim")) return true; // Azure SQL message if (strMessage.Contains("is not currently available")) return true; return false; } } #endregion Private Methods } /****************************************************************************/ /****************************************************************************/ /// <summary> /// A connection to a SQL database /// </summary> public class SqlDatabase : Database { private StringList _aMessages = null; /****************************************************************************/ public SqlDatabase(IConfig config) : base(SqlClientFactory.Instance, config) { } /****************************************************************************/ public SqlDatabase(IConfig config, string connectionString, bool bLookup) : base(SqlClientFactory.Instance, config, ConnectionString.Normalize(connectionString), bLookup) { } /****************************************************************************/ public DataSet ExecuteDataSet(DbCommand cmd, out IList aMessages) { if (this.IsOpen) { _aMessages = new StringList(); (this.Connection as SqlConnection).InfoMessage += new SqlInfoMessageEventHandler(Database_InfoMessage); DataSet ds = base.ExecuteDataSet(cmd); aMessages = _aMessages; return (ds); } using (this.Acquire) return (ExecuteDataSet(cmd, out aMessages)); } /****************************************************************************/ public DataSet ExecuteDataSet(string strSelect, out IList aMessages) { using (DbCommand cmd = MakeSelectCommand(strSelect)) { return (ExecuteDataSet(cmd, out aMessages)); } } /****************************************************************************/ private void Database_InfoMessage(object sender, SqlInfoMessageEventArgs e) { _aMessages.Add(e.Message); } } /****************************************************************************/ /****************************************************************************/ /// <summary> /// A connection to an OLE DB database /// </summary> public class OleDbDatabase : Database { /****************************************************************************/ public OleDbDatabase(IConfig config) : base(System.Data.OleDb.OleDbFactory.Instance, config) { } /****************************************************************************/ public OleDbDatabase(IConfig config, string connectionString, bool bLookup) : base(System.Data.OleDb.OleDbFactory.Instance, config, ConnectionString.Normalize(connectionString), bLookup) { } } /****************************************************************************/ /****************************************************************************/ /// <summary> /// A connection to an ODBC database /// </summary> public class OdbcDatabase : Database { /****************************************************************************/ public OdbcDatabase(IConfig config) : base(System.Data.Odbc.OdbcFactory.Instance, config) { } /****************************************************************************/ public OdbcDatabase(IConfig config, string connectionString, bool bLookup) : base(System.Data.Odbc.OdbcFactory.Instance, config, ConnectionString.Normalize(connectionString), bLookup) { } } }
#if TODO_XAML using System; using System.Collections.Generic; using System.Threading.Tasks; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; namespace Eto.WinRT.CustomControls { public class SelectableTreeView : TreeView { static SelectableTreeView () { } public SelectableTreeView () { this.SelectedItemChanged += TreeViewItemChanged; } public static DependencyProperty CurrentTreeViewItemProperty = DependencyProperty.RegisterAttached( "CurrentTreeViewItem", typeof(TreeViewItem), typeof(SelectableTreeView), new PropertyMetadata()); public static TreeViewItem GetCurrentTreeViewItem(TreeView treeView) { return (TreeViewItem)treeView.GetValue(CurrentTreeViewItemProperty); } public static void SetCurrentTreeViewItem(TreeView treeView, TreeViewItem value) { treeView.SetValue(CurrentTreeViewItemProperty, value); } public TreeViewItem CurrentTreeViewItem { get { return GetCurrentTreeViewItem(this); } set { SetCurrentTreeViewItem(this, value); } } public static RoutedEvent CurrentItemChangedEvent = EventManager.RegisterRoutedEvent ( "CurrentItemChangedEvent", RoutingStrategy.Bubble, typeof (RoutedPropertyChangedEventHandler<object>), typeof (SelectableTreeView) ); public event RoutedPropertyChangedEventHandler<object> CurrentItemChanged { add { AddHandler (SelectableTreeView.CurrentItemChangedEvent, value); } remove { RemoveHandler(SelectableTreeView.CurrentItemChangedEvent, value); } } protected virtual void OnCurrentItemChanged (RoutedPropertyChangedEventArgs<object> e) { RaiseEvent(e); } public static DependencyProperty CurrentItemProperty = DependencyProperty.RegisterAttached( "CurrentItem", typeof(object), typeof(SelectableTreeView), new PropertyMetadata(new object(), OnCurrentItemChanged)); public static object GetCurrentItem (TreeView treeView) { return treeView.GetValue (CurrentItemProperty); } public static void SetCurrentItem (TreeView treeView, object value) { treeView.SetValue (CurrentItemProperty, value); } public object CurrentItem { get { return GetCurrentItem (this); } set { SetCurrentItem (this, value); } } public bool Refreshing { get { return refreshing; } } bool refreshing; public void RefreshData () { var selectedItem = CurrentItem; refreshing = true; Items.Refresh (); refreshing = false; if (IsLoaded) { SetSelected(selectedItem); } else { Loaded += (sender, e) => SetSelected(selectedItem); } //this.CurrentItem = selectedItem; } void SetSelected(object selectedItem) { FindItem(selectedItem, this).ContinueWith(t => { if (t.Result != null) { t.Result.IsSelected = true; } }, TaskScheduler.FromCurrentSynchronizationContext()); } protected override void OnItemsChanged (System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { if (!refreshing) base.OnItemsChanged (e); } static void OnCurrentItemChanged (DependencyObject d, DependencyPropertyChangedEventArgs args) { var treeView = d as SelectableTreeView; if (treeView == null) return; treeView.SelectedItemChanged -= TreeViewItemChanged; var treeViewItem = SelectTreeViewItemForBinding (args.NewValue, treeView); var newValue = args.NewValue; if (treeViewItem != null) { treeViewItem.IsSelected = true; treeView.CurrentTreeViewItem = treeViewItem; } else { newValue = treeView.SelectedItem; SetCurrentItem(treeView, newValue); } treeView.SelectedItemChanged += TreeViewItemChanged; treeView.OnCurrentItemChanged (new RoutedPropertyChangedEventArgs<object>(args.OldValue, newValue, CurrentItemChangedEvent)); } static void TreeViewItemChanged (object sender, RoutedPropertyChangedEventArgs<object> e) { var treeView = (SelectableTreeView)sender; if (!treeView.refreshing) treeView.SetValue (CurrentItemProperty, e.NewValue); } class Helper { readonly Dictionary<ItemContainerGenerator, ItemsControl> items = new Dictionary<ItemContainerGenerator, ItemsControl> (); readonly TaskCompletionSource<TreeViewItem> completion = new TaskCompletionSource<TreeViewItem> (); bool completed; public object SelectedItem { get; set; } public Task<TreeViewItem> Task { get { return completion.Task; } } public TaskCompletionSource<TreeViewItem> Completion { get { return completion; } } void AddGenerator (ItemsControl ic) { items.Add (ic.ItemContainerGenerator, ic); ic.ItemContainerGenerator.StatusChanged += HandleStatusChanged; } void HandleStatusChanged (object sender, EventArgs e) { var generator = sender as ItemContainerGenerator; if (generator != null && generator.Status == GeneratorStatus.ContainersGenerated) { generator.StatusChanged -= HandleStatusChanged; ItemsControl ic; if (items.TryGetValue (generator, out ic)) { Seek (ic); items.Remove (generator); } if (items.Count == 0) Complete (null); } } void Complete (TreeViewItem item) { if (!completed) { completed = true; Completion.SetResult (item); Unwind (); } } void Unwind () { foreach (var generator in items.Keys) { generator.StatusChanged -= HandleStatusChanged; } items.Clear (); } public void Find (ItemsControl ic) { Seek (ic); if (items.Count == 0) Complete (null); } bool Seek (ItemsControl ic) { if (ic == null || !ic.HasItems) return false; var generator = ic.ItemContainerGenerator; if (generator.Status == GeneratorStatus.ContainersGenerated) { foreach (var item in ic.Items) { var container = generator.ContainerFromItem (item) as TreeViewItem; if (item == SelectedItem && container != null) { Complete (container); return true; } if (Seek (container)) return true; } } else { AddGenerator (ic); } return false; } } public Task<TreeViewItem> FindTreeViewItem(object dataItem) { return FindItem(dataItem, this); } static Task<TreeViewItem> FindItem (object dataItem, ItemsControl ic) { var helper = new Helper { SelectedItem = dataItem }; helper.Find (ic); return helper.Task; } static TreeViewItem SelectTreeViewItemForBinding (Helper helper, ItemsControl ic, object dataItem) { if (ic == null || dataItem == null || !ic.HasItems) return null; IItemContainerGenerator generator = ic.ItemContainerGenerator; if (ic.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated) { foreach (var t in ic.Items) { var tvi = ic.ItemContainerGenerator.ContainerFromItem (t); if (t == dataItem) return tvi as TreeViewItem; var tmp = SelectTreeViewItemForBinding (dataItem, tvi as ItemsControl); if (tmp != null) return tmp; } } else using (generator.StartAt (generator.GeneratorPositionFromIndex (-1), GeneratorDirection.Forward)) { foreach (var t in ic.Items) { bool isNewlyRealized; var tvi = generator.GenerateNext (out isNewlyRealized); if (isNewlyRealized) { generator.PrepareItemContainer (tvi); } if (t == dataItem) return tvi as TreeViewItem; var tmp = SelectTreeViewItemForBinding (dataItem, tvi as ItemsControl); if (tmp != null) return tmp; } } return null; } public TreeViewItem GetTreeViewItemForItem(object dataItem) { return SelectTreeViewItemForBinding(dataItem, this); } static TreeViewItem SelectTreeViewItemForBinding (object dataItem, ItemsControl ic) { if (ic == null || dataItem == null || !ic.HasItems) return null; IItemContainerGenerator generator = ic.ItemContainerGenerator; if (ic.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated) { foreach (var t in ic.Items) { var tvi = ic.ItemContainerGenerator.ContainerFromItem(t); if (t == dataItem) return tvi as TreeViewItem; var tmp = SelectTreeViewItemForBinding (dataItem, tvi as ItemsControl); if (tmp != null) return tmp; } } else using (generator.StartAt (generator.GeneratorPositionFromIndex (-1), GeneratorDirection.Forward)) { foreach (var t in ic.Items) { bool isNewlyRealized; var tvi = generator.GenerateNext (out isNewlyRealized); if (isNewlyRealized) { generator.PrepareItemContainer (tvi); } if (t == dataItem) return tvi as TreeViewItem; var tmp = SelectTreeViewItemForBinding (dataItem, tvi as ItemsControl); if (tmp != null) return tmp; } } return null; } } } #endif
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace Lucene.Net.Codecs.Lucene42 { /* * 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 BlockPackedWriter = Lucene.Net.Util.Packed.BlockPackedWriter; using BytesRef = Lucene.Net.Util.BytesRef; using FieldInfo = Lucene.Net.Index.FieldInfo; using FormatAndBits = Lucene.Net.Util.Packed.PackedInt32s.FormatAndBits; using IndexFileNames = Lucene.Net.Index.IndexFileNames; using IndexOutput = Lucene.Net.Store.IndexOutput; using IOUtils = Lucene.Net.Util.IOUtils; using MathUtil = Lucene.Net.Util.MathUtil; using PackedInt32s = Lucene.Net.Util.Packed.PackedInt32s; using SegmentWriteState = Lucene.Net.Index.SegmentWriteState; /// <summary> /// Writer for <see cref="Lucene42NormsFormat"/>. /// </summary> internal class Lucene42NormsConsumer : DocValuesConsumer { internal const sbyte NUMBER = 0; internal const int BLOCK_SIZE = 4096; internal const sbyte DELTA_COMPRESSED = 0; internal const sbyte TABLE_COMPRESSED = 1; internal const sbyte UNCOMPRESSED = 2; internal const sbyte GCD_COMPRESSED = 3; internal IndexOutput data, meta; internal readonly int maxDoc; internal readonly float acceptableOverheadRatio; internal Lucene42NormsConsumer(SegmentWriteState state, string dataCodec, string dataExtension, string metaCodec, string metaExtension, float acceptableOverheadRatio) { this.acceptableOverheadRatio = acceptableOverheadRatio; maxDoc = state.SegmentInfo.DocCount; bool success = false; try { string dataName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name, state.SegmentSuffix, dataExtension); data = state.Directory.CreateOutput(dataName, state.Context); CodecUtil.WriteHeader(data, dataCodec, Lucene42DocValuesProducer.VERSION_CURRENT); string metaName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name, state.SegmentSuffix, metaExtension); meta = state.Directory.CreateOutput(metaName, state.Context); CodecUtil.WriteHeader(meta, metaCodec, Lucene42DocValuesProducer.VERSION_CURRENT); success = true; } finally { if (!success) { IOUtils.DisposeWhileHandlingException(this); } } } public override void AddNumericField(FieldInfo field, IEnumerable<long?> values) { meta.WriteVInt32(field.Number); meta.WriteByte((byte)NUMBER); meta.WriteInt64(data.GetFilePointer()); long minValue = long.MaxValue; long maxValue = long.MinValue; long gcd = 0; // TODO: more efficient? HashSet<long> uniqueValues = null; if (true) { uniqueValues = new HashSet<long>(); long count = 0; foreach (long? nv in values) { Debug.Assert(nv != null); long v = nv.Value; if (gcd != 1) { if (v < long.MinValue / 2 || v > long.MaxValue / 2) { // in that case v - minValue might overflow and make the GCD computation return // wrong results. Since these extreme values are unlikely, we just discard // GCD computation for them gcd = 1; } // minValue needs to be set first else if (count != 0) { gcd = MathUtil.Gcd(gcd, v - minValue); } } minValue = Math.Min(minValue, v); maxValue = Math.Max(maxValue, v); if (uniqueValues != null) { if (uniqueValues.Add(v)) { if (uniqueValues.Count > 256) { uniqueValues = null; } } } ++count; } Debug.Assert(count == maxDoc); } if (uniqueValues != null) { // small number of unique values int bitsPerValue = PackedInt32s.BitsRequired(uniqueValues.Count - 1); FormatAndBits formatAndBits = PackedInt32s.FastestFormatAndBits(maxDoc, bitsPerValue, acceptableOverheadRatio); if (formatAndBits.BitsPerValue == 8 && minValue >= sbyte.MinValue && maxValue <= sbyte.MaxValue) { meta.WriteByte((byte)UNCOMPRESSED); // uncompressed foreach (long? nv in values) { data.WriteByte((byte)nv.GetValueOrDefault()); } } else { meta.WriteByte((byte)TABLE_COMPRESSED); // table-compressed var decode = uniqueValues.ToArray(); var encode = new Dictionary<long, int>(); data.WriteVInt32(decode.Length); for (int i = 0; i < decode.Length; i++) { data.WriteInt64(decode[i]); encode[decode[i]] = i; } meta.WriteVInt32(PackedInt32s.VERSION_CURRENT); data.WriteVInt32(formatAndBits.Format.Id); data.WriteVInt32(formatAndBits.BitsPerValue); PackedInt32s.Writer writer = PackedInt32s.GetWriterNoHeader(data, formatAndBits.Format, maxDoc, formatAndBits.BitsPerValue, PackedInt32s.DEFAULT_BUFFER_SIZE); foreach (long? nv in values) { writer.Add(encode[nv.GetValueOrDefault()]); } writer.Finish(); } } else if (gcd != 0 && gcd != 1) { meta.WriteByte((byte)GCD_COMPRESSED); meta.WriteVInt32(PackedInt32s.VERSION_CURRENT); data.WriteInt64(minValue); data.WriteInt64(gcd); data.WriteVInt32(BLOCK_SIZE); var writer = new BlockPackedWriter(data, BLOCK_SIZE); foreach (long? nv in values) { writer.Add((nv.GetValueOrDefault() - minValue) / gcd); } writer.Finish(); } else { meta.WriteByte((byte)DELTA_COMPRESSED); // delta-compressed meta.WriteVInt32(PackedInt32s.VERSION_CURRENT); data.WriteVInt32(BLOCK_SIZE); var writer = new BlockPackedWriter(data, BLOCK_SIZE); foreach (long? nv in values) { writer.Add(nv.GetValueOrDefault()); } writer.Finish(); } } protected override void Dispose(bool disposing) { if (disposing) { bool success = false; try { if (meta != null) { meta.WriteVInt32(-1); // write EOF marker CodecUtil.WriteFooter(meta); // write checksum } if (data != null) { CodecUtil.WriteFooter(data); // write checksum } success = true; } finally { if (success) { IOUtils.Dispose(data, meta); } else { IOUtils.DisposeWhileHandlingException(data, meta); } meta = data = null; } } } public override void AddBinaryField(FieldInfo field, IEnumerable<BytesRef> values) { throw new NotSupportedException(); } public override void AddSortedField(FieldInfo field, IEnumerable<BytesRef> values, IEnumerable<long?> docToOrd) { throw new NotSupportedException(); } public override void AddSortedSetField(FieldInfo field, IEnumerable<BytesRef> values, IEnumerable<long?> docToOrdCount, IEnumerable<long?> ords) { throw new NotSupportedException(); } } }
//--------------------------------------------------------------------- // <copyright file="ClientType.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <summary> // type resolver // </summary> //--------------------------------------------------------------------- namespace System.Data.Services.Client { #region Namespaces. using System; using System.Collections.Generic; using System.Data.Services.Common; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Reflection; #endregion Namespaces. /// <summary> /// wrapper around a clr type to /// get/set properties /// add items to collections /// support open types /// </summary> [DebuggerDisplay("{ElementTypeName}")] internal sealed class ClientType { /// <summary>what is the clr full name using ToString for generic name expansion</summary> internal readonly string ElementTypeName; /// <summary>what clr type does this represent</summary> internal readonly Type ElementType; /// <summary>if true then EntityType else if !KnownType then ComplexType else PrimitiveType</summary> internal readonly bool IsEntityType; /// <summary>count of keys on entity type</summary> internal readonly int KeyCount; #region static fields /// <summary>appdomain cache discovered types with properties that we materialize</summary> private static readonly Dictionary<Type, ClientType> types = new Dictionary<Type, ClientType>(EqualityComparer<Type>.Default); /// <summary>cache &lt;T&gt; and wireName to mapped type</summary> private static readonly Dictionary<TypeName, Type> namedTypes = new Dictionary<TypeName, Type>(new TypeNameEqualityComparer()); #endregion #if ASTORIA_OPEN_OBJECT /// <summary>IDictionary&lt;string,object&gt; OpenProperites { get; }</summary> private readonly ClientProperty openProperties; #endif /// <summary>properties</summary> private ArraySet<ClientProperty> properties; /// <summary>Property that holds data for ATOM-style media link entries</summary> private ClientProperty mediaDataMember; /// <summary>Set to true if the type is marked as ATOM-style media link entry</summary> private bool mediaLinkEntry; /// <summary>Souce Epm mappings</summary> private EpmSourceTree epmSourceTree; /// <summary>Target Epm mappings</summary> private EpmTargetTree epmTargetTree; /// <summary> /// discover and prepare properties for usage /// </summary> /// <param name="type">type being processed</param> /// <param name="typeName">parameter name</param> /// <param name="skipSettableCheck">Whether the skip the check for settable properties.</param> private ClientType(Type type, string typeName, bool skipSettableCheck) { Debug.Assert(null != type, "null type"); Debug.Assert(!String.IsNullOrEmpty(typeName), "empty typeName"); this.ElementTypeName = typeName; this.ElementType = Nullable.GetUnderlyingType(type) ?? type; #if ASTORIA_OPEN_OBJECT string openObjectPropertyName = null; #endif if (!ClientConvert.IsKnownType(this.ElementType)) { #if ASTORIA_OPEN_OBJECT #region OpenObject determined by walking type hierarchy and looking for [OpenObjectAttribute("PropertyName")] Type openObjectDeclared = this.ElementType; for (Type tmp = openObjectDeclared; (null != tmp) && (typeof(object) != tmp); tmp = tmp.BaseType) { object[] attributes = openObjectDeclared.GetCustomAttributes(typeof(OpenObjectAttribute), false); if (1 == attributes.Length) { if (null != openObjectPropertyName) { throw Error.InvalidOperation(Strings.Clienttype_MultipleOpenProperty(this.ElementTypeName)); } openObjectPropertyName = ((OpenObjectAttribute)attributes[0]).OpenObjectPropertyName; openObjectDeclared = tmp; } } #endregion #endif Type keyPropertyDeclaredType = null; bool isEntity = type.GetCustomAttributes(true).OfType<DataServiceEntityAttribute>().Any(); DataServiceKeyAttribute dska = type.GetCustomAttributes(true).OfType<DataServiceKeyAttribute>().FirstOrDefault(); foreach (PropertyInfo pinfo in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)) { //// examples where class<PropertyType> //// the normal examples //// PropertyType Property { get; set } //// Nullable<PropertyType> Property { get; set; } //// if 'Property: struct' then we would be unable set the property during construction (and have them stick) //// but when its a class, we can navigate if non-null and set the nested properties //// PropertyType Property { get; } where PropertyType: class //// we do support adding elements to collections //// ICollection<PropertyType> { get; /*ignored set;*/ } //// indexed properties are not suported because //// we don't have anything to use as the index //// PropertyType Property[object x] { /*ignored get;*/ /*ignored set;*/ } //// also ignored //// if PropertyType.IsPointer (like byte*) //// if PropertyType.IsArray except for byte[] and char[] //// if PropertyType == IntPtr or UIntPtr Type ptype = pinfo.PropertyType; // class / interface / value ptype = Nullable.GetUnderlyingType(ptype) ?? ptype; if (ptype.IsPointer || (ptype.IsArray && (typeof(byte[]) != ptype) && typeof(char[]) != ptype) || (typeof(IntPtr) == ptype) || (typeof(UIntPtr) == ptype)) { continue; } Debug.Assert(!ptype.ContainsGenericParameters, "remove when test case is found that encounters this"); if (pinfo.CanRead && (!ptype.IsValueType || pinfo.CanWrite) && !ptype.ContainsGenericParameters && (0 == pinfo.GetIndexParameters().Length)) { #region IsKey? bool keyProperty = dska != null ? dska.KeyNames.Contains(pinfo.Name) : false; if (keyProperty) { if (null == keyPropertyDeclaredType) { keyPropertyDeclaredType = pinfo.DeclaringType; } else if (keyPropertyDeclaredType != pinfo.DeclaringType) { throw Error.InvalidOperation(Strings.ClientType_KeysOnDifferentDeclaredType(this.ElementTypeName)); } if (!ClientConvert.IsKnownType(ptype)) { throw Error.InvalidOperation(Strings.ClientType_KeysMustBeSimpleTypes(this.ElementTypeName)); } this.KeyCount++; } #endregion #if ASTORIA_OPEN_OBJECT #region IsOpenObjectProperty? bool openProperty = (openObjectPropertyName == pinfo.Name) && typeof(IDictionary<string, object>).IsAssignableFrom(ptype); Debug.Assert(keyProperty != openProperty || (!keyProperty && !openProperty), "key can't be open type"); #endregion ClientProperty property = new ClientProperty(pinfo, ptype, keyProperty, openProperty); if (!property.OpenObjectProperty) #else ClientProperty property = new ClientProperty(pinfo, ptype, keyProperty); #endif { if (!this.properties.Add(property, ClientProperty.NameEquality)) { // 2nd property with same name shadows another property int shadow = this.IndexOfProperty(property.PropertyName); if (!property.DeclaringType.IsAssignableFrom(this.properties[shadow].DeclaringType)) { // the new property is on the most derived class this.properties.RemoveAt(shadow); this.properties.Add(property, null); } } } #if ASTORIA_OPEN_OBJECT else { if (pinfo.DeclaringType == openObjectDeclared) { this.openProperties = property; } } #endif } } #region No KeyAttribute, discover key by name pattern { DeclaringType.Name+ID, ID } if (null == keyPropertyDeclaredType) { ClientProperty key = null; for (int i = this.properties.Count - 1; 0 <= i; --i) { string propertyName = this.properties[i].PropertyName; if (propertyName.EndsWith("ID", StringComparison.Ordinal)) { string declaringTypeName = this.properties[i].DeclaringType.Name; if ((propertyName.Length == (declaringTypeName.Length + 2)) && propertyName.StartsWith(declaringTypeName, StringComparison.Ordinal)) { // matched "DeclaringType.Name+ID" pattern if ((null == keyPropertyDeclaredType) || this.properties[i].DeclaringType.IsAssignableFrom(keyPropertyDeclaredType)) { keyPropertyDeclaredType = this.properties[i].DeclaringType; key = this.properties[i]; } } else if ((null == keyPropertyDeclaredType) && (2 == propertyName.Length)) { // matched "ID" pattern keyPropertyDeclaredType = this.properties[i].DeclaringType; key = this.properties[i]; } } } if (null != key) { Debug.Assert(0 == this.KeyCount, "shouldn't have a key yet"); key.KeyProperty = true; this.KeyCount++; } } else if (this.KeyCount != dska.KeyNames.Count) { var m = (from string a in dska.KeyNames where null == (from b in this.properties where b.PropertyName == a select b).FirstOrDefault() select a).First<string>(); throw Error.InvalidOperation(Strings.ClientType_MissingProperty(this.ElementTypeName, m)); } #endregion this.IsEntityType = (null != keyPropertyDeclaredType) || isEntity; Debug.Assert(this.KeyCount == this.Properties.Where(k => k.KeyProperty).Count(), "KeyCount mismatch"); this.WireUpMimeTypeProperties(); this.CheckMediaLinkEntry(); if (!skipSettableCheck) { #if ASTORIA_OPEN_OBJECT if ((0 == this.properties.Count) && (null == this.openProperties)) #else if (0 == this.properties.Count) #endif { // implicit construction? throw Error.InvalidOperation(Strings.ClientType_NoSettableFields(this.ElementTypeName)); } } } this.properties.TrimToSize(); this.properties.Sort<string>(ClientProperty.GetPropertyName, String.CompareOrdinal); #if ASTORIA_OPEN_OBJECT #region Validate OpenObjectAttribute was used if ((null != openObjectPropertyName) && (null == this.openProperties)) { throw Error.InvalidOperation(Strings.ClientType_MissingOpenProperty(this.ElementTypeName, openObjectPropertyName)); } Debug.Assert((null != openObjectPropertyName) == (null != this.openProperties), "OpenProperties mismatch"); #endregion #endif this.BuildEpmInfo(type); } /// <summary>Properties sorted by name</summary> internal ArraySet<ClientProperty> Properties { get { return this.properties; } } /// <summary>Property that holds data for ATOM-style media link entries</summary> internal ClientProperty MediaDataMember { get { return this.mediaDataMember; } } /// <summary>Returns true if the type is marked as ATOM-style media link entry</summary> internal bool IsMediaLinkEntry { get { return this.mediaLinkEntry; } } /// <summary> /// Source tree for <see cref="EntityPropertyMappingAttribute"/>s on this type /// </summary> internal EpmSourceTree EpmSourceTree { get { if (this.epmSourceTree == null) { this.epmTargetTree = new EpmTargetTree(); this.epmSourceTree = new EpmSourceTree(this.epmTargetTree); } return this.epmSourceTree; } } /// <summary> /// Target tree for <see cref="EntityPropertyMappingAttribute"/>s on this type /// </summary> internal EpmTargetTree EpmTargetTree { get { Debug.Assert(this.epmTargetTree != null, "Must have valid target tree"); return this.epmTargetTree; } } /// <summary>Are there any entity property mappings on this type</summary> internal bool HasEntityPropertyMappings { get { return this.epmSourceTree != null; } } /// <summary>The mappings for friendly feeds are V1 compatible or not</summary> internal bool EpmIsV1Compatible { get { return !this.HasEntityPropertyMappings || this.EpmTargetTree.IsV1Compatible; } } /// <summary>Whether a variable of <paramref name="type"/> can be assigned null.</summary> /// <param name="type">Type to check.</param> /// <returns>true if a variable of type <paramref name="type"/> can be assigned null; false otherwise.</returns> internal static bool CanAssignNull(Type type) { Debug.Assert(type != null, "type != null"); return !type.IsValueType || (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(Nullable<>))); } /// <summary> /// Is the type or element type (in the case of nullableOfT or IEnumOfT) a Entity Type? /// </summary> /// <param name="t">Type to examine</param> /// <returns>bool indicating whether or not entity type</returns> internal static bool CheckElementTypeIsEntity(Type t) { t = TypeSystem.GetElementType(t); t = Nullable.GetUnderlyingType(t) ?? t; return ClientType.Create(t, false).IsEntityType; } /// <summary> /// get a client type resolver /// </summary> /// <param name="type">type to wrap</param> /// <returns>client type</returns> internal static ClientType Create(Type type) { return Create(type, true /* expectModelType */); } /// <summary> /// get a client type resolver /// </summary> /// <param name="type">type to wrap</param> /// <param name="expectModelType">Whether the type is expected to be a model type.</param> /// <returns>client type</returns> internal static ClientType Create(Type type, bool expectModelType) { ClientType clientType; lock (ClientType.types) { ClientType.types.TryGetValue(type, out clientType); } if (null == clientType) { if (CommonUtil.IsUnsupportedType(type)) { throw new InvalidOperationException(Strings.ClientType_UnsupportedType(type)); } bool skipSettableCheck = !expectModelType; clientType = new ClientType(type, type.ToString(), skipSettableCheck); // ToString expands generic type name where as FullName does not if (expectModelType) { lock (ClientType.types) { ClientType existing; if (ClientType.types.TryGetValue(type, out existing)) { clientType = existing; } else { ClientType.types.Add(type, clientType); } } } } return clientType; } #if !ASTORIA_LIGHT /// <summary> /// resolve the wireName/userType pair to a CLR type /// </summary> /// <param name="wireName">type name sent by server</param> /// <param name="userType">type passed by user or on propertyType from a class</param> /// <returns>mapped clr type</returns> internal static Type ResolveFromName(string wireName, Type userType) #else /// <summary> /// resolve the wireName/userType pair to a CLR type /// </summary> /// <param name="wireName">type name sent by server</param> /// <param name="userType">type passed by user or on propertyType from a class</param> /// <param name="contextType">typeof context for strongly typed assembly</param> /// <returns>mapped clr type</returns> internal static Type ResolveFromName(string wireName, Type userType, Type contextType) #endif { Type foundType; TypeName typename; typename.Type = userType; typename.Name = wireName; // search the "wirename"-userType key in type cache bool foundInCache; lock (ClientType.namedTypes) { foundInCache = ClientType.namedTypes.TryGetValue(typename, out foundType); } // at this point, if we have seen this type before, we either have the resolved type "foundType", // or we have tried to resolve it before but did not success, in which case foundType will be null. // Either way we should return what's in the cache since the result is unlikely to change. // We only need to keep on searching if there isn't an entry in the cache. if (!foundInCache) { string name = wireName; int index = wireName.LastIndexOf('.'); if ((0 <= index) && (index < wireName.Length - 1)) { name = wireName.Substring(index + 1); } if (userType.Name == name) { foundType = userType; } else { #if !ASTORIA_LIGHT // searching only loaded assemblies, not referenced assemblies foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) #else foreach (Assembly assembly in new Assembly[] { userType.Assembly, contextType.Assembly }.Distinct()) #endif { Type found = assembly.GetType(wireName, false); ResolveSubclass(name, userType, found, ref foundType); if (null == found) { Type[] types = null; try { types = assembly.GetTypes(); } catch (ReflectionTypeLoadException) { } if (null != types) { foreach (Type t in types) { ResolveSubclass(name, userType, t, ref foundType); } } } } } // The above search can all fail and leave "foundType" to be null // we should cache this result too so we won't waste time searching again. lock (ClientType.namedTypes) { ClientType.namedTypes[typename] = foundType; } } return foundType; } /// <summary> /// get concrete type that implements the genericTypeDefinitation /// </summary> /// <param name="propertyType">starting type</param> /// <param name="genericTypeDefinition">the generic type definition to find</param> /// <returns>concrete type that implementats the generic type</returns> internal static Type GetImplementationType(Type propertyType, Type genericTypeDefinition) { if (IsConstructedGeneric(propertyType, genericTypeDefinition)) { // propertyType is ICollection<T> return propertyType; } else { Type implementationType = null; foreach (Type interfaceType in propertyType.GetInterfaces()) { if (IsConstructedGeneric(interfaceType, genericTypeDefinition)) { if (null == implementationType) { // found implmentation of ICollection<T> implementationType = interfaceType; } else { // ICollection<int> and ICollection<int?> throw Error.NotSupported(Strings.ClientType_MultipleImplementationNotSupported); } } } return implementationType; } } /// <summary> /// Gets the Add method to add items to a collection of the specified type. /// </summary> /// <param name="collectionType">Type for the collection.</param> /// <param name="type">The element type in the collection if found; null otherwise.</param> /// <returns>The method to invoke to add to a collection of the specified type.</returns> internal static MethodInfo GetAddToCollectionMethod(Type collectionType, out Type type) { return GetCollectionMethod(collectionType, typeof(ICollection<>), "Add", out type); } /// <summary> /// Gets the Remove method to remove items from a collection of the specified type. /// </summary> /// <param name="collectionType">Type for the collection.</param> /// <param name="type">The element type in the collection if found; null otherwise.</param> /// <returns>The method to invoke to remove from a collection of the specified type.</returns> internal static MethodInfo GetRemoveFromCollectionMethod(Type collectionType, out Type type) { return GetCollectionMethod(collectionType, typeof(ICollection<>), "Remove", out type); } /// <summary> /// get element type, resolves ICollection and Nullable /// </summary> /// <param name="propertyType">starting type</param> /// <param name="genericTypeDefinition">the generic type definition to find</param> /// <param name="methodName">the method to search for</param> /// <param name="type">the collection type if found</param> /// <returns>element types</returns> internal static MethodInfo GetCollectionMethod(Type propertyType, Type genericTypeDefinition, string methodName, out Type type) { Debug.Assert(null != propertyType, "null propertyType"); Debug.Assert(null != genericTypeDefinition, "null genericTypeDefinition"); Debug.Assert(genericTypeDefinition.IsGenericTypeDefinition, "!IsGenericTypeDefinition"); type = null; Type implementationType = GetImplementationType(propertyType, genericTypeDefinition); if (null != implementationType) { Type[] genericArguments = implementationType.GetGenericArguments(); MethodInfo methodInfo = implementationType.GetMethod(methodName); Debug.Assert(null != methodInfo, "should have found the method"); #if DEBUG Debug.Assert(null != genericArguments, "null genericArguments"); ParameterInfo[] parameters = methodInfo.GetParameters(); if (0 < parameters.Length) { // following assert was disabled for Contains which returns bool // Debug.Assert(typeof(void) == methodInfo.ReturnParameter.ParameterType, "method doesn't return void"); Debug.Assert(genericArguments.Length == parameters.Length, "genericArguments don't match parameters"); for (int i = 0; i < genericArguments.Length; ++i) { Debug.Assert(genericArguments[i] == parameters[i].ParameterType, "parameter doesn't match generic argument"); } } #endif type = genericArguments[genericArguments.Length - 1]; return methodInfo; } return null; } /// <summary> /// create object using default constructor /// </summary> /// <returns>instance of propertyType</returns> internal object CreateInstance() { return Activator.CreateInstance(this.ElementType); } /// <summary> /// get property wrapper for a property name, might be method around open types for otherwise unknown properties /// </summary> /// <param name="propertyName">property name</param> /// <param name="ignoreMissingProperties">are missing properties ignored</param> /// <returns>property wrapper</returns> /// <exception cref="InvalidOperationException">for unknown properties on closed types</exception> internal ClientProperty GetProperty(string propertyName, bool ignoreMissingProperties) { int index = this.IndexOfProperty(propertyName); if (0 <= index) { return this.properties[index]; } #if ASTORIA_OPEN_OBJECT else if (null != this.openProperties) { return this.openProperties; } #endif else if (!ignoreMissingProperties) { throw Error.InvalidOperation(Strings.ClientType_MissingProperty(this.ElementTypeName, propertyName)); } return null; } /// <summary> /// Checks whether the specified <paramref name="type"/> is a /// closed constructed type of the generic type. /// </summary> /// <param name="type">Type to check.</param> /// <param name="genericTypeDefinition">Generic type for checkin.</param> /// <returns>true if <paramref name="type"/> is a constructed type of <paramref name="genericTypeDefinition"/>.</returns> /// <remarks>The check is an immediate check; no inheritance rules are applied.</remarks> private static bool IsConstructedGeneric(Type type, Type genericTypeDefinition) { Debug.Assert(type != null, "type != null"); Debug.Assert(!type.ContainsGenericParameters, "remove when test case is found that encounters this"); Debug.Assert(genericTypeDefinition != null, "genericTypeDefinition != null"); return type.IsGenericType && (type.GetGenericTypeDefinition() == genericTypeDefinition) && !type.ContainsGenericParameters; } /// <summary> /// is the type a visible subclass with correct name /// </summary> /// <param name="wireClassName">type name from server</param> /// <param name="userType">the type from user for materialization or property type</param> /// <param name="type">type being tested</param> /// <param name="existing">the previously discovered matching type</param> /// <exception cref="InvalidOperationException">if the mapping is ambiguous</exception> private static void ResolveSubclass(string wireClassName, Type userType, Type type, ref Type existing) { if ((null != type) && type.IsVisible && (wireClassName == type.Name) && userType.IsAssignableFrom(type)) { if (null != existing) { throw Error.InvalidOperation(Strings.ClientType_Ambiguous(wireClassName, userType)); } existing = type; } } /// <summary> /// By going over EntityPropertyMappingInfoAttribute(s) defined on <paramref name="type"/> /// builds the corresponding EntityPropertyMappingInfo /// </summary> /// <param name="type">Type being looked at</param> private void BuildEpmInfo(Type type) { if (type.BaseType != null && type.BaseType != typeof(object)) { this.BuildEpmInfo(type.BaseType); } foreach (EntityPropertyMappingAttribute epmAttr in type.GetCustomAttributes(typeof(EntityPropertyMappingAttribute), false)) { this.BuildEpmInfo(epmAttr, type); } } /// <summary> /// Builds the EntityPropertyMappingInfo corresponding to an EntityPropertyMappingAttribute, also builds the delegate to /// be invoked in order to retrieve the property provided in the <paramref name="epmAttr"/> /// </summary> /// <param name="epmAttr">Source EntityPropertyMappingAttribute</param> /// <param name="definingType">ResourceType on which to look for the property</param> private void BuildEpmInfo(EntityPropertyMappingAttribute epmAttr, Type definingType) { this.EpmSourceTree.Add(new EntityPropertyMappingInfo(epmAttr, definingType, this)); } /// <summary>get the index of a property</summary> /// <param name="propertyName">propertyName</param> /// <returns>index else -1</returns> private int IndexOfProperty(string propertyName) { return this.properties.IndexOf(propertyName, ClientProperty.GetPropertyName, String.Equals); } /// <summary> /// Find properties with dynamic MIME type related properties and /// set the references from each ClientProperty to its related MIME type property /// </summary> private void WireUpMimeTypeProperties() { MimeTypePropertyAttribute attribute = (MimeTypePropertyAttribute)this.ElementType.GetCustomAttributes(typeof(MimeTypePropertyAttribute), true).SingleOrDefault(); if (null != attribute) { int dataIndex, mimeTypeIndex; if ((0 > (dataIndex = this.IndexOfProperty(attribute.DataPropertyName))) || (0 > (mimeTypeIndex = this.IndexOfProperty(attribute.MimeTypePropertyName)))) { throw Error.InvalidOperation(Strings.ClientType_MissingMimeTypeProperty(attribute.DataPropertyName, attribute.MimeTypePropertyName)); } Debug.Assert(0 <= dataIndex, "missing data property"); Debug.Assert(0 <= mimeTypeIndex, "missing mime type property"); this.Properties[dataIndex].MimeTypeProperty = this.Properties[mimeTypeIndex]; } } /// <summary> /// Check if this type represents an ATOM-style media link entry and /// if so mark the ClientType as such /// </summary> private void CheckMediaLinkEntry() { object[] attributes = this.ElementType.GetCustomAttributes(typeof(MediaEntryAttribute), true); if (attributes != null && attributes.Length > 0) { Debug.Assert(attributes.Length == 1, "The AttributeUsage in the attribute definition should be preventing more than 1 per property"); MediaEntryAttribute mediaEntryAttribute = (MediaEntryAttribute)attributes[0]; this.mediaLinkEntry = true; int index = this.IndexOfProperty(mediaEntryAttribute.MediaMemberName); if (index < 0) { throw Error.InvalidOperation(Strings.ClientType_MissingMediaEntryProperty( mediaEntryAttribute.MediaMemberName)); } this.mediaDataMember = this.properties[index]; } attributes = this.ElementType.GetCustomAttributes(typeof(HasStreamAttribute), true); if (attributes != null && attributes.Length > 0) { Debug.Assert(attributes.Length == 1, "The AttributeUsage in the attribute definition should be preventing more than 1 per property"); this.mediaLinkEntry = true; } } /// <summary>type + wireName combination</summary> private struct TypeName { /// <summary>type</summary> internal Type Type; /// <summary>type name from server</summary> internal string Name; } /// <summary> /// wrapper around property methods /// </summary> [DebuggerDisplay("{PropertyName}")] internal sealed class ClientProperty { /// <summary>property name for debugging</summary> internal readonly string PropertyName; /// <summary>Exact property type; possibly nullable but not necessarily so.</summary> internal readonly Type NullablePropertyType; /// <summary>type of the property</summary> internal readonly Type PropertyType; /// <summary>what is the nested collection element</summary> internal readonly Type CollectionType; /// <summary> /// Is this a known primitive/reference type or an entity/complex/collection type? /// </summary> internal readonly bool IsKnownType; #if ASTORIA_OPEN_OBJECT /// <summary>IDictionary&lt;string,object&gt; OpenProperites { get; }</summary> internal readonly bool OpenObjectProperty; #endif /// <summary>property getter</summary> private readonly MethodInfo propertyGetter; /// <summary>property setter</summary> private readonly MethodInfo propertySetter; /// <summary>"set_Item" method supporting IDictionary properties</summary> private readonly MethodInfo setMethod; /// <summary>"Add" method supporting ICollection&lt;&gt; properties</summary> private readonly MethodInfo addMethod; /// <summary>"Remove" method supporting ICollection&lt;&gt; properties</summary> private readonly MethodInfo removeMethod; /// <summary>"Contains" method support ICollection&lt;&gt; properties</summary> private readonly MethodInfo containsMethod; /// <summary>IsKeyProperty?</summary> private bool keyProperty; /// <summary>The other property in this type that holds the MIME type for this one</summary> private ClientProperty mimeTypeProperty; #if ASTORIA_OPEN_OBJECT /// <summary> /// constructor /// </summary> /// <param name="property">property</param> /// <param name="propertyType">propertyType</param> /// <param name="keyProperty">keyProperty</param> /// <param name="openObjectProperty">openObjectProperty</param> internal ClientProperty(PropertyInfo property, Type propertyType, bool keyProperty, bool openObjectProperty) #else /// <summary> /// constructor /// </summary> /// <param name="property">property</param> /// <param name="propertyType">propertyType</param> /// <param name="keyProperty">Whether this property is part of the key for its declaring type.</param> internal ClientProperty(PropertyInfo property, Type propertyType, bool keyProperty) #endif { Debug.Assert(null != property, "null property"); Debug.Assert(null != propertyType, "null propertyType"); Debug.Assert(null == Nullable.GetUnderlyingType(propertyType), "should already have been denullified"); this.PropertyName = property.Name; this.NullablePropertyType = property.PropertyType; this.PropertyType = propertyType; this.propertyGetter = property.GetGetMethod(); this.propertySetter = property.GetSetMethod(); this.keyProperty = keyProperty; #if ASTORIA_OPEN_OBJECT this.OpenObjectProperty = openObjectProperty; #endif this.IsKnownType = ClientConvert.IsKnownType(propertyType); if (!this.IsKnownType) { this.setMethod = GetCollectionMethod(this.PropertyType, typeof(IDictionary<,>), "set_Item", out this.CollectionType); if (null == this.setMethod) { this.containsMethod = GetCollectionMethod(this.PropertyType, typeof(ICollection<>), "Contains", out this.CollectionType); this.addMethod = GetAddToCollectionMethod(this.PropertyType, out this.CollectionType); this.removeMethod = GetRemoveFromCollectionMethod(this.PropertyType, out this.CollectionType); } } Debug.Assert(!this.keyProperty || this.IsKnownType, "can't have an random type as key"); } /// <summary>what type was this property declared on?</summary> internal Type DeclaringType { get { return this.propertyGetter.DeclaringType; } } /// <summary>Does this property particpate in the primary key?</summary> internal bool KeyProperty { get { return this.keyProperty; } set { this.keyProperty = value; } } /// <summary>The other property in this type that holds the MIME type for this one</summary> internal ClientProperty MimeTypeProperty { get { return this.mimeTypeProperty; } set { this.mimeTypeProperty = value; } } /// <summary>get KeyProperty</summary> /// <param name="x">x</param> /// <returns>KeyProperty</returns> internal static bool GetKeyProperty(ClientProperty x) { return x.KeyProperty; } /// <summary>get property name</summary> /// <param name="x">x</param> /// <returns>PropertyName</returns> internal static string GetPropertyName(ClientProperty x) { return x.PropertyName; } /// <summary>compare name equality</summary> /// <param name="x">x</param> /// <param name="y">y</param> /// <returns>true if the property names are equal; false otherwise.</returns> internal static bool NameEquality(ClientProperty x, ClientProperty y) { return String.Equals(x.PropertyName, y.PropertyName); } /// <summary> /// get property value from an object /// </summary> /// <param name="instance">object to get the property value from</param> /// <returns>property value</returns> internal object GetValue(object instance) { Debug.Assert(null != instance, "null instance"); Debug.Assert(null != this.propertyGetter, "null propertyGetter"); return this.propertyGetter.Invoke(instance, null); } /// <summary> /// remove a item from collection /// </summary> /// <param name="instance">collection</param> /// <param name="value">item to remove</param> internal void RemoveValue(object instance, object value) { Debug.Assert(null != instance, "null instance"); Debug.Assert(null != this.removeMethod, "missing removeMethod"); Debug.Assert(this.PropertyType.IsAssignableFrom(instance.GetType()), "unexpected collection instance"); Debug.Assert((null == value) || this.CollectionType.IsAssignableFrom(value.GetType()), "unexpected collection value to add"); this.removeMethod.Invoke(instance, new object[] { value }); } #if ASTORIA_OPEN_OBJECT /// <summary> /// set property value on an object /// </summary> /// <param name="instance">object to set the property value on</param> /// <param name="value">property value</param> /// <param name="propertyName">used for open type</param> /// <param name="allowAdd">allow add to a collection if available, else allow setting collection property</param> /// <param name="openProperties">cached OpenProperties dictionary</param> internal void SetValue(object instance, object value, string propertyName, ref object openProperties, bool allowAdd) #else /// <summary> /// set property value on an object /// </summary> /// <param name="instance">object to set the property value on</param> /// <param name="value">property value</param> /// <param name="propertyName">used for open type</param> /// <param name="allowAdd">allow add to a collection if available, else allow setting collection property</param> internal void SetValue(object instance, object value, string propertyName, bool allowAdd) #endif { Debug.Assert(null != instance, "null instance"); if (null != this.setMethod) { #if ASTORIA_OPEN_OBJECT if (this.OpenObjectProperty) { if (null == openProperties) { if (null == (openProperties = this.propertyGetter.Invoke(instance, null))) { throw Error.NotSupported(Strings.ClientType_NullOpenProperties(this.PropertyName)); } } ((IDictionary<string, object>)openProperties)[propertyName] = value; } else #endif { Debug.Assert(this.PropertyType.IsAssignableFrom(instance.GetType()), "unexpected dictionary instance"); Debug.Assert((null == value) || this.CollectionType.IsAssignableFrom(value.GetType()), "unexpected dictionary value to set"); // ((IDictionary<string, CollectionType>)instance)[propertyName] = (CollectionType)value; this.setMethod.Invoke(instance, new object[] { propertyName, value }); } } else if (allowAdd && (null != this.addMethod)) { Debug.Assert(this.PropertyType.IsAssignableFrom(instance.GetType()), "unexpected collection instance"); Debug.Assert((null == value) || this.CollectionType.IsAssignableFrom(value.GetType()), "unexpected collection value to add"); // ((ICollection<CollectionType>)instance).Add((CollectionType)value); if (!(bool)this.containsMethod.Invoke(instance, new object[] { value })) { this.addMethod.Invoke(instance, new object[] { value }); } } else if (null != this.propertySetter) { Debug.Assert((null == value) || this.PropertyType.IsAssignableFrom(value.GetType()), "unexpected property value to set"); // ((ElementType)instance).PropertyName = (PropertyType)value; this.propertySetter.Invoke(instance, new object[] { value }); } else { throw Error.InvalidOperation(Strings.ClientType_MissingProperty(value.GetType().ToString(), propertyName)); } } } /// <summary>equality comparer for TypeName</summary> private sealed class TypeNameEqualityComparer : IEqualityComparer<TypeName> { /// <summary>equality comparer for TypeName</summary> /// <param name="x">left type</param> /// <param name="y">right type</param> /// <returns>true if x and y are equal</returns> public bool Equals(TypeName x, TypeName y) { return (x.Type == y.Type && x.Name == y.Name); } /// <summary>compute hashcode for TypeName</summary> /// <param name="obj">object to compute hashcode for</param> /// <returns>computed hashcode</returns> public int GetHashCode(TypeName obj) { return obj.Type.GetHashCode() ^ obj.Name.GetHashCode(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using Codecov.Services; using Codecov.Services.ContinuousIntegrationServers; using Codecov.Utilities; using Codecov.Yaml; namespace Codecov.Url { internal class Query : IQuery { private readonly IEnviornmentVariables _environmentVariables; private readonly Lazy<string> _getQuery; public Query(IQueryOptions options, IEnumerable<IRepository> repositories, IBuild build, IYaml yaml, IEnviornmentVariables environmentVariables) { Options = options; Repositories = repositories; Build = build; Yaml = yaml; _environmentVariables = environmentVariables; SetQueryParameters(); _getQuery = new Lazy<string>(() => string.Join("&", QueryParameters.Select(x => $"{x.Key}={x.Value ?? string.Empty}"))); } public string GetQuery => _getQuery.Value; private IBuild Build { get; } private IQueryOptions Options { get; } private IDictionary<string, string> QueryParameters { get; set; } private IEnumerable<IRepository> Repositories { get; } private IYaml Yaml { get; } private static string EscapeKnownProblematicCharacters(string data) { var knownChars = new Dictionary<char, string> { { '#', "%23" }, }; var result = new StringBuilder(); foreach (var c in data) { if (knownChars.ContainsKey(c)) { result.Append(knownChars[c]); } else { result.Append(c); } } return result.ToString(); } private void OverrideIfNotEmptyOrNull(string key, string value, bool escapeValue = false) { if (!string.IsNullOrWhiteSpace(value)) { QueryParameters[key] = escapeValue ? Uri.EscapeDataString(value.RemoveAllWhiteSpace()) : value.RemoveAllWhiteSpace(); } } private void SetBranch() { QueryParameters["branch"] = string.Empty; foreach (var repository in Repositories) { if (!string.IsNullOrWhiteSpace(repository.Branch)) { // We also need to take into account that '#' needs to be escaped for parameters var escapedBranch = EscapeKnownProblematicCharacters(Uri.EscapeDataString(repository.Branch)); QueryParameters["branch"] = escapedBranch; break; } } OverrideIfNotEmptyOrNull("branch", Options.Branch); } private void SetBuild() { var escapedBuild = Uri.EscapeDataString(Build.Build); QueryParameters["build"] = escapedBuild; OverrideIfNotEmptyOrNull("build", Options.Build); } private void SetBuildUrl() => QueryParameters["build_url"] = Build.BuildUrl.Replace("?", "%3F"); private void SetCommit() { QueryParameters["commit"] = string.Empty; foreach (var repository in Repositories) { if (!string.IsNullOrWhiteSpace(repository.Commit)) { QueryParameters["commit"] = repository.Commit; break; } } OverrideIfNotEmptyOrNull("commit", Options.Commit); } private void SetFlags() { var flags = Options.Flags; if (string.IsNullOrWhiteSpace(flags)) { QueryParameters["flags"] = string.Empty; return; } var flagsSeperatedByCommasAndNoExtraWhiteSpace = string.Join(",", flags.Split(',').Select(x => x.Trim())); QueryParameters["flags"] = flagsSeperatedByCommasAndNoExtraWhiteSpace; } private void SetJob() { var escapedJob = Uri.EscapeDataString(Build.Job); // Due to the + sign being escaped, we need to unescape that character escapedJob = escapedJob.Replace("%2B", "%252B"); QueryParameters["job"] = escapedJob; } private void SetName() { QueryParameters["name"] = string.Empty; OverrideIfNotEmptyOrNull("name", Options.Name); } private void SetPackage() => QueryParameters["package"] = About.Version; private void SetPr() { QueryParameters["pr"] = string.Empty; foreach (var repository in Repositories) { if (!string.IsNullOrWhiteSpace(repository.Pr)) { QueryParameters["pr"] = repository.Pr; break; } } OverrideIfNotEmptyOrNull("pr", Options.Pr); } private void SetProjectAndServerUri() { foreach (var repository in Repositories) { if (!string.IsNullOrEmpty(repository.Project) && !string.IsNullOrEmpty(repository.ServerUri)) { QueryParameters["project"] = repository.Project; QueryParameters["server_uri"] = repository.ServerUri; break; } } } private void SetQueryParameters() { QueryParameters = new Dictionary<string, string>(); SetBranch(); SetCommit(); SetBuild(); SetTag(); SetPr(); SetName(); SetFlags(); SetSlug(); SetToken(); SetPackage(); SetBuildUrl(); SetYaml(); SetJob(); SetService(); SetProjectAndServerUri(); } private void SetService() => QueryParameters["service"] = Build.Service; private void SetSlug() { QueryParameters["slug"] = string.Empty; foreach (var repository in Repositories) { if (!string.IsNullOrWhiteSpace(repository.Slug)) { QueryParameters["slug"] = WebUtility.UrlEncode(repository.Slug); break; } } var slugEnv = _environmentVariables.GetEnvironmentVariable("CODECOV_SLUG"); if (!string.IsNullOrWhiteSpace(slugEnv)) { QueryParameters["slug"] = WebUtility.UrlEncode(slugEnv.Trim()); } if (!string.IsNullOrWhiteSpace(Options.Slug)) { QueryParameters["slug"] = WebUtility.UrlEncode(Options.Slug.Trim()); } } private void SetTag() { QueryParameters["tag"] = string.Empty; foreach (var repository in Repositories) { if (!string.IsNullOrWhiteSpace(repository.Tag)) { QueryParameters["tag"] = repository.Tag; break; } } OverrideIfNotEmptyOrNull("tag", Options.Tag); } private void SetToken() { QueryParameters["token"] = string.Empty; var tokenEnv = _environmentVariables.GetEnvironmentVariable("CODECOV_TOKEN"); if (!string.IsNullOrWhiteSpace(tokenEnv)) { QueryParameters["token"] = tokenEnv.RemoveAllWhiteSpace(); } if (Guid.TryParse(Options.Token, out var _)) { QueryParameters["token"] = Options.Token.RemoveAllWhiteSpace(); } } private void SetYaml() => QueryParameters["yaml"] = Yaml.FileName; } }
using Parse; using Parse.Common.Internal; using Parse.Core.Internal; using System; using System.Threading; using System.Threading.Tasks; using System.Runtime.CompilerServices; using Moq; using NUnit.Framework; using System.Collections.Generic; namespace ParseTest { [TestFixture] public class CurrentUserControllerTests { [SetUp] public void SetUp() { ParseObject.RegisterSubclass<ParseUser>(); } [TearDown] public void TearDown() { ParseCorePlugins.Instance.Reset(); } [Test] public void TestConstructor() { var storageController = new Mock<IStorageController>(); var controller = new ParseCurrentUserController(storageController.Object); Assert.IsNull(controller.CurrentUser); } [Test] [AsyncStateMachine(typeof(CurrentUserControllerTests))] public Task TestGetSetAsync() { var storageController = new Mock<IStorageController>(MockBehavior.Strict); var mockedStorage = new Mock<IStorageDictionary<string, object>>(); var controller = new ParseCurrentUserController(storageController.Object); var user = new ParseUser(); storageController.Setup(s => s.LoadAsync()).Returns(Task.FromResult(mockedStorage.Object)); return controller.SetAsync(user, CancellationToken.None).OnSuccess(_ => { Assert.AreEqual(user, controller.CurrentUser); object jsonObject = null; Predicate<object> predicate = o => { jsonObject = o; return true; }; mockedStorage.Verify(s => s.AddAsync("CurrentUser", Match.Create<object>(predicate))); mockedStorage.Setup(s => s.TryGetValue("CurrentUser", out jsonObject)).Returns(true); return controller.GetAsync(CancellationToken.None); }).Unwrap() .OnSuccess(t => { Assert.AreEqual(user, controller.CurrentUser); controller.ClearFromMemory(); Assert.AreNotEqual(user, controller.CurrentUser); return controller.GetAsync(CancellationToken.None); }).Unwrap() .OnSuccess(t => { Assert.AreNotSame(user, controller.CurrentUser); Assert.IsNotNull(controller.CurrentUser); }); } [Test] [AsyncStateMachine(typeof(CurrentUserControllerTests))] public Task TestExistsAsync() { var storageController = new Mock<IStorageController>(); var mockedStorage = new Mock<IStorageDictionary<string, object>>(); var controller = new ParseCurrentUserController(storageController.Object); var user = new ParseUser(); storageController.Setup(c => c.LoadAsync()).Returns(Task.FromResult(mockedStorage.Object)); bool contains = false; mockedStorage.Setup(s => s.AddAsync("CurrentUser", It.IsAny<object>())).Callback(() => { contains = true; }).Returns(Task.FromResult<object>(null)).Verifiable(); mockedStorage.Setup(s => s.RemoveAsync("CurrentUser")).Callback(() => { contains = false; }).Returns(Task.FromResult<object>(null)).Verifiable(); mockedStorage.Setup(s => s.ContainsKey("CurrentUser")).Returns(() => contains); return controller.SetAsync(user, CancellationToken.None).OnSuccess(_ => { Assert.AreEqual(user, controller.CurrentUser); return controller.ExistsAsync(CancellationToken.None); }).Unwrap() .OnSuccess(t => { Assert.IsTrue(t.Result); controller.ClearFromMemory(); return controller.ExistsAsync(CancellationToken.None); }).Unwrap() .OnSuccess(t => { Assert.IsTrue(t.Result); controller.ClearFromDisk(); return controller.ExistsAsync(CancellationToken.None); }).Unwrap() .OnSuccess(t => { Assert.IsFalse(t.Result); mockedStorage.Verify(); }); } [Test] [AsyncStateMachine(typeof(CurrentUserControllerTests))] public Task TestIsCurrent() { var storageController = new Mock<IStorageController>(MockBehavior.Strict); var mockedStorage = new Mock<IStorageDictionary<string, object>>(); var controller = new ParseCurrentUserController(storageController.Object); var user = new ParseUser(); var user2 = new ParseUser(); storageController.Setup(s => s.LoadAsync()).Returns(Task.FromResult(mockedStorage.Object)); return controller.SetAsync(user, CancellationToken.None).OnSuccess(t => { Assert.IsTrue(controller.IsCurrent(user)); Assert.IsFalse(controller.IsCurrent(user2)); controller.ClearFromMemory(); Assert.IsFalse(controller.IsCurrent(user)); return controller.SetAsync(user, CancellationToken.None); }).Unwrap() .OnSuccess(t => { Assert.IsTrue(controller.IsCurrent(user)); Assert.IsFalse(controller.IsCurrent(user2)); controller.ClearFromDisk(); Assert.IsFalse(controller.IsCurrent(user)); return controller.SetAsync(user2, CancellationToken.None); }).Unwrap() .OnSuccess(t => { Assert.IsFalse(controller.IsCurrent(user)); Assert.IsTrue(controller.IsCurrent(user2)); }); } [Test] [AsyncStateMachine(typeof(CurrentUserControllerTests))] public Task TestCurrentSessionToken() { var storageController = new Mock<IStorageController>(); var mockedStorage = new Mock<IStorageDictionary<string, object>>(); var controller = new ParseCurrentUserController(storageController.Object); storageController.Setup(c => c.LoadAsync()).Returns(Task.FromResult(mockedStorage.Object)); return controller.GetCurrentSessionTokenAsync(CancellationToken.None).OnSuccess(t => { Assert.IsNull(t.Result); // We should probably mock this. var userState = new MutableObjectState { ServerData = new Dictionary<string, object>() { { "sessionToken", "randomString" } } }; var user = ParseObject.CreateWithoutData<ParseUser>(null); user.HandleFetchResult(userState); return controller.SetAsync(user, CancellationToken.None); }).Unwrap() .OnSuccess(_ => controller.GetCurrentSessionTokenAsync(CancellationToken.None)).Unwrap() .OnSuccess(t => { Assert.AreEqual("randomString", t.Result); }); } public Task TestLogOut() { var storageController = new Mock<IStorageController>(MockBehavior.Strict); var controller = new ParseCurrentUserController(storageController.Object); var user = new ParseUser(); return controller.SetAsync(user, CancellationToken.None).OnSuccess(_ => { Assert.AreEqual(user, controller.CurrentUser); return controller.ExistsAsync(CancellationToken.None); }).Unwrap() .OnSuccess(t => { Assert.IsTrue(t.Result); return controller.LogOutAsync(CancellationToken.None); }).Unwrap().OnSuccess(_ => controller.GetAsync(CancellationToken.None)).Unwrap() .OnSuccess(t => { Assert.IsNull(t.Result); return controller.ExistsAsync(CancellationToken.None); }).Unwrap() .OnSuccess(t => { Assert.IsFalse(t.Result); }); } } }
using System; using System.Collections.Generic; using System.Threading; using System.Net; using System.IO; using NetSiege.Api.Data; namespace NetSiege.Api { /// <summary> /// Signature of events receiving any new hit results. /// </summary> public delegate void HitEventHandler(SeigeTest sender, Hit hit); /// <summary> /// Object in charge of conducting a test by launching and maintaining /// a set of threads to do the test and maintain the results. /// </summary> public class SeigeTest { #region Constructors /// <summary> /// Constructor requires the settings to use for this test, and by /// default immediately starts the test. /// </summary> public SeigeTest(TestSettings settings, bool autoStart = true) { this.Settings = settings; if (autoStart) { Start (); } } #endregion #region Properties /// <summary> /// The settings being used for this test. /// </summary> public readonly TestSettings Settings; /// <summary> /// The results of this test. /// </summary> public readonly TestResult Results = new TestResult(); /// <summary> /// The time the test started. /// </summary> public DateTime StartTime { get; private set; } /// <summary> /// The time the test will be finished. /// </summary> public DateTime StopTime { get; private set;} /// <summary> /// True iff the test has been started. Each object can only /// run a test lifecycle one tim. /// </summary> public bool Started { get; private set; } /// <summary> /// Event triggered when hit data is received. /// </summary> public event HitEventHandler OnHit; #endregion #region Methods /// <summary> /// Creates the threads and starts the test. /// </summary> public void Start() { lock (this) { // check object state if (Started) { throw new Exception ("SeigeTest.Start() called on a test that was already started."); } // create the threads for (var i = 0; i < Settings.ThreadCount; i++) { TestThreads.Add (new Thread (ThreadMain)); } // set the time range for the test StartTime = DateTime.Now; StopTime = DateTime.Now.AddSeconds (Settings.TestSeconds); // get the threads rolling foreach (var t in TestThreads) { t.Start (); } Started = true; } } /// <summary> /// Politely tells the threads to not run anymore tests. The Wait() /// method can be used to detect when they have all finished. /// </summary> public void Stop() { StopTime = DateTime.Now; } /// <summary> /// Immediately aborts all threads. /// </summary> public void Kill() { foreach (var t in TestThreads) { t.Abort (); } } /// <summary> /// Waits for all test threads to finish, with an optional timeout. /// </summary> public bool Wait(int millisecondsTimeout = 0) { DateTime end = DateTime.Now.AddMilliseconds (millisecondsTimeout); foreach (var t in TestThreads) { if (millisecondsTimeout > 0) { t.Join (end - DateTime.Now); if (DateTime.Now >= end) { return false; } } else { t.Join (); } } return true; } #endregion #region Private Properties /// <summary> /// The threads running the test. /// </summary> private readonly List<Thread> TestThreads = new List<Thread>(); /// <summary> /// Shared random number generator. /// </summary> private readonly Random rnd = new Random(); #endregion #region Private Methods /// <summary> /// The logic run by each test thread. /// </summary> private void ThreadMain() { while (DateTime.Now < StopTime) { RandomPause (); var url = GetRandomUrl (); var hit = TestRequest (url); if (hit != null) { Results.AddHit (hit); if (OnHit != null) { OnHit (this, hit); } } } } /// <summary> /// Pauses the calling thread a random amount of time within the /// range set by the TestSettings. /// </summary> private void RandomPause () { var sec = Settings.MinPause + (Settings.MaxPause - Settings.MinPause) * rnd.NextDouble (); Thread.Sleep ((int)(sec*1000)); } /// <summary> /// Returns one url at random from those available in TestSettings. /// </summary> private string GetRandomUrl() { var i = rnd.Next (Settings.Urls.Count); return Settings.Urls [i]; } /// <summary> /// Does a test request against a URL returning a hit result record. /// </summary> private static Hit TestRequest(string url) { try { var start = DateTime.Now; string data; var request = (HttpWebRequest)WebRequest.Create (url); var response = (HttpWebResponse)request.GetResponse (); using (var s = response.GetResponseStream ()) { using (var sr = new StreamReader (s)) { data = sr.ReadToEnd (); } } var end = DateTime.Now; var result = new Hit (); result.Url = url; result.Bytes = data.Length; result.ResponseCode = response.StatusCode.ToString (); result.Time = (end - start); result.StartTime = start; response.Close (); return result; } catch { // TODO: better error handling. return null; } } #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. // namespace System.Reflection.Emit { using System; using System.Globalization; using System.Diagnostics.SymbolStore; using System.Runtime.InteropServices; using System.Reflection; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Security; internal class DynamicILGenerator : ILGenerator { internal DynamicScope m_scope; private int m_methodSigToken; internal unsafe DynamicILGenerator(DynamicMethod method, byte[] methodSignature, int size) : base(method, size) { m_scope = new DynamicScope(); m_methodSigToken = m_scope.GetTokenFor(methodSignature); } internal void GetCallableMethod(RuntimeModule module, DynamicMethod dm) { dm.m_methodHandle = ModuleHandle.GetDynamicMethod(dm, module, m_methodBuilder.Name, (byte[])m_scope[m_methodSigToken], new DynamicResolver(this)); } // *** ILGenerator api *** public override LocalBuilder DeclareLocal(Type localType, bool pinned) { LocalBuilder localBuilder; if (localType == null) throw new ArgumentNullException(nameof(localType)); RuntimeType rtType = localType as RuntimeType; if (rtType == null) throw new ArgumentException(SR.Argument_MustBeRuntimeType); localBuilder = new LocalBuilder(m_localCount, localType, m_methodBuilder); // add the localType to local signature m_localSignature.AddArgument(localType, pinned); m_localCount++; return localBuilder; } // // // Token resolution calls // // public override void Emit(OpCode opcode, MethodInfo meth) { if (meth == null) throw new ArgumentNullException(nameof(meth)); int stackchange = 0; int token = 0; DynamicMethod dynMeth = meth as DynamicMethod; if (dynMeth == null) { RuntimeMethodInfo rtMeth = meth as RuntimeMethodInfo; if (rtMeth == null) throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(meth)); RuntimeType declaringType = rtMeth.GetRuntimeType(); if (declaringType != null && (declaringType.IsGenericType || declaringType.IsArray)) token = GetTokenFor(rtMeth, declaringType); else token = GetTokenFor(rtMeth); } else { // rule out not allowed operations on DynamicMethods if (opcode.Equals(OpCodes.Ldtoken) || opcode.Equals(OpCodes.Ldftn) || opcode.Equals(OpCodes.Ldvirtftn)) { throw new ArgumentException(SR.Argument_InvalidOpCodeOnDynamicMethod); } token = GetTokenFor(dynMeth); } EnsureCapacity(7); InternalEmit(opcode); if (opcode.StackBehaviourPush == StackBehaviour.Varpush && meth.ReturnType != typeof(void)) { stackchange++; } if (opcode.StackBehaviourPop == StackBehaviour.Varpop) { stackchange -= meth.GetParametersNoCopy().Length; } // Pop the "this" parameter if the method is non-static, // and the instruction is not newobj/ldtoken/ldftn. if (!meth.IsStatic && !(opcode.Equals(OpCodes.Newobj) || opcode.Equals(OpCodes.Ldtoken) || opcode.Equals(OpCodes.Ldftn))) { stackchange--; } UpdateStackSize(opcode, stackchange); PutInteger4(token); } public override void Emit(OpCode opcode, ConstructorInfo con) { if (con == null) throw new ArgumentNullException(nameof(con)); RuntimeConstructorInfo rtConstructor = con as RuntimeConstructorInfo; if (rtConstructor == null) throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(con)); RuntimeType declaringType = rtConstructor.GetRuntimeType(); int token; if (declaringType != null && (declaringType.IsGenericType || declaringType.IsArray)) // need to sort out the stack size story token = GetTokenFor(rtConstructor, declaringType); else token = GetTokenFor(rtConstructor); EnsureCapacity(7); InternalEmit(opcode); // need to sort out the stack size story UpdateStackSize(opcode, 1); PutInteger4(token); } public override void Emit(OpCode opcode, Type type) { if (type == null) throw new ArgumentNullException(nameof(type)); RuntimeType rtType = type as RuntimeType; if (rtType == null) throw new ArgumentException(SR.Argument_MustBeRuntimeType); int token = GetTokenFor(rtType); EnsureCapacity(7); InternalEmit(opcode); PutInteger4(token); } public override void Emit(OpCode opcode, FieldInfo field) { if (field == null) throw new ArgumentNullException(nameof(field)); RuntimeFieldInfo runtimeField = field as RuntimeFieldInfo; if (runtimeField == null) throw new ArgumentException(SR.Argument_MustBeRuntimeFieldInfo, nameof(field)); int token; if (field.DeclaringType == null) token = GetTokenFor(runtimeField); else token = GetTokenFor(runtimeField, runtimeField.GetRuntimeType()); EnsureCapacity(7); InternalEmit(opcode); PutInteger4(token); } public override void Emit(OpCode opcode, String str) { if (str == null) throw new ArgumentNullException(nameof(str)); int tempVal = GetTokenForString(str); EnsureCapacity(7); InternalEmit(opcode); PutInteger4(tempVal); } // // // Signature related calls (vararg, calli) // // public override void EmitCalli(OpCode opcode, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, Type[] optionalParameterTypes) { int stackchange = 0; SignatureHelper sig; if (optionalParameterTypes != null) if ((callingConvention & CallingConventions.VarArgs) == 0) throw new InvalidOperationException(SR.InvalidOperation_NotAVarArgCallingConvention); sig = GetMemberRefSignature(callingConvention, returnType, parameterTypes, optionalParameterTypes); EnsureCapacity(7); Emit(OpCodes.Calli); // If there is a non-void return type, push one. if (returnType != typeof(void)) stackchange++; // Pop off arguments if any. if (parameterTypes != null) stackchange -= parameterTypes.Length; // Pop off vararg arguments. if (optionalParameterTypes != null) stackchange -= optionalParameterTypes.Length; // Pop the this parameter if the method has a this parameter. if ((callingConvention & CallingConventions.HasThis) == CallingConventions.HasThis) stackchange--; // Pop the native function pointer. stackchange--; UpdateStackSize(OpCodes.Calli, stackchange); int token = GetTokenForSig(sig.GetSignature(true)); PutInteger4(token); } public override void EmitCalli(OpCode opcode, CallingConvention unmanagedCallConv, Type returnType, Type[] parameterTypes) { int stackchange = 0; int cParams = 0; int i; SignatureHelper sig; if (parameterTypes != null) cParams = parameterTypes.Length; sig = SignatureHelper.GetMethodSigHelper(unmanagedCallConv, returnType); if (parameterTypes != null) for (i = 0; i < cParams; i++) sig.AddArgument(parameterTypes[i]); // If there is a non-void return type, push one. if (returnType != typeof(void)) stackchange++; // Pop off arguments if any. if (parameterTypes != null) stackchange -= cParams; // Pop the native function pointer. stackchange--; UpdateStackSize(OpCodes.Calli, stackchange); EnsureCapacity(7); Emit(OpCodes.Calli); int token = GetTokenForSig(sig.GetSignature(true)); PutInteger4(token); } public override void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes) { if (methodInfo == null) throw new ArgumentNullException(nameof(methodInfo)); if (!(opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt) || opcode.Equals(OpCodes.Newobj))) throw new ArgumentException(SR.Argument_NotMethodCallOpcode, nameof(opcode)); if (methodInfo.ContainsGenericParameters) throw new ArgumentException(SR.Argument_GenericsInvalid, nameof(methodInfo)); if (methodInfo.DeclaringType != null && methodInfo.DeclaringType.ContainsGenericParameters) throw new ArgumentException(SR.Argument_GenericsInvalid, nameof(methodInfo)); int tk; int stackchange = 0; tk = GetMemberRefToken(methodInfo, optionalParameterTypes); EnsureCapacity(7); InternalEmit(opcode); // Push the return value if there is one. if (methodInfo.ReturnType != typeof(void)) stackchange++; // Pop the parameters. stackchange -= methodInfo.GetParameterTypes().Length; // Pop the this parameter if the method is non-static and the // instruction is not newobj. if (!(methodInfo is SymbolMethod) && methodInfo.IsStatic == false && !(opcode.Equals(OpCodes.Newobj))) stackchange--; // Pop the optional parameters off the stack. if (optionalParameterTypes != null) stackchange -= optionalParameterTypes.Length; UpdateStackSize(opcode, stackchange); PutInteger4(tk); } public override void Emit(OpCode opcode, SignatureHelper signature) { if (signature == null) throw new ArgumentNullException(nameof(signature)); int stackchange = 0; EnsureCapacity(7); InternalEmit(opcode); // The only IL instruction that has VarPop behaviour, that takes a // Signature token as a parameter is calli. Pop the parameters and // the native function pointer. To be conservative, do not pop the // this pointer since this information is not easily derived from // SignatureHelper. if (opcode.StackBehaviourPop == StackBehaviour.Varpop) { Debug.Assert(opcode.Equals(OpCodes.Calli), "Unexpected opcode encountered for StackBehaviour VarPop."); // Pop the arguments.. stackchange -= signature.ArgumentCount; // Pop native function pointer off the stack. stackchange--; UpdateStackSize(opcode, stackchange); } int token = GetTokenForSig(signature.GetSignature(true)); PutInteger4(token); } // // // Exception related generation // // public override void BeginExceptFilterBlock() { // Begins an exception filter block. Emits a branch instruction to the end of the current exception block. if (CurrExcStackCount == 0) throw new NotSupportedException(SR.Argument_NotInExceptionBlock); __ExceptionInfo current = CurrExcStack[CurrExcStackCount - 1]; Label endLabel = current.GetEndLabel(); Emit(OpCodes.Leave, endLabel); UpdateStackSize(OpCodes.Nop, 1); current.MarkFilterAddr(ILOffset); } public override void BeginCatchBlock(Type exceptionType) { if (CurrExcStackCount == 0) throw new NotSupportedException(SR.Argument_NotInExceptionBlock); __ExceptionInfo current = CurrExcStack[CurrExcStackCount - 1]; RuntimeType rtType = exceptionType as RuntimeType; if (current.GetCurrentState() == __ExceptionInfo.State_Filter) { if (exceptionType != null) { throw new ArgumentException(SR.Argument_ShouldNotSpecifyExceptionType); } this.Emit(OpCodes.Endfilter); current.MarkCatchAddr(ILOffset, null); } else { // execute this branch if previous clause is Catch or Fault if (exceptionType == null) throw new ArgumentNullException(nameof(exceptionType)); if (rtType == null) throw new ArgumentException(SR.Argument_MustBeRuntimeType); Label endLabel = current.GetEndLabel(); this.Emit(OpCodes.Leave, endLabel); // if this is a catch block the exception will be pushed on the stack and we need to update the stack info UpdateStackSize(OpCodes.Nop, 1); current.MarkCatchAddr(ILOffset, exceptionType); // this is relying on too much implementation details of the base and so it's highly breaking // Need to have a more integrated story for exceptions current.m_filterAddr[current.m_currentCatch - 1] = GetTokenFor(rtType); } } // // // debugger related calls. // // public override void UsingNamespace(String ns) { throw new NotSupportedException(SR.InvalidOperation_NotAllowedInDynamicMethod); } public override void MarkSequencePoint(ISymbolDocumentWriter document, int startLine, int startColumn, int endLine, int endColumn) { throw new NotSupportedException(SR.InvalidOperation_NotAllowedInDynamicMethod); } public override void BeginScope() { throw new NotSupportedException(SR.InvalidOperation_NotAllowedInDynamicMethod); } public override void EndScope() { throw new NotSupportedException(SR.InvalidOperation_NotAllowedInDynamicMethod); } private int GetMemberRefToken(MethodBase methodInfo, Type[] optionalParameterTypes) { Type[] parameterTypes; if (optionalParameterTypes != null && (methodInfo.CallingConvention & CallingConventions.VarArgs) == 0) throw new InvalidOperationException(SR.InvalidOperation_NotAVarArgCallingConvention); RuntimeMethodInfo rtMeth = methodInfo as RuntimeMethodInfo; DynamicMethod dm = methodInfo as DynamicMethod; if (rtMeth == null && dm == null) throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(methodInfo)); ParameterInfo[] paramInfo = methodInfo.GetParametersNoCopy(); if (paramInfo != null && paramInfo.Length != 0) { parameterTypes = new Type[paramInfo.Length]; for (int i = 0; i < paramInfo.Length; i++) parameterTypes[i] = paramInfo[i].ParameterType; } else { parameterTypes = null; } SignatureHelper sig = GetMemberRefSignature(methodInfo.CallingConvention, MethodBuilder.GetMethodBaseReturnType(methodInfo), parameterTypes, optionalParameterTypes); if (rtMeth != null) return GetTokenForVarArgMethod(rtMeth, sig); else return GetTokenForVarArgMethod(dm, sig); } internal override SignatureHelper GetMemberRefSignature( CallingConventions call, Type returnType, Type[] parameterTypes, Type[] optionalParameterTypes) { SignatureHelper sig = SignatureHelper.GetMethodSigHelper(call, returnType); if (parameterTypes != null) { foreach (Type t in parameterTypes) sig.AddArgument(t); } if (optionalParameterTypes != null && optionalParameterTypes.Length != 0) { // add the sentinel sig.AddSentinel(); foreach (Type t in optionalParameterTypes) sig.AddArgument(t); } return sig; } internal override void RecordTokenFixup() { // DynamicMethod doesn't need fixup. } #region GetTokenFor helpers private int GetTokenFor(RuntimeType rtType) { return m_scope.GetTokenFor(rtType.TypeHandle); } private int GetTokenFor(RuntimeFieldInfo runtimeField) { return m_scope.GetTokenFor(runtimeField.FieldHandle); } private int GetTokenFor(RuntimeFieldInfo runtimeField, RuntimeType rtType) { return m_scope.GetTokenFor(runtimeField.FieldHandle, rtType.TypeHandle); } private int GetTokenFor(RuntimeConstructorInfo rtMeth) { return m_scope.GetTokenFor(rtMeth.MethodHandle); } private int GetTokenFor(RuntimeConstructorInfo rtMeth, RuntimeType rtType) { return m_scope.GetTokenFor(rtMeth.MethodHandle, rtType.TypeHandle); } private int GetTokenFor(RuntimeMethodInfo rtMeth) { return m_scope.GetTokenFor(rtMeth.MethodHandle); } private int GetTokenFor(RuntimeMethodInfo rtMeth, RuntimeType rtType) { return m_scope.GetTokenFor(rtMeth.MethodHandle, rtType.TypeHandle); } private int GetTokenFor(DynamicMethod dm) { return m_scope.GetTokenFor(dm); } private int GetTokenForVarArgMethod(RuntimeMethodInfo rtMeth, SignatureHelper sig) { VarArgMethod varArgMeth = new VarArgMethod(rtMeth, sig); return m_scope.GetTokenFor(varArgMeth); } private int GetTokenForVarArgMethod(DynamicMethod dm, SignatureHelper sig) { VarArgMethod varArgMeth = new VarArgMethod(dm, sig); return m_scope.GetTokenFor(varArgMeth); } private int GetTokenForString(String s) { return m_scope.GetTokenFor(s); } private int GetTokenForSig(byte[] sig) { return m_scope.GetTokenFor(sig); } #endregion } internal class DynamicResolver : Resolver { #region Private Data Members private __ExceptionInfo[] m_exceptions; private byte[] m_exceptionHeader; private DynamicMethod m_method; private byte[] m_code; private byte[] m_localSignature; private int m_stackSize; private DynamicScope m_scope; #endregion #region Internal Methods internal DynamicResolver(DynamicILGenerator ilGenerator) { m_stackSize = ilGenerator.GetMaxStackSize(); m_exceptions = ilGenerator.GetExceptions(); m_code = ilGenerator.BakeByteArray(); m_localSignature = ilGenerator.m_localSignature.InternalGetSignatureArray(); m_scope = ilGenerator.m_scope; m_method = (DynamicMethod)ilGenerator.m_methodBuilder; m_method.m_resolver = this; } internal DynamicResolver(DynamicILInfo dynamicILInfo) { m_stackSize = dynamicILInfo.MaxStackSize; m_code = dynamicILInfo.Code; m_localSignature = dynamicILInfo.LocalSignature; m_exceptionHeader = dynamicILInfo.Exceptions; //m_exceptions = dynamicILInfo.Exceptions; m_scope = dynamicILInfo.DynamicScope; m_method = dynamicILInfo.DynamicMethod; m_method.m_resolver = this; } // // We can destroy the unmanaged part of dynamic method only after the managed part is definitely gone and thus // nobody can call the dynamic method anymore. A call to finalizer alone does not guarantee that the managed // part is gone. A malicious code can keep a reference to DynamicMethod in long weak reference that survives finalization, // or we can be running during shutdown where everything is finalized. // // The unmanaged resolver keeps a reference to the managed resolver in long weak handle. If the long weak handle // is null, we can be sure that the managed part of the dynamic method is definitely gone and that it is safe to // destroy the unmanaged part. (Note that the managed finalizer has to be on the same object that the long weak handle // points to in order for this to work.) Unfortunately, we can not perform the above check when out finalizer // is called - the long weak handle won't be cleared yet. Instead, we create a helper scout object that will attempt // to do the destruction after next GC. // // The finalization does not have to be done using CriticalFinalizerObject. We have to go over all DynamicMethodDescs // during AppDomain shutdown anyway to avoid leaks e.g. if somebody stores reference to DynamicMethod in static. // ~DynamicResolver() { DynamicMethod method = m_method; if (method == null) return; if (method.m_methodHandle == null) return; DestroyScout scout = null; try { scout = new DestroyScout(); } catch { // We go over all DynamicMethodDesc during AppDomain shutdown and make sure // that everything associated with them is released. So it is ok to skip reregistration // for finalization during appdomain shutdown if (!Environment.HasShutdownStarted && !AppDomain.CurrentDomain.IsFinalizingForUnload()) { // Try again later. GC.ReRegisterForFinalize(this); } return; } // We can never ever have two active destroy scouts for the same method. We need to initialize the scout // outside the try/reregister block to avoid possibility of reregistration for finalization with active scout. scout.m_methodHandle = method.m_methodHandle.Value; } private class DestroyScout { internal RuntimeMethodHandleInternal m_methodHandle; ~DestroyScout() { if (m_methodHandle.IsNullHandle()) return; // It is not safe to destroy the method if the managed resolver is alive. if (RuntimeMethodHandle.GetResolver(m_methodHandle) != null) { if (!Environment.HasShutdownStarted && !AppDomain.CurrentDomain.IsFinalizingForUnload()) { // Somebody might have been holding a reference on us via weak handle. // We will keep trying. It will be hopefully released eventually. GC.ReRegisterForFinalize(this); } return; } RuntimeMethodHandle.Destroy(m_methodHandle); } } // Keep in sync with vm/dynamicmethod.h [Flags] internal enum SecurityControlFlags { Default = 0x0, SkipVisibilityChecks = 0x1, RestrictedSkipVisibilityChecks = 0x2, HasCreationContext = 0x4, CanSkipCSEvaluation = 0x8, } internal override RuntimeType GetJitContext(ref int securityControlFlags) { RuntimeType typeOwner; SecurityControlFlags flags = SecurityControlFlags.Default; if (m_method.m_restrictedSkipVisibility) flags |= SecurityControlFlags.RestrictedSkipVisibilityChecks; else if (m_method.m_skipVisibility) flags |= SecurityControlFlags.SkipVisibilityChecks; typeOwner = m_method.m_typeOwner; securityControlFlags = (int)flags; return typeOwner; } private static int CalculateNumberOfExceptions(__ExceptionInfo[] excp) { int num = 0; if (excp == null) return 0; for (int i = 0; i < excp.Length; i++) num += excp[i].GetNumberOfCatches(); return num; } internal override byte[] GetCodeInfo( ref int stackSize, ref int initLocals, ref int EHCount) { stackSize = m_stackSize; if (m_exceptionHeader != null && m_exceptionHeader.Length != 0) { if (m_exceptionHeader.Length < 4) throw new FormatException(); byte header = m_exceptionHeader[0]; if ((header & 0x40) != 0) // Fat { byte[] size = new byte[4]; for (int q = 0; q < 3; q++) size[q] = m_exceptionHeader[q + 1]; EHCount = (BitConverter.ToInt32(size, 0) - 4) / 24; } else EHCount = (m_exceptionHeader[1] - 2) / 12; } else { EHCount = CalculateNumberOfExceptions(m_exceptions); } initLocals = (m_method.InitLocals) ? 1 : 0; return m_code; } internal override byte[] GetLocalsSignature() { return m_localSignature; } internal override unsafe byte[] GetRawEHInfo() { return m_exceptionHeader; } internal override unsafe void GetEHInfo(int excNumber, void* exc) { CORINFO_EH_CLAUSE* exception = (CORINFO_EH_CLAUSE*)exc; for (int i = 0; i < m_exceptions.Length; i++) { int excCount = m_exceptions[i].GetNumberOfCatches(); if (excNumber < excCount) { // found the right exception block exception->Flags = m_exceptions[i].GetExceptionTypes()[excNumber]; exception->TryOffset = m_exceptions[i].GetStartAddress(); if ((exception->Flags & __ExceptionInfo.Finally) != __ExceptionInfo.Finally) exception->TryLength = m_exceptions[i].GetEndAddress() - exception->TryOffset; else exception->TryLength = m_exceptions[i].GetFinallyEndAddress() - exception->TryOffset; exception->HandlerOffset = m_exceptions[i].GetCatchAddresses()[excNumber]; exception->HandlerLength = m_exceptions[i].GetCatchEndAddresses()[excNumber] - exception->HandlerOffset; // this is cheating because the filter address is the token of the class only for light code gen exception->ClassTokenOrFilterOffset = m_exceptions[i].GetFilterAddresses()[excNumber]; break; } excNumber -= excCount; } } internal override String GetStringLiteral(int token) { return m_scope.GetString(token); } internal override void ResolveToken(int token, out IntPtr typeHandle, out IntPtr methodHandle, out IntPtr fieldHandle) { typeHandle = new IntPtr(); methodHandle = new IntPtr(); fieldHandle = new IntPtr(); Object handle = m_scope[token]; if (handle == null) throw new InvalidProgramException(); if (handle is RuntimeTypeHandle) { typeHandle = ((RuntimeTypeHandle)handle).Value; return; } if (handle is RuntimeMethodHandle) { methodHandle = ((RuntimeMethodHandle)handle).Value; return; } if (handle is RuntimeFieldHandle) { fieldHandle = ((RuntimeFieldHandle)handle).Value; return; } DynamicMethod dm = handle as DynamicMethod; if (dm != null) { methodHandle = dm.GetMethodDescriptor().Value; return; } GenericMethodInfo gmi = handle as GenericMethodInfo; if (gmi != null) { methodHandle = gmi.m_methodHandle.Value; typeHandle = gmi.m_context.Value; return; } GenericFieldInfo gfi = handle as GenericFieldInfo; if (gfi != null) { fieldHandle = gfi.m_fieldHandle.Value; typeHandle = gfi.m_context.Value; return; } VarArgMethod vaMeth = handle as VarArgMethod; if (vaMeth != null) { if (vaMeth.m_dynamicMethod == null) { methodHandle = vaMeth.m_method.MethodHandle.Value; typeHandle = vaMeth.m_method.GetDeclaringTypeInternal().GetTypeHandleInternal().Value; } else methodHandle = vaMeth.m_dynamicMethod.GetMethodDescriptor().Value; return; } } internal override byte[] ResolveSignature(int token, int fromMethod) { return m_scope.ResolveSignature(token, fromMethod); } internal override MethodInfo GetDynamicMethod() { return m_method.GetMethodInfo(); } #endregion } internal class DynamicILInfo { #region Private Data Members private DynamicMethod m_method; private DynamicScope m_scope; private byte[] m_exceptions; private byte[] m_code; private byte[] m_localSignature; private int m_maxStackSize; private int m_methodSignature; #endregion #region Internal Methods internal void GetCallableMethod(RuntimeModule module, DynamicMethod dm) { dm.m_methodHandle = ModuleHandle.GetDynamicMethod(dm, module, m_method.Name, (byte[])m_scope[m_methodSignature], new DynamicResolver(this)); } internal byte[] LocalSignature { get { if (m_localSignature == null) m_localSignature = SignatureHelper.GetLocalVarSigHelper().InternalGetSignatureArray(); return m_localSignature; } } internal byte[] Exceptions { get { return m_exceptions; } } internal byte[] Code { get { return m_code; } } internal int MaxStackSize { get { return m_maxStackSize; } } #endregion #region Public ILGenerator Methods public DynamicMethod DynamicMethod { get { return m_method; } } internal DynamicScope DynamicScope { get { return m_scope; } } #endregion #region Public Scope Methods #endregion } internal class DynamicScope { #region Private Data Members internal List<Object> m_tokens; #endregion #region Constructor internal unsafe DynamicScope() { m_tokens = new List<Object>(); m_tokens.Add(null); } #endregion #region Internal Methods internal object this[int token] { get { token &= 0x00FFFFFF; if (token < 0 || token > m_tokens.Count) return null; return m_tokens[token]; } } internal int GetTokenFor(VarArgMethod varArgMethod) { m_tokens.Add(varArgMethod); return m_tokens.Count - 1 | (int)MetadataTokenType.MemberRef; } internal string GetString(int token) { return this[token] as string; } internal byte[] ResolveSignature(int token, int fromMethod) { if (fromMethod == 0) return (byte[])this[token]; VarArgMethod vaMethod = this[token] as VarArgMethod; if (vaMethod == null) return null; return vaMethod.m_signature.GetSignature(true); } #endregion #region Public Methods public int GetTokenFor(RuntimeMethodHandle method) { IRuntimeMethodInfo methodReal = method.GetMethodInfo(); RuntimeMethodHandleInternal rmhi = methodReal.Value; if (methodReal != null && !RuntimeMethodHandle.IsDynamicMethod(rmhi)) { RuntimeType type = RuntimeMethodHandle.GetDeclaringType(rmhi); if ((type != null) && RuntimeTypeHandle.HasInstantiation(type)) { // Do we really need to retrieve this much info just to throw an exception? MethodBase m = RuntimeType.GetMethodBase(methodReal); Type t = m.DeclaringType.GetGenericTypeDefinition(); throw new ArgumentException(String.Format( CultureInfo.CurrentCulture, SR.Argument_MethodDeclaringTypeGenericLcg, m, t)); } } m_tokens.Add(method); return m_tokens.Count - 1 | (int)MetadataTokenType.MethodDef; } public int GetTokenFor(RuntimeMethodHandle method, RuntimeTypeHandle typeContext) { m_tokens.Add(new GenericMethodInfo(method, typeContext)); return m_tokens.Count - 1 | (int)MetadataTokenType.MethodDef; } public int GetTokenFor(DynamicMethod method) { m_tokens.Add(method); return m_tokens.Count - 1 | (int)MetadataTokenType.MethodDef; } public int GetTokenFor(RuntimeFieldHandle field) { m_tokens.Add(field); return m_tokens.Count - 1 | (int)MetadataTokenType.FieldDef; } public int GetTokenFor(RuntimeFieldHandle field, RuntimeTypeHandle typeContext) { m_tokens.Add(new GenericFieldInfo(field, typeContext)); return m_tokens.Count - 1 | (int)MetadataTokenType.FieldDef; } public int GetTokenFor(RuntimeTypeHandle type) { m_tokens.Add(type); return m_tokens.Count - 1 | (int)MetadataTokenType.TypeDef; } public int GetTokenFor(string literal) { m_tokens.Add(literal); return m_tokens.Count - 1 | (int)MetadataTokenType.String; } public int GetTokenFor(byte[] signature) { m_tokens.Add(signature); return m_tokens.Count - 1 | (int)MetadataTokenType.Signature; } #endregion } internal sealed class GenericMethodInfo { internal RuntimeMethodHandle m_methodHandle; internal RuntimeTypeHandle m_context; internal GenericMethodInfo(RuntimeMethodHandle methodHandle, RuntimeTypeHandle context) { m_methodHandle = methodHandle; m_context = context; } } internal sealed class GenericFieldInfo { internal RuntimeFieldHandle m_fieldHandle; internal RuntimeTypeHandle m_context; internal GenericFieldInfo(RuntimeFieldHandle fieldHandle, RuntimeTypeHandle context) { m_fieldHandle = fieldHandle; m_context = context; } } internal sealed class VarArgMethod { internal RuntimeMethodInfo m_method; internal DynamicMethod m_dynamicMethod; internal SignatureHelper m_signature; internal VarArgMethod(DynamicMethod dm, SignatureHelper signature) { m_dynamicMethod = dm; m_signature = signature; } internal VarArgMethod(RuntimeMethodInfo method, SignatureHelper signature) { m_method = method; m_signature = signature; } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Xml.Linq; using Adxstudio.Xrm.Resources; using Adxstudio.Xrm.Web.UI.WebControls; using Microsoft.Xrm.Client; using Microsoft.Xrm.Client.Configuration; using Microsoft.Xrm.Portal.Web.UI.CrmEntityFormView; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Query; namespace Adxstudio.Xrm.Web.UI.CrmEntityFormView { /// <summary> /// Template used when rendering a Subject Lookup field. /// </summary> public class SubjectControlTemplate : CellTemplate, ICustomFieldControlTemplate { /// <summary> /// SubjecControlTemplate class initialization. /// </summary> /// <param name="field"></param> /// <param name="metadata"></param> /// <param name="validationGroup"></param> /// <param name="bindings"></param> public SubjectControlTemplate(CrmEntityFormViewField field, FormXmlCellMetadata metadata, string validationGroup, IDictionary<string, CellBinding> bindings) : base(metadata, validationGroup, bindings) { Field = field; } /// <summary> /// Form field. /// </summary> public CrmEntityFormViewField Field { get; private set; } public override string CssClass { get { return "lookup"; } } private string ValidationText { get { return Metadata.ValidationText; } } private ValidatorDisplay ValidatorDisplay { get { return string.IsNullOrWhiteSpace(ValidationText) ? ValidatorDisplay.None : ValidatorDisplay.Dynamic; } } protected override void InstantiateControlIn(Control container) { var dropDown = new DropDownList { ID = ControlID, CssClass = string.Join(" ", "form-control", CssClass, Metadata.CssClass), ToolTip = Metadata.ToolTip }; dropDown.Attributes.Add("onchange", "setIsDirty(this.id);"); container.Controls.Add(dropDown); if (Metadata.IsRequired || Metadata.WebFormForceFieldIsRequired) { dropDown.Attributes.Add("required", string.Empty); } if (Metadata.ReadOnly || ((WebControls.CrmEntityFormView)container.BindingContainer).Mode == FormViewMode.ReadOnly) { AddSpecialBindingAndHiddenFieldsToPersistDisabledSelect(container, dropDown); } else { PopulateDropDown(dropDown); Bindings[Metadata.DataFieldName] = new CellBinding { Get = () => { Guid id; return !Guid.TryParse(dropDown.SelectedValue, out id) ? null : new EntityReference("subject", id); }, Set = obj => { var entityReference = (EntityReference)obj; dropDown.SelectedValue = entityReference.Id.ToString(); } }; } } protected override void InstantiateValidatorsIn(Control container) { if (Metadata.IsRequired || Metadata.WebFormForceFieldIsRequired) { container.Controls.Add(new RequiredFieldValidator { ID = string.Format("RequiredFieldValidator{0}", ControlID), ControlToValidate = ControlID, ValidationGroup = ValidationGroup, Display = ValidatorDisplay, ErrorMessage = ValidationSummaryMarkup((string.IsNullOrWhiteSpace(Metadata.RequiredFieldValidationErrorMessage) ? (Metadata.Messages == null || !Metadata.Messages.ContainsKey("required")) ? ResourceManager.GetString("Required_Field_Error").FormatWith(Metadata.Label) : Metadata.Messages["required"].FormatWith(Metadata.Label) : Metadata.RequiredFieldValidationErrorMessage)), Text = Metadata.ValidationText, }); } this.InstantiateCustomValidatorsIn(container); } private void AddSpecialBindingAndHiddenFieldsToPersistDisabledSelect(Control container, DropDownList dropDown) { dropDown.CssClass = string.Join(" ", dropDown.CssClass, "readonly"); dropDown.Attributes["disabled"] = "disabled"; dropDown.Attributes["aria-disabled"] = "true"; var hiddenValue = new HiddenField { ID = "{0}_Value".FormatWith(ControlID) }; container.Controls.Add(hiddenValue); var hiddenSelectedIndex = new HiddenField { ID = "{0}_SelectedIndex".FormatWith(ControlID) }; container.Controls.Add(hiddenSelectedIndex); RegisterClientSideDependencies(container); Bindings[Metadata.DataFieldName] = new CellBinding { Get = () => { Guid id; return !Guid.TryParse(hiddenValue.Value, out id) ? null : new EntityReference("subject", id); }, Set = obj => { var entityReference = (EntityReference)obj; dropDown.Items.Add(new ListItem { Value = entityReference.Id.ToString(), Text = entityReference.Name ?? string.Empty }); dropDown.SelectedValue = "{0}".FormatWith(entityReference.Id); hiddenValue.Value = dropDown.SelectedValue; hiddenSelectedIndex.Value = dropDown.SelectedIndex.ToString(CultureInfo.InvariantCulture); } }; } private void PopulateDropDown(DropDownList dropDown) { if (dropDown.Items.Count > 0) { return; } var empty = new ListItem(string.Empty, string.Empty); empty.Attributes["label"] = " "; dropDown.Items.Add(empty); var context = CrmConfigurationManager.CreateContext(); var service = CrmConfigurationManager.CreateService(); // By default a lookup field cell defined in the form XML does not contain view parameters unless the user has specified a view that is not the default for that entity and we must query to find the default view. Saved Query entity's QueryType code 64 indicates a lookup view. var view = Metadata.LookupViewID == Guid.Empty ? context.CreateQuery("savedquery").FirstOrDefault(s => s.GetAttributeValue<string>("returnedtypecode") == "subject" && s.GetAttributeValue<bool?>("isdefault").GetValueOrDefault(false) && s.GetAttributeValue<int>("querytype") == 64) : context.CreateQuery("savedquery").FirstOrDefault(s => s.GetAttributeValue<Guid>("savedqueryid") == Metadata.LookupViewID); List<Entity> subjects; if (view != null) { var fetchXML = view.GetAttributeValue<string>("fetchxml"); var xElement = XElement.Parse(fetchXML); var parentsubjectElement = xElement.Descendants("attribute").FirstOrDefault(e => { var xAttribute = e.Attribute("name"); return xAttribute != null && xAttribute.Value == "parentsubject"; }); if (parentsubjectElement == null) { //If fetchxml does not contain the parentsubject attribute then it must be injected so the results can be organized in a hierarchical order. var entityElement = xElement.Element("entity"); if (entityElement == null) { return; } var p = new XElement("attribute", new XAttribute("name", "parentsubject")); entityElement.Add(p); fetchXML = xElement.ToString(); } var data = service.RetrieveMultiple(new FetchExpression(fetchXML)); if (data == null || data.Entities == null) { return; } subjects = data.Entities.ToList(); } else { subjects = context.CreateQuery("subject").ToList(); } var parents = subjects.Where(s => s.GetAttributeValue<EntityReference>("parentsubject") == null).OrderBy(s => s.GetAttributeValue<string>("title")); foreach (var parent in parents) { if (parent == null) { continue; } dropDown.Items.Add(new ListItem(parent.GetAttributeValue<string>("title"), parent.Id.ToString())); var parentId = parent.Id; var children = subjects.Where(s => s.GetAttributeValue<EntityReference>("parentsubject") != null && s.GetAttributeValue<EntityReference>("parentsubject").Id == parentId).OrderBy(s => s.GetAttributeValue<string>("title")); AddChildItems(dropDown, subjects, children, 1); } } protected void AddChildItems(DropDownList dropDown, List<Entity> subjects, IEnumerable<Entity> children, int depth) { foreach (var child in children) { if (child == null) { continue; } var padding = HttpUtility.HtmlDecode(string.Concat(Enumerable.Repeat("&nbsp;-&nbsp;", depth))); dropDown.Items.Add(new ListItem(string.Format("{0}{1}", padding, child.GetAttributeValue<string>("title")), child.Id.ToString())); var childId = child.Id; var grandchildren = subjects.Where(s => s.GetAttributeValue<EntityReference>("parentsubject") != null && s.GetAttributeValue<EntityReference>("parentsubject").Id == childId).OrderBy(s => s.GetAttributeValue<string>("title")); depth++; AddChildItems(dropDown, subjects, grandchildren, depth); depth--; } } } }
// 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; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Reflection; using System.Runtime; using System.Runtime.Serialization; using System.Security; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Dispatcher; using System.Xml; using System.Xml.Serialization; namespace System.ServiceModel.Description { public class XmlSerializerOperationBehavior : IOperationBehavior { private readonly Reflector.OperationReflector _reflector; private readonly bool _builtInOperationBehavior; public XmlSerializerOperationBehavior(OperationDescription operation) : this(operation, null) { } public XmlSerializerOperationBehavior(OperationDescription operation, XmlSerializerFormatAttribute attribute) { if (operation == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("operation"); #pragma warning suppress 56506 // Declaring contract cannot be null Reflector parentReflector = new Reflector(operation.DeclaringContract.Namespace, operation.DeclaringContract.ContractType); #pragma warning suppress 56506 // parentReflector cannot be null _reflector = parentReflector.ReflectOperation(operation, attribute ?? new XmlSerializerFormatAttribute()); } internal XmlSerializerOperationBehavior(OperationDescription operation, XmlSerializerFormatAttribute attribute, Reflector parentReflector) : this(operation, attribute) { // used by System.ServiceModel.Web _reflector = parentReflector.ReflectOperation(operation, attribute ?? new XmlSerializerFormatAttribute()); } private XmlSerializerOperationBehavior(Reflector.OperationReflector reflector, bool builtInOperationBehavior) { Fx.Assert(reflector != null, ""); _reflector = reflector; _builtInOperationBehavior = builtInOperationBehavior; } internal Reflector.OperationReflector OperationReflector { get { return _reflector; } } internal bool IsBuiltInOperationBehavior { get { return _builtInOperationBehavior; } } public XmlSerializerFormatAttribute XmlSerializerFormatAttribute { get { return _reflector.Attribute; } } internal static XmlSerializerOperationFormatter CreateOperationFormatter(OperationDescription operation) { return new XmlSerializerOperationBehavior(operation).CreateFormatter(); } internal static XmlSerializerOperationFormatter CreateOperationFormatter(OperationDescription operation, XmlSerializerFormatAttribute attr) { return new XmlSerializerOperationBehavior(operation, attr).CreateFormatter(); } internal static void AddBehaviors(ContractDescription contract) { AddBehaviors(contract, false); } internal static void AddBuiltInBehaviors(ContractDescription contract) { AddBehaviors(contract, true); } private static void AddBehaviors(ContractDescription contract, bool builtInOperationBehavior) { Reflector reflector = new Reflector(contract.Namespace, contract.ContractType); foreach (OperationDescription operation in contract.Operations) { Reflector.OperationReflector operationReflector = reflector.ReflectOperation(operation); if (operationReflector != null) { bool isInherited = operation.DeclaringContract != contract; if (!isInherited) { operation.Behaviors.Add(new XmlSerializerOperationBehavior(operationReflector, builtInOperationBehavior)); } } } } internal XmlSerializerOperationFormatter CreateFormatter() { return new XmlSerializerOperationFormatter(_reflector.Operation, _reflector.Attribute, _reflector.Request, _reflector.Reply); } private XmlSerializerFaultFormatter CreateFaultFormatter(SynchronizedCollection<FaultContractInfo> faultContractInfos) { return new XmlSerializerFaultFormatter(faultContractInfos, _reflector.XmlSerializerFaultContractInfos); } void IOperationBehavior.Validate(OperationDescription description) { } void IOperationBehavior.AddBindingParameters(OperationDescription description, BindingParameterCollection parameters) { } void IOperationBehavior.ApplyDispatchBehavior(OperationDescription description, DispatchOperation dispatch) { if (description == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("description"); if (dispatch == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("dispatch"); if (dispatch.Formatter == null) { dispatch.Formatter = (IDispatchMessageFormatter)CreateFormatter(); dispatch.DeserializeRequest = _reflector.RequestRequiresSerialization; dispatch.SerializeReply = _reflector.ReplyRequiresSerialization; } if (_reflector.Attribute.SupportFaults && !dispatch.IsFaultFormatterSetExplicit) { dispatch.FaultFormatter = (IDispatchFaultFormatter)CreateFaultFormatter(dispatch.FaultContractInfos); } } void IOperationBehavior.ApplyClientBehavior(OperationDescription description, ClientOperation proxy) { if (description == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("description"); if (proxy == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("proxy"); if (proxy.Formatter == null) { proxy.Formatter = (IClientMessageFormatter)CreateFormatter(); proxy.SerializeRequest = _reflector.RequestRequiresSerialization; proxy.DeserializeReply = _reflector.ReplyRequiresSerialization; } if (_reflector.Attribute.SupportFaults && !proxy.IsFaultFormatterSetExplicit) proxy.FaultFormatter = (IClientFaultFormatter)CreateFaultFormatter(proxy.FaultContractInfos); } // helper for reflecting operations internal class Reflector { private readonly XmlSerializerImporter _importer; private readonly SerializerGenerationContext _generation; private Collection<OperationReflector> _operationReflectors = new Collection<OperationReflector>(); private object _thisLock = new object(); internal Reflector(string defaultNs, Type type) { _importer = new XmlSerializerImporter(defaultNs); _generation = new SerializerGenerationContext(type); } internal void EnsureMessageInfos() { lock (_thisLock) { foreach (OperationReflector operationReflector in _operationReflectors) { operationReflector.EnsureMessageInfos(); } } } private static XmlSerializerFormatAttribute FindAttribute(OperationDescription operation) { Type contractType = operation.DeclaringContract != null ? operation.DeclaringContract.ContractType : null; XmlSerializerFormatAttribute contractFormatAttribute = contractType != null ? TypeLoader.GetFormattingAttribute(contractType, null) as XmlSerializerFormatAttribute : null; return TypeLoader.GetFormattingAttribute(operation.OperationMethod, contractFormatAttribute) as XmlSerializerFormatAttribute; } // auto-reflects the operation, returning null if no attribute was found or inherited internal OperationReflector ReflectOperation(OperationDescription operation) { XmlSerializerFormatAttribute attr = FindAttribute(operation); if (attr == null) return null; return ReflectOperation(operation, attr); } // overrides the auto-reflection with an attribute internal OperationReflector ReflectOperation(OperationDescription operation, XmlSerializerFormatAttribute attrOverride) { OperationReflector operationReflector = new OperationReflector(this, operation, attrOverride, true/*reflectOnDemand*/); _operationReflectors.Add(operationReflector); return operationReflector; } internal class OperationReflector { private readonly Reflector _parent; internal readonly OperationDescription Operation; internal readonly XmlSerializerFormatAttribute Attribute; internal readonly bool IsRpc; internal readonly bool IsOneWay; internal readonly bool RequestRequiresSerialization; internal readonly bool ReplyRequiresSerialization; private readonly string _keyBase; private MessageInfo _request; private MessageInfo _reply; private SynchronizedCollection<XmlSerializerFaultContractInfo> _xmlSerializerFaultContractInfos; internal OperationReflector(Reflector parent, OperationDescription operation, XmlSerializerFormatAttribute attr, bool reflectOnDemand) { Fx.Assert(parent != null, ""); Fx.Assert(operation != null, ""); Fx.Assert(attr != null, ""); OperationFormatter.Validate(operation, attr.Style == OperationFormatStyle.Rpc, false/*IsEncoded*/); _parent = parent; this.Operation = operation; this.Attribute = attr; this.IsRpc = (attr.Style == OperationFormatStyle.Rpc); this.IsOneWay = operation.Messages.Count == 1; this.RequestRequiresSerialization = !operation.Messages[0].IsUntypedMessage; this.ReplyRequiresSerialization = !this.IsOneWay && !operation.Messages[1].IsUntypedMessage; MethodInfo methodInfo = operation.OperationMethod; if (methodInfo == null) { // keyBase needs to be unique within the scope of the parent reflector _keyBase = string.Empty; if (operation.DeclaringContract != null) { _keyBase = operation.DeclaringContract.Name + "," + operation.DeclaringContract.Namespace + ":"; } _keyBase = _keyBase + operation.Name; } else _keyBase = methodInfo.DeclaringType.FullName + ":" + methodInfo.ToString(); foreach (MessageDescription message in operation.Messages) foreach (MessageHeaderDescription header in message.Headers) SetUnknownHeaderInDescription(header); if (!reflectOnDemand) { this.EnsureMessageInfos(); } } private void SetUnknownHeaderInDescription(MessageHeaderDescription header) { if (header.AdditionalAttributesProvider != null) { object[] attrs = header.AdditionalAttributesProvider.GetCustomAttributes(false); foreach (var attr in attrs) { if (attr is XmlAnyElementAttribute) { if (String.IsNullOrEmpty(((XmlAnyElementAttribute)attr).Name)) { header.IsUnknownHeaderCollection = true; } } } } } private string ContractName { get { return this.Operation.DeclaringContract.Name; } } private string ContractNamespace { get { return this.Operation.DeclaringContract.Namespace; } } internal MessageInfo Request { get { _parent.EnsureMessageInfos(); return _request; } } internal MessageInfo Reply { get { _parent.EnsureMessageInfos(); return _reply; } } internal SynchronizedCollection<XmlSerializerFaultContractInfo> XmlSerializerFaultContractInfos { get { _parent.EnsureMessageInfos(); return _xmlSerializerFaultContractInfos; } } internal void EnsureMessageInfos() { if (_request == null) { foreach (Type knownType in Operation.KnownTypes) { if (knownType == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxKnownTypeNull, Operation.Name))); _parent._importer.IncludeType(knownType); } _request = CreateMessageInfo(this.Operation.Messages[0], ":Request"); // We don't do the following check at Net Native runtime because XmlMapping.XsdElementName // is not available at that time. bool skipVerifyXsdElementName = false; #if FEATURE_NETNATIVE skipVerifyXsdElementName = GeneratedXmlSerializers.IsInitialized; #endif if (_request != null && this.IsRpc && this.Operation.IsValidateRpcWrapperName && !skipVerifyXsdElementName && _request.BodyMapping.XsdElementName != this.Operation.Name) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxRpcMessageBodyPartNameInvalid, Operation.Name, this.Operation.Messages[0].MessageName, _request.BodyMapping.XsdElementName, this.Operation.Name))); if (!this.IsOneWay) { _reply = CreateMessageInfo(this.Operation.Messages[1], ":Response"); XmlName responseName = TypeLoader.GetBodyWrapperResponseName(this.Operation.Name); if (_reply != null && this.IsRpc && this.Operation.IsValidateRpcWrapperName && !skipVerifyXsdElementName && _reply.BodyMapping.XsdElementName != responseName.EncodedName) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxRpcMessageBodyPartNameInvalid, Operation.Name, this.Operation.Messages[1].MessageName, _reply.BodyMapping.XsdElementName, responseName.EncodedName))); } if (this.Attribute.SupportFaults) { GenerateXmlSerializerFaultContractInfos(); } } } private void GenerateXmlSerializerFaultContractInfos() { SynchronizedCollection<XmlSerializerFaultContractInfo> faultInfos = new SynchronizedCollection<XmlSerializerFaultContractInfo>(); for (int i = 0; i < this.Operation.Faults.Count; i++) { FaultDescription fault = this.Operation.Faults[i]; FaultContractInfo faultContractInfo = new FaultContractInfo(fault.Action, fault.DetailType, fault.ElementName, fault.Namespace, this.Operation.KnownTypes); XmlQualifiedName elementName; XmlMembersMapping xmlMembersMapping = this.ImportFaultElement(fault, out elementName); SerializerStub serializerStub = _parent._generation.AddSerializer(xmlMembersMapping); faultInfos.Add(new XmlSerializerFaultContractInfo(faultContractInfo, serializerStub, elementName)); } _xmlSerializerFaultContractInfos = faultInfos; } private MessageInfo CreateMessageInfo(MessageDescription message, string key) { if (message.IsUntypedMessage) return null; MessageInfo info = new MessageInfo(); bool isEncoded = false; if (message.IsTypedMessage) key = message.MessageType.FullName + ":" + isEncoded + ":" + IsRpc; XmlMembersMapping headersMapping = LoadHeadersMapping(message, key + ":Headers"); info.SetHeaders(_parent._generation.AddSerializer(headersMapping)); MessagePartDescriptionCollection rpcEncodedTypedMessgeBodyParts; info.SetBody(_parent._generation.AddSerializer(LoadBodyMapping(message, key, out rpcEncodedTypedMessgeBodyParts)), rpcEncodedTypedMessgeBodyParts); CreateHeaderDescriptionTable(message, info, headersMapping); return info; } private void CreateHeaderDescriptionTable(MessageDescription message, MessageInfo info, XmlMembersMapping headersMapping) { int headerNameIndex = 0; OperationFormatter.MessageHeaderDescriptionTable headerDescriptionTable = new OperationFormatter.MessageHeaderDescriptionTable(); info.SetHeaderDescriptionTable(headerDescriptionTable); foreach (MessageHeaderDescription header in message.Headers) { if (header.IsUnknownHeaderCollection) info.SetUnknownHeaderDescription(header); else if (headersMapping != null) { XmlMemberMapping memberMapping = headersMapping[headerNameIndex++]; string headerName, headerNs; headerName = memberMapping.XsdElementName; headerNs = memberMapping.Namespace; if (headerName != header.Name) { if (message.MessageType != null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxHeaderNameMismatchInMessageContract, message.MessageType, header.MemberInfo.Name, header.Name, headerName))); else throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxHeaderNameMismatchInOperation, this.Operation.Name, this.Operation.DeclaringContract.Name, this.Operation.DeclaringContract.Namespace, header.Name, headerName))); } if (headerNs != header.Namespace) { if (message.MessageType != null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxHeaderNamespaceMismatchInMessageContract, message.MessageType, header.MemberInfo.Name, header.Namespace, headerNs))); else throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxHeaderNamespaceMismatchInOperation, this.Operation.Name, this.Operation.DeclaringContract.Name, this.Operation.DeclaringContract.Namespace, header.Namespace, headerNs))); } headerDescriptionTable.Add(headerName, headerNs, header); } } } private XmlMembersMapping LoadBodyMapping(MessageDescription message, string mappingKey, out MessagePartDescriptionCollection rpcEncodedTypedMessageBodyParts) { MessagePartDescription returnPart; string wrapperName, wrapperNs; MessagePartDescriptionCollection bodyParts; rpcEncodedTypedMessageBodyParts = null; returnPart = OperationFormatter.IsValidReturnValue(message.Body.ReturnValue) ? message.Body.ReturnValue : null; bodyParts = message.Body.Parts; wrapperName = message.Body.WrapperName; wrapperNs = message.Body.WrapperNamespace; bool isWrapped = (wrapperName != null); bool hasReturnValue = returnPart != null; int paramCount = bodyParts.Count + (hasReturnValue ? 1 : 0); if (paramCount == 0 && !isWrapped) // no need to create serializer { return null; } XmlReflectionMember[] members = new XmlReflectionMember[paramCount]; int paramIndex = 0; if (hasReturnValue) members[paramIndex++] = XmlSerializerHelper.GetXmlReflectionMember(returnPart, IsRpc, isWrapped); for (int i = 0; i < bodyParts.Count; i++) members[paramIndex++] = XmlSerializerHelper.GetXmlReflectionMember(bodyParts[i], IsRpc, isWrapped); if (!isWrapped) wrapperNs = ContractNamespace; return ImportMembersMapping(wrapperName, wrapperNs, members, isWrapped, IsRpc, mappingKey); } private XmlMembersMapping LoadHeadersMapping(MessageDescription message, string mappingKey) { int headerCount = message.Headers.Count; if (headerCount == 0) return null; int unknownHeaderCount = 0, headerIndex = 0; XmlReflectionMember[] members = new XmlReflectionMember[headerCount]; for (int i = 0; i < headerCount; i++) { MessageHeaderDescription header = message.Headers[i]; if (!header.IsUnknownHeaderCollection) { members[headerIndex++] = XmlSerializerHelper.GetXmlReflectionMember(header, false/*isRpc*/, false/*isWrapped*/); } else { unknownHeaderCount++; } } if (unknownHeaderCount == headerCount) { return null; } if (unknownHeaderCount > 0) { XmlReflectionMember[] newMembers = new XmlReflectionMember[headerCount - unknownHeaderCount]; Array.Copy(members, newMembers, newMembers.Length); members = newMembers; } return ImportMembersMapping(ContractName, ContractNamespace, members, false /*isWrapped*/, false /*isRpc*/, mappingKey); } internal XmlMembersMapping ImportMembersMapping(string elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool rpc, string mappingKey) { string key = mappingKey.StartsWith(":", StringComparison.Ordinal) ? _keyBase + mappingKey : mappingKey; return _parent._importer.ImportMembersMapping(new XmlName(elementName, true /*isEncoded*/), ns, members, hasWrapperElement, rpc, key); } internal XmlMembersMapping ImportFaultElement(FaultDescription fault, out XmlQualifiedName elementName) { // the number of reflection members is always 1 because there is only one fault detail type XmlReflectionMember[] members = new XmlReflectionMember[1]; XmlName faultElementName = fault.ElementName; string faultNamespace = fault.Namespace; if (faultElementName == null) { XmlTypeMapping mapping = _parent._importer.ImportTypeMapping(fault.DetailType); faultElementName = new XmlName(mapping.ElementName, false /*isEncoded*/); faultNamespace = mapping.Namespace; if (faultElementName == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxFaultTypeAnonymous, this.Operation.Name, fault.DetailType.FullName))); } elementName = new XmlQualifiedName(faultElementName.DecodedName, faultNamespace); members[0] = XmlSerializerHelper.GetXmlReflectionMember(null /*memberName*/, faultElementName, faultNamespace, fault.DetailType, null /*additionalAttributesProvider*/, false /*isMultiple*/, false /*isWrapped*/); string mappingKey = "fault:" + faultElementName.DecodedName + ":" + faultNamespace; return ImportMembersMapping(faultElementName.EncodedName, faultNamespace, members, false /*hasWrapperElement*/, this.IsRpc, mappingKey); } } private class XmlSerializerImporter { private readonly string _defaultNs; private XmlReflectionImporter _xmlImporter; private Dictionary<string, XmlMembersMapping> _xmlMappings; internal XmlSerializerImporter(string defaultNs) { _defaultNs = defaultNs; _xmlImporter = null; } private XmlReflectionImporter XmlImporter { get { if (_xmlImporter == null) { _xmlImporter = new XmlReflectionImporter(_defaultNs); } return _xmlImporter; } } private Dictionary<string, XmlMembersMapping> XmlMappings { get { if (_xmlMappings == null) { _xmlMappings = new Dictionary<string, XmlMembersMapping>(); } return _xmlMappings; } } internal XmlMembersMapping ImportMembersMapping(XmlName elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool rpc, string mappingKey) { XmlMembersMapping mapping; string mappingName = elementName.DecodedName; if (XmlMappings.TryGetValue(mappingKey, out mapping)) { return mapping; } mapping = this.XmlImporter.ImportMembersMapping(mappingName, ns, members, hasWrapperElement, rpc); mapping.SetKey(mappingKey); XmlMappings.Add(mappingKey, mapping); return mapping; } internal XmlTypeMapping ImportTypeMapping(Type type) { return this.XmlImporter.ImportTypeMapping(type); } internal void IncludeType(Type knownType) { this.XmlImporter.IncludeType(knownType); } } internal class SerializerGenerationContext { private List<XmlMembersMapping> _mappings = new List<XmlMembersMapping>(); private XmlSerializer[] _serializers = null; private Type _type; private object _thisLock = new object(); internal SerializerGenerationContext(Type type) { _type = type; } // returns a stub to a serializer internal SerializerStub AddSerializer(XmlMembersMapping mapping) { int handle = -1; if (mapping != null) { handle = ((IList)_mappings).Add(mapping); } return new SerializerStub(this, mapping, handle); } internal XmlSerializer GetSerializer(int handle) { if (handle < 0) { return null; } if (_serializers == null) { lock (_thisLock) { if (_serializers == null) { _serializers = GenerateSerializers(); } } } return _serializers[handle]; } private XmlSerializer[] GenerateSerializers() { //this.Mappings may have duplicate mappings (for e.g. same message contract is used by more than one operation) //XmlSerializer.FromMappings require unique mappings. The following code uniquifies, calls FromMappings and deuniquifies List<XmlMembersMapping> uniqueMappings = new List<XmlMembersMapping>(); int[] uniqueIndexes = new int[_mappings.Count]; for (int srcIndex = 0; srcIndex < _mappings.Count; srcIndex++) { XmlMembersMapping mapping = _mappings[srcIndex]; int uniqueIndex = uniqueMappings.IndexOf(mapping); if (uniqueIndex < 0) { uniqueMappings.Add(mapping); uniqueIndex = uniqueMappings.Count - 1; } uniqueIndexes[srcIndex] = uniqueIndex; } XmlSerializer[] uniqueSerializers = CreateSerializersFromMappings(uniqueMappings.ToArray(), _type); if (uniqueMappings.Count == _mappings.Count) return uniqueSerializers; XmlSerializer[] serializers = new XmlSerializer[_mappings.Count]; for (int i = 0; i < _mappings.Count; i++) { serializers[i] = uniqueSerializers[uniqueIndexes[i]]; } return serializers; } [Fx.Tag.SecurityNote(Critical = "XmlSerializer.FromMappings has a LinkDemand.", Safe = "LinkDemand is spurious, not protecting anything in particular.")] [SecuritySafeCritical] private XmlSerializer[] CreateSerializersFromMappings(XmlMapping[] mappings, Type type) { return XmlSerializerHelper.FromMappings(mappings, type); } } internal struct SerializerStub { private readonly SerializerGenerationContext _context; internal readonly XmlMembersMapping Mapping; internal readonly int Handle; internal SerializerStub(SerializerGenerationContext context, XmlMembersMapping mapping, int handle) { _context = context; this.Mapping = mapping; this.Handle = handle; } internal XmlSerializer GetSerializer() { return _context.GetSerializer(Handle); } } internal class XmlSerializerFaultContractInfo { private FaultContractInfo _faultContractInfo; private SerializerStub _serializerStub; private XmlQualifiedName _faultContractElementName; private XmlSerializerObjectSerializer _serializer; internal XmlSerializerFaultContractInfo(FaultContractInfo faultContractInfo, SerializerStub serializerStub, XmlQualifiedName faultContractElementName) { if (faultContractInfo == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("faultContractInfo"); } if (faultContractElementName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("faultContractElementName"); } _faultContractInfo = faultContractInfo; _serializerStub = serializerStub; _faultContractElementName = faultContractElementName; } internal FaultContractInfo FaultContractInfo { get { return _faultContractInfo; } } internal XmlQualifiedName FaultContractElementName { get { return _faultContractElementName; } } internal XmlSerializerObjectSerializer Serializer { get { if (_serializer == null) _serializer = new XmlSerializerObjectSerializer(_faultContractInfo.Detail, _faultContractElementName, _serializerStub.GetSerializer()); return _serializer; } } } internal class MessageInfo : XmlSerializerOperationFormatter.MessageInfo { private SerializerStub _headers; private SerializerStub _body; private OperationFormatter.MessageHeaderDescriptionTable _headerDescriptionTable; private MessageHeaderDescription _unknownHeaderDescription; private MessagePartDescriptionCollection _rpcEncodedTypedMessageBodyParts; internal XmlMembersMapping BodyMapping { get { return _body.Mapping; } } internal override XmlSerializer BodySerializer { get { return _body.GetSerializer(); } } internal XmlMembersMapping HeadersMapping { get { return _headers.Mapping; } } internal override XmlSerializer HeaderSerializer { get { return _headers.GetSerializer(); } } internal override OperationFormatter.MessageHeaderDescriptionTable HeaderDescriptionTable { get { return _headerDescriptionTable; } } internal override MessageHeaderDescription UnknownHeaderDescription { get { return _unknownHeaderDescription; } } internal override MessagePartDescriptionCollection RpcEncodedTypedMessageBodyParts { get { return _rpcEncodedTypedMessageBodyParts; } } internal void SetBody(SerializerStub body, MessagePartDescriptionCollection rpcEncodedTypedMessageBodyParts) { _body = body; _rpcEncodedTypedMessageBodyParts = rpcEncodedTypedMessageBodyParts; } internal void SetHeaders(SerializerStub headers) { _headers = headers; } internal void SetHeaderDescriptionTable(OperationFormatter.MessageHeaderDescriptionTable headerDescriptionTable) { _headerDescriptionTable = headerDescriptionTable; } internal void SetUnknownHeaderDescription(MessageHeaderDescription unknownHeaderDescription) { _unknownHeaderDescription = unknownHeaderDescription; } } } } internal static class XmlSerializerHelper { static internal XmlReflectionMember GetXmlReflectionMember(MessagePartDescription part, bool isRpc, bool isWrapped) { string ns = isRpc ? null : part.Namespace; MemberInfo additionalAttributesProvider = null; if (part.AdditionalAttributesProvider.MemberInfo != null) additionalAttributesProvider = part.AdditionalAttributesProvider.MemberInfo; XmlName memberName = string.IsNullOrEmpty(part.UniquePartName) ? null : new XmlName(part.UniquePartName, true /*isEncoded*/); XmlName elementName = part.XmlName; return GetXmlReflectionMember(memberName, elementName, ns, part.Type, additionalAttributesProvider, part.Multiple, isWrapped); } static internal XmlReflectionMember GetXmlReflectionMember(XmlName memberName, XmlName elementName, string ns, Type type, MemberInfo additionalAttributesProvider, bool isMultiple, bool isWrapped) { XmlReflectionMember member = new XmlReflectionMember(); member.MemberName = (memberName ?? elementName).DecodedName; member.MemberType = type; if (member.MemberType.IsByRef) member.MemberType = member.MemberType.GetElementType(); if (isMultiple) member.MemberType = member.MemberType.MakeArrayType(); if (additionalAttributesProvider != null) { member.XmlAttributes = XmlAttributesHelper.CreateXmlAttributes(additionalAttributesProvider); } if (member.XmlAttributes == null) member.XmlAttributes = new XmlAttributes(); else { Type invalidAttributeType = null; if (member.XmlAttributes.XmlAttribute != null) invalidAttributeType = typeof(XmlAttributeAttribute); else if (member.XmlAttributes.XmlAnyAttribute != null && !isWrapped) invalidAttributeType = typeof(XmlAnyAttributeAttribute); else if (member.XmlAttributes.XmlChoiceIdentifier != null) invalidAttributeType = typeof(XmlChoiceIdentifierAttribute); else if (member.XmlAttributes.XmlIgnore) invalidAttributeType = typeof(XmlIgnoreAttribute); else if (member.XmlAttributes.Xmlns) invalidAttributeType = typeof(XmlNamespaceDeclarationsAttribute); else if (member.XmlAttributes.XmlText != null) invalidAttributeType = typeof(XmlTextAttribute); else if (member.XmlAttributes.XmlEnum != null) invalidAttributeType = typeof(XmlEnumAttribute); if (invalidAttributeType != null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(isWrapped ? SR.SFxInvalidXmlAttributeInWrapped : SR.SFxInvalidXmlAttributeInBare, invalidAttributeType, elementName.DecodedName))); if (member.XmlAttributes.XmlArray != null && isMultiple) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxXmlArrayNotAllowedForMultiple, elementName.DecodedName, ns))); } bool isArray = member.MemberType.IsArray; if ((isArray && !isMultiple && member.MemberType != typeof(byte[])) || (!isArray && typeof(IEnumerable).IsAssignableFrom(member.MemberType) && member.MemberType != typeof(string) && !typeof(XmlNode).IsAssignableFrom(member.MemberType) && !typeof(IXmlSerializable).IsAssignableFrom(member.MemberType))) { if (member.XmlAttributes.XmlArray != null) { if (member.XmlAttributes.XmlArray.ElementName == String.Empty) member.XmlAttributes.XmlArray.ElementName = elementName.DecodedName; if (member.XmlAttributes.XmlArray.Namespace == null) member.XmlAttributes.XmlArray.Namespace = ns; } else if (HasNoXmlParameterAttributes(member.XmlAttributes)) { member.XmlAttributes.XmlArray = new XmlArrayAttribute(); member.XmlAttributes.XmlArray.ElementName = elementName.DecodedName; member.XmlAttributes.XmlArray.Namespace = ns; } } else { if (member.XmlAttributes.XmlElements == null || member.XmlAttributes.XmlElements.Count == 0) { if (HasNoXmlParameterAttributes(member.XmlAttributes)) { XmlElementAttribute elementAttribute = new XmlElementAttribute(); elementAttribute.ElementName = elementName.DecodedName; elementAttribute.Namespace = ns; member.XmlAttributes.XmlElements.Add(elementAttribute); } } else { foreach (XmlElementAttribute elementAttribute in member.XmlAttributes.XmlElements) { if (elementAttribute.ElementName == String.Empty) elementAttribute.ElementName = elementName.DecodedName; if (elementAttribute.Namespace == null) elementAttribute.Namespace = ns; } } } return member; } private static bool HasNoXmlParameterAttributes(XmlAttributes xmlAttributes) { return xmlAttributes.XmlAnyAttribute == null && (xmlAttributes.XmlAnyElements == null || xmlAttributes.XmlAnyElements.Count == 0) && xmlAttributes.XmlArray == null && xmlAttributes.XmlAttribute == null && !xmlAttributes.XmlIgnore && xmlAttributes.XmlText == null && xmlAttributes.XmlChoiceIdentifier == null && (xmlAttributes.XmlElements == null || xmlAttributes.XmlElements.Count == 0) && !xmlAttributes.Xmlns; } public static XmlSerializer[] FromMappings(XmlMapping[] mappings, Type type) { #if FEATURE_NETNATIVE if (GeneratedXmlSerializers.IsInitialized) { return FromMappingsViaInjection(mappings, type); } #endif return FromMappingsViaReflection(mappings, type); } private static XmlSerializer[] FromMappingsViaReflection(XmlMapping[] mappings, Type type) { if (mappings == null || mappings.Length == 0) { return new XmlSerializer[0]; } Array mappingArray = XmlMappingTypesHelper.InitializeArray(XmlMappingTypesHelper.XmlMappingType, mappings); MethodInfo method = typeof(XmlSerializer).GetMethod("FromMappings", new Type[] { XmlMappingTypesHelper.XmlMappingType.MakeArrayType(), typeof(Type) }); object result = method.Invoke(null, new object[] { mappingArray, type }); return (XmlSerializer[])result; } #if FEATURE_NETNATIVE private static XmlSerializer[] FromMappingsViaInjection(XmlMapping[] mappings, Type type) { XmlSerializer[] serializers = new XmlSerializer[mappings.Length]; for (int i = 0; i < serializers.Length; i++) { Type t; GeneratedXmlSerializers.GetGeneratedSerializers().TryGetValue(mappings[i].Key, out t); if (t == null) { throw new InvalidOperationException(SR.Format(SR.SFxXmlSerializerIsNotFound, type)); } serializers[i] = new XmlSerializer(t); } return serializers; } #endif } }
// 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.Build.Framework; using Microsoft.Build.Utilities; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Newtonsoft.Json.Linq; using Newtonsoft.Json; using System.Security.Cryptography; using System.Reflection.PortableExecutable; using System.Reflection.Metadata; namespace Microsoft.DotNet.Build.Tasks { /// <summary> /// Resolves the assets out of packages in the project.lock.json /// </summary> public sealed class PrereleaseResolveNuGetPackageAssets : Task { internal const string NuGetPackageIdMetadata = "NuGetPackageId"; internal const string NuGetPackageVersionMetadata = "NuGetPackageVersion"; internal const string NuGetIsFrameworkReference = "NuGetIsFrameworkReference"; internal const string NuGetSourceType = "NuGetSourceType"; internal const string NuGetSourceType_Project = "Project"; internal const string NuGetSourceType_Package = "Package"; internal const string ReferenceImplementationMetadata = "Implementation"; internal const string ReferenceImageRuntimeMetadata = "ImageRuntime"; internal const string ReferenceWinMDFileMetadata = "WinMDFile"; internal const string ReferenceWinMDFileTypeMetadata = "WinMDFileType"; internal const string WinMDFileTypeManaged = "Managed"; internal const string WinMDFileTypeNative = "Native"; internal const string NuGetAssetTypeCompile = "compile"; internal const string NuGetAssetTypeNative = "native"; internal const string NuGetAssetTypeRuntime = "runtime"; internal const string NuGetAssetTypeResource = "resource"; private readonly List<ITaskItem> _analyzers = new List<ITaskItem>(); private readonly List<ITaskItem> _copyLocalItems = new List<ITaskItem>(); private readonly List<ITaskItem> _references = new List<ITaskItem>(); private readonly List<ITaskItem> _referencedPackages = new List<ITaskItem>(); private readonly List<ITaskItem> _contentItems = new List<ITaskItem>(); private readonly List<ITaskItem> _fileWrites = new List<ITaskItem>(); private readonly List<string> _packageFolders = new List<string>(); private readonly Dictionary<string, string> _projectReferencesToOutputBasePaths = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); #region UnitTestSupport private readonly DirectoryExists _directoryExists = new DirectoryExists(Directory.Exists); private readonly FileExists _fileExists = new FileExists(File.Exists); private readonly TryGetRuntimeVersion _tryGetRuntimeVersion = new TryGetRuntimeVersion(TryGetRuntimeVersion); private readonly bool _reportExceptionsToMSBuildLogger = true; internal PrereleaseResolveNuGetPackageAssets(DirectoryExists directoryExists, FileExists fileExists, TryGetRuntimeVersion tryGetRuntimeVersion) : this() { if (directoryExists != null) { _directoryExists = directoryExists; } if (fileExists != null) { _fileExists = fileExists; } if (tryGetRuntimeVersion != null) { _tryGetRuntimeVersion = tryGetRuntimeVersion; } _reportExceptionsToMSBuildLogger = false; } // For unit testing. internal IEnumerable<string> GetPackageFolders() { return _packageFolders; } #endregion /// <summary> /// Creates a new <see cref="PrereleaseResolveNuGetPackageAssets"/>. /// </summary> public PrereleaseResolveNuGetPackageAssets() { Log.TaskResources = Strings.ResourceManager; } /// <summary> /// The full paths to resolved analyzers. /// </summary> [Output] public ITaskItem[] ResolvedAnalyzers { get { return _analyzers.ToArray(); } } /// <summary> /// The full paths to resolved run-time resources. /// </summary> [Output] public ITaskItem[] ResolvedCopyLocalItems { get { return _copyLocalItems.ToArray(); } } /// <summary> /// The full paths to resolved build-time dependencies. Contains standard metadata for Reference items. /// </summary> [Output] public ITaskItem[] ResolvedReferences { get { return _references.ToArray(); } } /// <summary> /// The names of NuGet packages directly referenced by this project. /// </summary> [Output] public ITaskItem[] ReferencedPackages { get { return _referencedPackages.ToArray(); } } /// <summary> /// Additional content items provided from NuGet packages. /// </summary> [Output] public ITaskItem[] ContentItems => _contentItems.ToArray(); /// <summary> /// Files written to during the generation process. /// </summary> [Output] public ITaskItem[] FileWrites => _fileWrites.ToArray(); /// <summary> /// Items specifying the tokens that can be substituted into preprocessed content files. The ItemSpec of each item is /// the name of the token, without the surrounding $$, and the Value metadata should specify the replacement value. /// </summary> public ITaskItem[] ContentPreprocessorValues { get; set; } /// <summary> /// A list of project references that are creating packages as listed in the lock file. The OutputPath metadata should /// set on each of these items, which is used by the task to construct full output paths to assets. /// </summary> public ITaskItem[] ProjectReferencesCreatingPackages { get; set; } /// <summary> /// The base output directory where the temporary, preprocessed files should be written to. /// </summary> public string ContentPreprocessorOutputDirectory { get; set; } /// <summary> /// The target monikers to use when selecting assets from packages. The first one found in the lock file is used. /// </summary> [Required] public ITaskItem[] TargetMonikers { get; set; } [Required] public string ProjectLockFile { get; set; } public string NuGetPackagesDirectory { get; set; } public string RuntimeIdentifier { get; set; } public bool AllowFallbackOnTargetSelection { get; set; } public string ProjectLanguage { get; set; } public bool IncludeFrameworkReferences { get; set; } /// <summary> /// Performs the NuGet package resolution. /// </summary> public override bool Execute() { try { ExecuteCore(); return true; } catch (ExceptionFromResource e) when (_reportExceptionsToMSBuildLogger) { Log.LogErrorFromResources(e.ResourceName, e.MessageArgs); return false; } catch (Exception e) when (_reportExceptionsToMSBuildLogger) { // Any user-visible exceptions we throw should be ExceptionFromResource, so here we should dump stacks because // something went very wrong. Log.LogErrorFromException(e, showStackTrace: true); return false; } } private void ExecuteCore() { if (!_fileExists(ProjectLockFile)) { throw new ExceptionFromResource(nameof(Strings.LockFileNotFound), ProjectLockFile); } JObject lockFile; using (var streamReader = new StreamReader(new FileStream(ProjectLockFile, FileMode.Open, FileAccess.Read, FileShare.Read))) { lockFile = JObject.Load(new JsonTextReader(streamReader)); } PopulatePackageFolders(lockFile); PopulateProjectReferenceMaps(); GetReferences(lockFile); GetCopyLocalItems(lockFile); GetAnalyzers(lockFile); GetReferencedPackages(lockFile); ProduceContentAssets(lockFile); } private void PopulatePackageFolders(JObject lockFile) { // If we explicitly were given a path, let's use that if (!string.IsNullOrEmpty(NuGetPackagesDirectory)) { _packageFolders.Add(NuGetPackagesDirectory); } // Newer versions of NuGet can now specify the final list of locations in the lock file var packageFolders = lockFile["packageFolders"] as JObject; if (packageFolders != null) { foreach (var packageFolder in packageFolders.Properties()) { _packageFolders.Add(packageFolder.Name); } } } private void PopulateProjectReferenceMaps() { foreach (var projectReference in ProjectReferencesCreatingPackages ?? new ITaskItem[] { }) { var fullPath = GetAbsolutePathFromProjectRelativePath(projectReference.ItemSpec); if (_projectReferencesToOutputBasePaths.ContainsKey(fullPath)) { Log.LogWarningFromResources(nameof(Strings.DuplicateProjectReference), fullPath, nameof(ProjectReferencesCreatingPackages)); } else { var outputPath = projectReference.GetMetadata("OutputBasePath"); _projectReferencesToOutputBasePaths.Add(fullPath, outputPath); } } } private void GetReferences(JObject lockFile) { var target = GetTargetOrAttemptFallback(lockFile, needsRuntimeIdentifier: false); var frameworkReferences = new HashSet<string>(StringComparer.OrdinalIgnoreCase); var fileNamesOfRegularReferences = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (var package in GetPackagesFromTarget(lockFile, target)) { foreach (var referenceItem in CreateItems(package, NuGetAssetTypeCompile, includePdbs: false)) { _references.Add(referenceItem); fileNamesOfRegularReferences.Add(Path.GetFileNameWithoutExtension(referenceItem.ItemSpec)); } if (IncludeFrameworkReferences) { var frameworkAssembliesArray = package.TargetObject["frameworkAssemblies"] as JArray; if (frameworkAssembliesArray != null) { foreach (var frameworkAssembly in frameworkAssembliesArray.OfType<JToken>()) { frameworkReferences.Add((string)frameworkAssembly); } } } } foreach (var frameworkReference in frameworkReferences.Except(fileNamesOfRegularReferences, StringComparer.OrdinalIgnoreCase)) { var item = new TaskItem(frameworkReference); item.SetMetadata(NuGetIsFrameworkReference, "true"); item.SetMetadata(NuGetSourceType, NuGetSourceType_Package); _references.Add(item); } } private void GetCopyLocalItems(JObject lockFile) { // If we have no runtime identifier, we're not copying implementations if (string.IsNullOrEmpty(RuntimeIdentifier)) { return; } // We'll use as a fallback just the target moniker if the user didn't have the right runtime identifier in their lock file. var target = GetTargetOrAttemptFallback(lockFile, needsRuntimeIdentifier: true); HashSet<string> candidateNativeImplementations = new HashSet<string>(StringComparer.OrdinalIgnoreCase); List<ITaskItem> runtimeWinMDItems = new List<ITaskItem>(); foreach (var package in GetPackagesFromTarget(lockFile, target)) { foreach (var nativeItem in CreateItems(package, NuGetAssetTypeNative)) { if (Path.GetExtension(nativeItem.ItemSpec).Equals(".dll", StringComparison.OrdinalIgnoreCase)) { candidateNativeImplementations.Add(Path.GetFileNameWithoutExtension(nativeItem.ItemSpec)); } _copyLocalItems.Add(nativeItem); } foreach (var runtimeItem in CreateItems(package, NuGetAssetTypeRuntime)) { if (Path.GetExtension(runtimeItem.ItemSpec).Equals(".winmd", StringComparison.OrdinalIgnoreCase)) { runtimeWinMDItems.Add(runtimeItem); } _copyLocalItems.Add(runtimeItem); } foreach (var resourceItem in CreateItems(package, NuGetAssetTypeResource)) { _copyLocalItems.Add(resourceItem); } } SetWinMDMetadata(runtimeWinMDItems, candidateNativeImplementations); } private void GetAnalyzers(JObject lockFile) { // For analyzers, analyzers could be provided in runtime implementation packages. This might be reasonable -- imagine a gatekeeper // scenario where somebody has a library but on .NET Native might have some specific restrictions that need to be enforced. var target = GetTargetOrAttemptFallback(lockFile, needsRuntimeIdentifier: !string.IsNullOrEmpty(RuntimeIdentifier)); foreach (var package in GetPackagesFromTarget(lockFile, target)) { var files = package.LibraryObject["files"]; if (files != null) { foreach (var file in files.Children() .Select(x => x.ToString()) .Where(x => x.StartsWith("analyzers"))) { if (Path.GetExtension(file).Equals(".dll", StringComparison.OrdinalIgnoreCase)) { string path; if (TryGetFile(package.Id, package.Version, file, out path)) { var analyzer = new TaskItem(path); analyzer.SetMetadata(NuGetPackageIdMetadata, package.Id); analyzer.SetMetadata(NuGetPackageVersionMetadata, package.Version); _analyzers.Add(analyzer); } } } } } } private void SetWinMDMetadata(IEnumerable<ITaskItem> runtimeWinMDs, ICollection<string> candidateImplementations) { foreach (var winMD in runtimeWinMDs.Where(w => _fileExists(w.ItemSpec))) { string imageRuntimeVersion = _tryGetRuntimeVersion(winMD.ItemSpec); if (String.IsNullOrEmpty(imageRuntimeVersion)) continue; // RAR sets ImageRuntime for everything but the only dependencies we're aware of are // for WinMDs winMD.SetMetadata(ReferenceImageRuntimeMetadata, imageRuntimeVersion); bool isWinMD, isManaged; TryParseRuntimeVersion(imageRuntimeVersion, out isWinMD, out isManaged); if (isWinMD) { winMD.SetMetadata(ReferenceWinMDFileMetadata, "true"); if (isManaged) { winMD.SetMetadata(ReferenceWinMDFileTypeMetadata, WinMDFileTypeManaged); } else { winMD.SetMetadata(ReferenceWinMDFileTypeMetadata, WinMDFileTypeNative); // Normally RAR will expect the native DLL to be next to the WinMD, but that doesn't // work well for nuget packages since compile time assets cannot be architecture specific. // We also explicitly set all compile time assets to not copy local so we need to // make sure that this metadata is set on the runtime asset. // Examine all runtime assets that are native winmds and add Implementation metadata // We intentionally permit this to cross package boundaries to support cases where // folks want to split their architecture specific implementations into runtime // specific packages. // Sample layout // lib\netcore50\Contoso.Controls.winmd // lib\netcore50\Contoso.Controls.xml // runtimes\win10-arm\native\Contoso.Controls.dll // runtimes\win10-x64\native\Contoso.Controls.dll // runtimes\win10-x86\native\Contoso.Controls.dll string fileName = Path.GetFileNameWithoutExtension(winMD.ItemSpec); // determine if we have a Native WinMD that could be satisfied by this native dll. if (candidateImplementations.Contains(fileName)) { winMD.SetMetadata(ReferenceImplementationMetadata, fileName + ".dll"); } } } } } private bool TryGetFile(string packageName, string packageVersion, string file, out string path) { if (IsFileValid(file, "C#", "VB")) { path = GetPath(packageName, packageVersion, file); return true; } else if (IsFileValid(file, "VB", "C#")) { path = GetPath(packageName, packageVersion, file); return true; } path = null; return false; } private bool IsFileValid(string file, string expectedLanguage, string unExpectedLanguage) { var expectedProjectLanguage = expectedLanguage; expectedLanguage = expectedLanguage == "C#" ? "cs" : expectedLanguage; unExpectedLanguage = unExpectedLanguage == "C#" ? "cs" : unExpectedLanguage; return (ProjectLanguage.Equals(expectedProjectLanguage, StringComparison.OrdinalIgnoreCase)) && (file.Split('/').Any(x => x.Equals(ProjectLanguage, StringComparison.OrdinalIgnoreCase)) || !file.Split('/').Any(x => x.Equals(unExpectedLanguage, StringComparison.OrdinalIgnoreCase))); } private string GetPath(string packageName, string packageVersion, string file) { return Path.Combine(GetNuGetPackagePath(packageName, packageVersion), file.Replace('/', '\\')); } /// <summary> /// Produces a string hash of the key/values in the dictionary. This hash is used to put all the /// preprocessed files into a folder with the name so we know to regenerate when any of the /// inputs change. /// </summary> private string BuildPreprocessedContentHash(IReadOnlyDictionary<string, string> values) { using (var stream = new MemoryStream()) { using (var streamWriter = new StreamWriter(stream, Encoding.UTF8, bufferSize: 4096, leaveOpen: true)) { foreach (var pair in values.OrderBy(v => v.Key)) { streamWriter.Write(pair.Key); streamWriter.Write('\0'); streamWriter.Write(pair.Value); streamWriter.Write('\0'); } } stream.Position = 0; return SHA1.Create().ComputeHash(stream).Aggregate("", (s, b) => s + b.ToString("x2")); } } private void ProduceContentAssets(JObject lockFile) { string valueSpecificPreprocessedOutputDirectory = null; var preprocessorValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); // If a preprocessor directory isn't set, then we won't have a place to generate. if (!string.IsNullOrEmpty(ContentPreprocessorOutputDirectory)) { // Assemble the preprocessor values up-front var duplicatedPreprocessorKeys = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (var preprocessorValueItem in ContentPreprocessorValues ?? Enumerable.Empty<ITaskItem>()) { if (preprocessorValues.ContainsKey(preprocessorValueItem.ItemSpec)) { duplicatedPreprocessorKeys.Add(preprocessorValueItem.ItemSpec); } preprocessorValues[preprocessorValueItem.ItemSpec] = preprocessorValueItem.GetMetadata("Value"); } foreach (var duplicatedPreprocessorKey in duplicatedPreprocessorKeys) { Log.LogWarningFromResources(nameof(Strings.DuplicatePreprocessorToken), duplicatedPreprocessorKey, preprocessorValues[duplicatedPreprocessorKey]); } valueSpecificPreprocessedOutputDirectory = Path.Combine(ContentPreprocessorOutputDirectory, BuildPreprocessedContentHash(preprocessorValues)); } // For shared content, it does not depend upon the RID so we should ignore it var target = GetTargetOrAttemptFallback(lockFile, needsRuntimeIdentifier: false); foreach (var package in GetPackagesFromTarget(lockFile, target)) { var contentFiles = package.TargetObject["contentFiles"] as JObject; if (contentFiles != null) { // Is there an asset with our exact language? If so, we use that. Otherwise we'll simply collect "any" assets. string codeLanguageToSelect; if (string.IsNullOrEmpty(ProjectLanguage)) { codeLanguageToSelect = "any"; } else { string nuGetLanguageName = GetNuGetLanguageName(ProjectLanguage); if (contentFiles.Properties().Any(a => (string)a.Value["codeLanguage"] == nuGetLanguageName)) { codeLanguageToSelect = nuGetLanguageName; } else { codeLanguageToSelect = "any"; } } foreach (var contentFile in contentFiles.Properties()) { // Ignore magic _._ placeholder files. We couldn't ignore them during the project language // selection, since you could imagine somebody might have a package that puts assets under // "any" but then uses _._ to opt some languages out of it if (Path.GetFileName(contentFile.Name) != "_._") { if ((string)contentFile.Value["codeLanguage"] == codeLanguageToSelect) { ProduceContentAsset(package, contentFile, preprocessorValues, valueSpecificPreprocessedOutputDirectory); } } } } } } private static string GetNuGetLanguageName(string projectLanguage) { switch (projectLanguage) { case "C#": return "cs"; case "F#": return "fs"; default: return projectLanguage.ToLowerInvariant(); } } /// <summary> /// Produces the asset for a single shared asset. All applicablility checks have already been completed. /// </summary> private void ProduceContentAsset(NuGetPackageObject package, JProperty sharedAsset, IReadOnlyDictionary<string, string> preprocessorValues, string preprocessedOutputDirectory) { string pathToFinalAsset = package.GetFullPathToFile(sharedAsset.Name); if (sharedAsset.Value["ppOutputPath"] != null) { if (preprocessedOutputDirectory == null) { throw new ExceptionFromResource(nameof(Strings.PreprocessedDirectoryNotSet), nameof(ContentPreprocessorOutputDirectory)); } // We need the preprocessed output, so let's run the preprocessor here pathToFinalAsset = Path.Combine(preprocessedOutputDirectory, package.Id, package.Version, (string)sharedAsset.Value["ppOutputPath"]); if (!File.Exists(pathToFinalAsset)) { Directory.CreateDirectory(Path.GetDirectoryName(pathToFinalAsset)); using (var input = new StreamReader(new FileStream(package.GetFullPathToFile(sharedAsset.Name), FileMode.Open, FileAccess.Read, FileShare.Read), detectEncodingFromByteOrderMarks: true)) using (var output = new StreamWriter(new FileStream(pathToFinalAsset, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write), encoding: input.CurrentEncoding)) { Preprocessor.Preprocess(input, output, preprocessorValues); } _fileWrites.Add(new TaskItem(pathToFinalAsset)); } } if ((bool)sharedAsset.Value["copyToOutput"]) { string outputPath = (string)sharedAsset.Value["outputPath"] ?? (string)sharedAsset.Value["ppOutputPath"]; if (outputPath != null) { var item = CreateItem(package, pathToFinalAsset, targetPath: outputPath); _copyLocalItems.Add(item); } } string buildAction = (string)sharedAsset.Value["buildAction"]; if (!string.Equals(buildAction, "none", StringComparison.OrdinalIgnoreCase)) { var item = CreateItem(package, pathToFinalAsset); // We'll put additional metadata on the item so we can convert it back to the real item group in our targets item.SetMetadata("NuGetItemType", buildAction); // If this is XAML, the build targets expect Link metadata to construct the relative path if (string.Equals(buildAction, "Page", StringComparison.OrdinalIgnoreCase)) { item.SetMetadata("Link", Path.Combine("NuGet", package.Id, package.Version, Path.GetFileName(sharedAsset.Name))); } _contentItems.Add(item); } } /// <summary> /// Fetches the right target from the targets section in a lock file, or attempts to find a "best match" if allowed. The "best match" logic /// is there to allow a design time build for the IDE to generally work even if something isn't quite right. Throws an exception /// if either the preferred isn't there and fallbacks aren't allowed, or fallbacks are allowed but nothing at all could be found. /// </summary> /// <param name="lockFile">The lock file JSON.</param> /// <param name="needsRuntimeIdentifier">Whether we must find targets that include the runtime identifier or one without the runtime identifier.</param> private JObject GetTargetOrAttemptFallback(JObject lockFile, bool needsRuntimeIdentifier) { var targets = (JObject)lockFile["targets"]; foreach (var preferredTargetMoniker in TargetMonikers) { var preferredTargetMonikerWithOptionalRuntimeIdentifier = GetTargetMonikerWithOptionalRuntimeIdentifier(preferredTargetMoniker, needsRuntimeIdentifier); var target = (JObject)targets[preferredTargetMonikerWithOptionalRuntimeIdentifier]; if (target != null) { return target; } } // If we need a runtime identifier, let's see if we have the framework targeted. If we do, // then we can give a better error message. bool onlyNeedsRuntimeInProjectJson = false; if (needsRuntimeIdentifier) { foreach (var targetMoniker in TargetMonikers) { var targetMonikerWithoutRuntimeIdentifier = GetTargetMonikerWithOptionalRuntimeIdentifier(targetMoniker, needsRuntimeIdentifier: false); if (targets[targetMonikerWithoutRuntimeIdentifier] != null) { // We do have a TXM being targeted, so we just are missing the runtime onlyNeedsRuntimeInProjectJson = true; break; } } } if (onlyNeedsRuntimeInProjectJson) { GiveErrorForMissingRuntimeIdentifier(); } else { ThrowExceptionIfNotAllowingFallback(nameof(Strings.MissingFramework), TargetMonikers.First().ItemSpec); } // If we're still here, that means we're allowing fallback, so let's try foreach (var fallback in TargetMonikers) { var target = (JObject)targets[GetTargetMonikerWithOptionalRuntimeIdentifier(fallback, needsRuntimeIdentifier: false)]; if (target != null) { return target; } } // Anything goes var enumerableTargets = targets.Cast<KeyValuePair<string, JToken>>(); var firstTarget = (JObject)enumerableTargets.FirstOrDefault().Value; if (firstTarget == null) { throw new ExceptionFromResource(nameof(Strings.NoTargetsInLockFile)); } return firstTarget; } private void GiveErrorForMissingRuntimeIdentifier() { string runtimePiece = '"' + RuntimeIdentifier + "\": { }"; bool hasRuntimesSection; try { using (var streamReader = new StreamReader(new FileStream(ProjectLockFile.Replace(".lock.json", ".json"), FileMode.Open, FileAccess.Read, FileShare.Read))) { var jsonFile = JObject.Load(new JsonTextReader(streamReader)); hasRuntimesSection = jsonFile["runtimes"] != null; } } catch { // User has a bad file, locked file, no file at all, etc. We'll just assume they have one. hasRuntimesSection = true; } if (hasRuntimesSection) { ThrowExceptionIfNotAllowingFallback(nameof(Strings.MissingRuntimeInRuntimesSection), RuntimeIdentifier, runtimePiece); } else { var runtimesSection = "\"runtimes\": { " + runtimePiece + " }"; ThrowExceptionIfNotAllowingFallback(nameof(Strings.MissingRuntimesSection), runtimesSection); } } private void ThrowExceptionIfNotAllowingFallback(string resourceName, params string[] messageArgs) { if (!AllowFallbackOnTargetSelection) { throw new ExceptionFromResource(resourceName, messageArgs); } else { // We are allowing fallback, so we'll still give a warning but allow us to continue Log.LogWarningFromResources(resourceName, messageArgs); } } private string GetTargetMonikerWithOptionalRuntimeIdentifier(ITaskItem preferredTargetMoniker, bool needsRuntimeIdentifier) { return needsRuntimeIdentifier ? preferredTargetMoniker.ItemSpec + "/" + RuntimeIdentifier : preferredTargetMoniker.ItemSpec; } private IEnumerable<ITaskItem> CreateItems(NuGetPackageObject package, string key, bool includePdbs = true) { var values = package.TargetObject[key] as JObject; var items = new List<ITaskItem>(); if (values == null) { return items; } foreach (var file in values.Properties()) { if (Path.GetFileName(file.Name) == "_._") { continue; } string targetPath = null; string culture = file.Value["locale"]?.ToString(); if (culture != null) { targetPath = Path.Combine(culture, Path.GetFileName(file.Name)); } var item = CreateItem(package, package.GetFullPathToFile(file.Name), targetPath); item.SetMetadata("Private", "false"); item.SetMetadata(NuGetIsFrameworkReference, "false"); item.SetMetadata(NuGetSourceType, package.IsProject ? NuGetSourceType_Project : NuGetSourceType_Package); items.Add(item); // If there's a PDB alongside the implementation, we should copy that as well if (includePdbs) { var pdbFileName = Path.ChangeExtension(item.ItemSpec, ".pdb"); if (_fileExists(pdbFileName)) { var pdbItem = new TaskItem(pdbFileName); // CopyMetadataTo also includes an OriginalItemSpec that will point to our original item, as we want item.CopyMetadataTo(pdbItem); items.Add(pdbItem); } } } return items; } private static ITaskItem CreateItem(NuGetPackageObject package, string itemSpec, string targetPath = null) { var item = new TaskItem(itemSpec); item.SetMetadata(NuGetPackageIdMetadata, package.Id); item.SetMetadata(NuGetPackageVersionMetadata, package.Version); if (targetPath != null) { item.SetMetadata("TargetPath", targetPath); var destinationSubDirectory = Path.GetDirectoryName(targetPath); if (!string.IsNullOrEmpty(destinationSubDirectory)) { item.SetMetadata("DestinationSubDirectory", destinationSubDirectory + "\\"); } } return item; } private void GetReferencedPackages(JObject lockFile) { var projectFileDependencyGroups = (JObject)lockFile["projectFileDependencyGroups"]; // find whichever target we will have selected var actualTarget = GetTargetOrAttemptFallback(lockFile, needsRuntimeIdentifier: false)?.Parent as JProperty; string targetMoniker = null; if (actualTarget != null) { targetMoniker = actualTarget.Name.Split('/').FirstOrDefault(); } foreach (var dependencyGroup in projectFileDependencyGroups.Values<JProperty>()) { if (dependencyGroup.Name.Length == 0 || dependencyGroup.Name == targetMoniker) { foreach (var packageDependency in dependencyGroup.Value.Values<string>()) { int firstSpace = packageDependency.IndexOf(' '); if (firstSpace > -1) { _referencedPackages.Add(new TaskItem(packageDependency.Substring(0, firstSpace))); } } } } } private string GetNuGetPackagePath(string packageId, string packageVersion) { foreach (var packagesFolder in _packageFolders) { string packagePath = Path.Combine(packagesFolder, packageId, packageVersion); if (_directoryExists(packagePath)) { return packagePath; } else { // Try a lower-case path. string lowerCasePath = Path.Combine(packagesFolder, packageId.ToLowerInvariant(), packageVersion.ToLowerInvariant()); if (_directoryExists(lowerCasePath)) { return lowerCasePath; } } } throw new ExceptionFromResource(nameof(Strings.PackageFolderNotFound), packageId, packageVersion, string.Join(", ", _packageFolders)); } private string GetNuGetPackagesPath() { if (!string.IsNullOrEmpty(NuGetPackagesDirectory)) { return NuGetPackagesDirectory; } string packagesFolder = Environment.GetEnvironmentVariable("NUGET_PACKAGES"); if (!string.IsNullOrEmpty(packagesFolder)) { return packagesFolder; } return string.Empty; } private IEnumerable<NuGetPackageObject> GetPackagesFromTarget(JObject lockFile, JObject target) { foreach (var package in target) { var nameParts = package.Key.Split('/'); var id = nameParts[0]; var version = nameParts[1]; bool isProject = false; var libraryObject = (JObject)lockFile["libraries"][package.Key]; Func<string> fullPackagePathGenerator; // If this is a project then we need to figure out it's relative output path if ((string)libraryObject["type"] == "project") { isProject = true; fullPackagePathGenerator = () => { var relativeMSBuildProjectPath = (string)libraryObject["msbuildProject"]; if (string.IsNullOrEmpty(relativeMSBuildProjectPath)) { throw new ExceptionFromResource(nameof(Strings.MissingMSBuildPathInProjectPackage), id); } var absoluteMSBuildProjectPath = GetAbsolutePathFromProjectRelativePath(relativeMSBuildProjectPath); string fullPackagePath; if (!_projectReferencesToOutputBasePaths.TryGetValue(absoluteMSBuildProjectPath, out fullPackagePath)) { throw new ExceptionFromResource(nameof(Strings.MissingProjectReference), absoluteMSBuildProjectPath, nameof(ProjectReferencesCreatingPackages)); } return fullPackagePath; }; } else { fullPackagePathGenerator = () => GetNuGetPackagePath(id, version); } yield return new NuGetPackageObject(id, version, isProject, fullPackagePathGenerator, (JObject)package.Value, libraryObject); } } private string GetAbsolutePathFromProjectRelativePath(string path) { return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(Path.GetFullPath(ProjectLockFile)), path)); } /// <summary> /// Parse the imageRuntimeVersion from COR header /// </summary> private void TryParseRuntimeVersion(string imageRuntimeVersion, out bool isWinMD, out bool isManaged) { if (!String.IsNullOrEmpty(imageRuntimeVersion)) { isWinMD = imageRuntimeVersion.IndexOf("WindowsRuntime", StringComparison.OrdinalIgnoreCase) >= 0; isManaged = imageRuntimeVersion.IndexOf("CLR", StringComparison.OrdinalIgnoreCase) >= 0; } else { isWinMD = isManaged = false; } } /// <summary> /// Given a path get the CLR runtime version of the file /// </summary> /// <param name="path">path to the file</param> /// <returns>The CLR runtime version or empty if the path does not exist.</returns> private static string TryGetRuntimeVersion(string path) { try { using (FileStream stream = File.OpenRead(path)) using (PEReader peReader = new PEReader(stream)) { return peReader.GetMetadataReader().MetadataVersion; } } catch (Exception) { return string.Empty; } } } }
using System; using System.Runtime.InteropServices; using VulkanCore.Khr; namespace VulkanCore.Ext { /// <summary> /// Provides extension methods for the <see cref="PhysicalDevice"/> class. /// </summary> public static unsafe class PhysicalDeviceExtensions { /// <summary> /// Query surface capabilities. /// </summary> /// <param name="physicalDevice"> /// The physical device that will be associated with the swapchain to be created, as /// described for <see cref="Khr.DeviceExtensions.CreateSwapchainKhr"/>. /// </param> /// <param name="surface">The surface that will be associated with the swapchain.</param> /// <returns>The structure in which the capabilities are returned.</returns> /// <exception cref="VulkanException">Vulkan returns an error code.</exception> public static SurfaceCapabilities2Ext GetSurfaceCapabilities2Ext(this PhysicalDevice physicalDevice, SurfaceKhr surface) { SurfaceCapabilities2Ext capabilities; Result result = vkGetPhysicalDeviceSurfaceCapabilities2EXT(physicalDevice)(physicalDevice, surface, &capabilities); VulkanException.ThrowForInvalidResult(result); return capabilities; } /// <summary> /// Query the <see cref="DisplayKhr"/> corresponding to an X11 RandR Output. /// <para> /// When acquiring displays from an X11 server, an application may also wish to enumerate and /// identify them using a native handle rather than a <see cref="DisplayKhr"/> handle. /// </para> /// </summary> /// <param name="physicalDevice">The physical device to query the display handle on.</param> /// <param name="dpy">A connection to the X11 server from which <paramref name="rrOutput"/> was queried.</param> /// <param name="rrOutput">An X11 RandR output ID.</param> /// <returns>The corresponding <see cref="DisplayKhr"/> handle.</returns> /// <exception cref="VulkanException">Vulkan returns an error code.</exception> public static DisplayKhr GetRandROutputDisplayExt(this PhysicalDevice physicalDevice, IntPtr dpy, IntPtr rrOutput) { long handle; Result result = vkGetRandROutputDisplayEXT(physicalDevice)(physicalDevice, &dpy, rrOutput, &handle); VulkanException.ThrowForInvalidResult(result); return new DisplayKhr(physicalDevice, handle); } /// <summary> /// Report sample count specific multisampling capabilities of a physical device. /// </summary> /// <param name="physicalDevice"> /// The physical device from which to query the additional multisampling capabilities. /// </param> /// <param name="samples">The sample count to query the capabilities for.</param> /// <returns> /// A structure in which information about the additional multisampling capabilities specific /// to the sample count is returned. /// </returns> public static MultisamplePropertiesExt GetMultisamplePropertiesExt(this PhysicalDevice physicalDevice, SampleCounts samples) { MultisamplePropertiesExt properties; vkGetPhysicalDeviceMultisamplePropertiesEXT(physicalDevice)(physicalDevice, samples, &properties); return properties; } private delegate Result vkGetPhysicalDeviceSurfaceCapabilities2EXTDelegate(IntPtr physicalDevice, long surface, SurfaceCapabilities2Ext* surfaceCapabilities); private static vkGetPhysicalDeviceSurfaceCapabilities2EXTDelegate vkGetPhysicalDeviceSurfaceCapabilities2EXT(PhysicalDevice physicalDevice) => GetProc<vkGetPhysicalDeviceSurfaceCapabilities2EXTDelegate>(physicalDevice, nameof(vkGetPhysicalDeviceSurfaceCapabilities2EXT)); private delegate Result vkGetRandROutputDisplayEXTDelegate(IntPtr physicalDevice, IntPtr* dpy, IntPtr rrOutput, long* display); private static vkGetRandROutputDisplayEXTDelegate vkGetRandROutputDisplayEXT(PhysicalDevice physicalDevice) => GetProc<vkGetRandROutputDisplayEXTDelegate>(physicalDevice, nameof(vkGetRandROutputDisplayEXT)); private delegate void vkGetPhysicalDeviceMultisamplePropertiesEXTDelegate(IntPtr physicalDevice, SampleCounts samples, MultisamplePropertiesExt* multisampleProperties); private static vkGetPhysicalDeviceMultisamplePropertiesEXTDelegate vkGetPhysicalDeviceMultisamplePropertiesEXT(PhysicalDevice physicalDevice) => GetProc<vkGetPhysicalDeviceMultisamplePropertiesEXTDelegate>(physicalDevice, nameof(vkGetPhysicalDeviceMultisamplePropertiesEXT)); private static TDelegate GetProc<TDelegate>(PhysicalDevice physicalDevice, string name) where TDelegate : class => physicalDevice.Parent.GetProc<TDelegate>(name); } /// <summary> /// Structure describing capabilities of a surface. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct SurfaceCapabilities2Ext { internal StructureType Type; /// <summary> /// Is <see cref="IntPtr.Zero"/> or a pointer to an extension-specific structure. /// </summary> public IntPtr Next; /// <summary> /// The minimum number of images the specified device supports for a swapchain created for /// the surface, and will be at least one. /// </summary> public int MinImageCount; /// <summary> /// The maximum number of images the specified device supports for a swapchain created for /// the surface, and will be either 0, or greater than or equal to <see /// cref="MinImageCount"/>. A value of 0 means that there is no limit on the number of /// images, though there may be limits related to the total amount of memory used by /// swapchain images. /// </summary> public int MaxImageCount; /// <summary> /// The current width and height of the surface, or the special value <see /// cref="Extent2D.WholeSize"/> indicating that the surface size will be determined by the /// extent of a swapchain targeting the surface. /// </summary> public Extent2D CurrentExtent; /// <summary> /// Contains the smallest valid swapchain extent for the surface on the specified device. The /// width and height of the extent will each be less than or equal to the corresponding width /// and height of <see cref="CurrentExtent"/>, unless <see cref="CurrentExtent"/> has the /// special value described above. /// </summary> public Extent2D MinImageExtent; /// <summary> /// Contains the largest valid swapchain extent for the surface on the specified device. The /// width and height of the extent will each be greater than or equal to the corresponding /// width and height of <see cref="MinImageExtent"/>. The width and height of the extent will /// each be greater than or equal to the corresponding width and height of <see /// cref="CurrentExtent"/>, unless <see cref="CurrentExtent"/> has the special value /// described above. /// </summary> public Extent2D MaxImageExtent; /// <summary> /// The maximum number of layers swapchain images can have for a swapchain created for this /// device and surface, and will be at least one. /// </summary> public int MaxImageArrayLayers; /// <summary> /// A bitmask of <see cref="SurfaceTransformsKhr"/>, describing the presentation /// transforms supported for the surface on the specified device, and at least one bit will /// be set. /// </summary> public SurfaceTransformsKhr SupportedTransforms; /// <summary> /// The surface's current transform relative to the presentation engine's natural /// orientation, as described by <see cref="SurfaceTransformsKhr"/>. /// </summary> public SurfaceTransformsKhr CurrentTransform; /// <summary> /// A bitmask of <see cref="CompositeAlphasKhr"/>, representing the alpha compositing /// modes supported by the presentation engine for the surface on the specified device, and /// at least one bit will be set. Opaque composition can be achieved in any alpha compositing /// mode by either using a swapchain image format that has no alpha component, or by ensuring /// that all pixels in the swapchain images have an alpha value of 1.0. /// </summary> public CompositeAlphasKhr SupportedCompositeAlpha; /// <summary> /// A bitmask of <see cref="ImageUsages"/> representing the ways the /// application can use the presentable images of a swapchain created for the /// surface on the specified device. <see cref="ImageUsages.ColorAttachment"/> /// must be included in the set but implementations may support additional usages. /// </summary> public ImageUsages SupportedUsageFlags; /// <summary> /// A bitfield containing one bit set for each surface counter type supported. /// </summary> public SurfaceCountersExt SupportedSurfaceCounters; } /// <summary> /// Surface-relative counter types. /// </summary> [Flags] public enum SurfaceCountersExt { /// <summary> /// No flags. /// </summary> None = 0, /// <summary> /// Indicates a counter incrementing once every time a vertical blanking period occurs on the /// display associated with the surface. /// </summary> VBlank = 1 << 0 } /// <summary> /// Structure describing discard rectangle limits that can be supported by an implementation. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct PhysicalDeviceDiscardRectanglePropertiesExt { internal StructureType Type; /// <summary> /// Pointer to next structure. /// </summary> public IntPtr Next; /// <summary> /// The maximum number of discard rectangles that can be specified. /// </summary> public int MaxDiscardRectangles; } /// <summary> /// Structure describing advanced blending features that can be supported by an implementation. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct PhysicalDeviceBlendOperationAdvancedFeaturesExt { internal StructureType Type; /// <summary> /// Pointer to next structure. /// </summary> public IntPtr Next; public Bool AdvancedBlendCoherentOperations; } /// <summary> /// Structure describing advanced blending limits that can be supported by an implementation. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct PhysicalDeviceBlendOperationAdvancedPropertiesExt { internal StructureType Type; /// <summary> /// Pointer to next structure. /// </summary> public IntPtr Next; public int AdvancedBlendMaxColorAttachments; public Bool AdvancedBlendIndependentBlend; public Bool AdvancedBlendNonPremultipliedSrcColor; public Bool AdvancedBlendNonPremultipliedDstColor; public Bool AdvancedBlendCorrelatedOverlap; public Bool AdvancedBlendAllOperations; } /// <summary> /// Structure returning information about sample count specific additional multisampling capabilities. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct MultisamplePropertiesExt { /// <summary> /// The type of this structure. /// </summary> public StructureType Type; /// <summary> /// Is <see cref="IntPtr.Zero"/> or a pointer to an extension-specific structure. /// </summary> public IntPtr Next; /// <summary> /// The maximum size of the pixel grid in which sample locations can vary. /// </summary> public Extent2D MaxSampleLocationGridSize; } /// <summary> /// Structure describing conservative raster properties that can be supported by an /// implementation. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct PhysicalDeviceConservativeRasterizationPropertiesExt { public StructureType Type; public IntPtr Next; public float PrimitiveOverestimationSize; public float MaxExtraPrimitiveOverestimationSize; public float ExtraPrimitiveOverestimationSizeGranularity; public Bool PrimitiveUnderestimation; public Bool ConservativePointAndLineRasterization; public Bool DegenerateTrianglesRasterized; public Bool DegenerateLinesRasterized; public Bool FullyCoveredFragmentShaderInputVariable; public Bool ConservativeRasterizationPostDepthCoverage; } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Test.Utilities; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.CodeQuality.CSharp.Analyzers.ApiDesignGuidelines.CSharpTypesThatOwnDisposableFieldsShouldBeDisposableAnalyzer, Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.TypesThatOwnDisposableFieldsShouldBeDisposableFixer>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.CodeQuality.VisualBasic.Analyzers.ApiDesignGuidelines.BasicTypesThatOwnDisposableFieldsShouldBeDisposableAnalyzer, Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.TypesThatOwnDisposableFieldsShouldBeDisposableFixer>; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests { public class TypesThatOwnDisposableFieldsShouldBeDisposableAnalyzerTests { [Fact] public async Task CA1001CSharpTestWithNoDisposableTypeAsync() { await VerifyCS.VerifyAnalyzerAsync(@" class Program { static void Main(string[] args) { } } "); } [Fact] public async Task CA1001CSharpTestWithNoCreationOfDisposableObjectAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System.IO; public class NoDisposeClass { FileStream newFile; } "); } [Fact] public async Task CA1001CSharpTestWithFieldInitAndNoDisposeMethodAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System.IO; public class NoDisposeClass { FileStream newFile1, newFile2 = new FileStream(""data.txt"", FileMode.Append); } ", GetCA1001CSharpResultAt(4, 18, "NoDisposeClass", "newFile2")); } [Fact] public async Task CA1001CSharpTestWithCtorInitAndNoDisposeMethodAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System.IO; // This class violates the rule. public class NoDisposeClass { FileStream newFile; public NoDisposeClass() { newFile = new FileStream(""data.txt"", FileMode.Append); } } ", GetCA1001CSharpResultAt(5, 18, "NoDisposeClass", "newFile")); } [Fact] public async Task CA1001CSharpTestWithCreationOfDisposableObjectInOtherClassAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System.IO; public class NoDisposeClass { public FileStream newFile; } public class CreationClass { public void Create() { var obj = new NoDisposeClass() { newFile = new FileStream(""data.txt"", FileMode.Append) }; } } "); await VerifyCS.VerifyAnalyzerAsync(@" using System.IO; public class NoDisposeClass { public FileStream newFile; public NoDisposeClass(FileStream fs) { newFile = fs; } } "); } [Fact] public async Task CA1001CSharpTestWithNoDisposeMethodInScopeAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System.IO; // This class violates the rule. public class [|NoDisposeClass|] { FileStream newFile; public NoDisposeClass() { newFile = new FileStream(""data.txt"", FileMode.Append); } } "); } [Fact] public async Task CA1001CSharpScopedTestWithNoDisposeMethodOutOfScopeAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.IO; // This class violates the rule. public class [|NoDisposeClass|] { FileStream newFile; public NoDisposeClass() { newFile = new FileStream(""data.txt"", FileMode.Append); } } public class SomeClass { } "); } [Fact] public async Task CA1001CSharpTestWithADisposeMethodAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.IO; // This class satisfies the rule. public class HasDisposeMethod : IDisposable { FileStream newFile; public HasDisposeMethod() { newFile = new FileStream(""data.txt"", FileMode.Append); } protected virtual void Dispose(bool disposing) { if (disposing) { // dispose managed resources newFile.Close(); } // free native resources } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } "); } [Fact, WorkItem(1562, "https://github.com/dotnet/roslyn-analyzers/issues/1562")] public async Task CA1001CSharpTestWithIDisposableFieldAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System; using System.IO; namespace ClassLibrary1 { public class Class1 { private readonly IDisposable _disp1 = new MemoryStream(); } } ", GetCA1001CSharpResultAt(7, 18, "Class1", "_disp1")); } [Fact, WorkItem(1562, "https://github.com/dotnet/roslyn-analyzers/issues/1562")] public async Task CA1001CSharpTestWithIAsyncDisposableAsync() { await VerifyCS.VerifyAnalyzerAsync(@" namespace System { public class ValueTask {} public interface IAsyncDisposable { ValueTask DisposeAsync(); } public sealed class Stream : System.IDisposable, IAsyncDisposable { public ValueTask DisposeAsync() => new ValueTask(); public void Dispose() {} } } namespace ClassLibrary1 { using System; public class Class1 : IAsyncDisposable { private readonly Stream _disposableMember = new Stream(); public ValueTask DisposeAsync() => _disposableMember.DisposeAsync(); } } "); } [Fact] public async Task CA1001BasicTestWithNoDisposableTypeAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Module Module1 Sub Main() End Sub End Module "); } [Fact] public async Task CA1001BasicTestWithNoCreationOfDisposableObjectAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System.IO Public Class NoDisposeClass Dim newFile As FileStream End Class "); } [Fact] public async Task CA1001BasicTestWithFieldInitAndNoDisposeMethodAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System.IO ' This class violates the rule. Public Class NoDisposeClass Dim newFile As FileStream = New FileStream(""data.txt"", FileMode.Append) End Class ", GetCA1001BasicResultAt(5, 18, "NoDisposeClass", "newFile")); await VerifyVB.VerifyAnalyzerAsync(@" Imports System.IO ' This class violates the rule. Public Class NoDisposeClass Dim newFile1 As FileStream, newFile2 As FileStream = New FileStream(""data.txt"", FileMode.Append) End Class ", GetCA1001BasicResultAt(5, 18, "NoDisposeClass", "newFile2")); await VerifyVB.VerifyAnalyzerAsync(@" Imports System.IO ' This class violates the rule. Public Class NoDisposeClass Dim newFile1 As FileStream Dim newFile2 As FileStream = New FileStream(""data.txt"", FileMode.Append) End Class ", GetCA1001BasicResultAt(5, 18, "NoDisposeClass", "newFile2")); } [Fact] public async Task CA1001BasicTestWithCtorInitAndNoDisposeMethodAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System Imports System.IO ' This class violates the rule. Public Class NoDisposeMethod Dim newFile As FileStream Sub New() newFile = New FileStream(Nothing, FileMode.Open) End Sub End Class ", GetCA1001BasicResultAt(6, 17, "NoDisposeMethod", "newFile")); } [Fact] public async Task CA1001BasicTestWithCreationOfDisposableObjectInOtherClassAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System.IO Public Class NoDisposeClass Public newFile As FileStream End Class Public Class CreationClass Public Sub Create() Dim obj As NoDisposeClass = New NoDisposeClass() obj.newFile = New FileStream(""data.txt"", FileMode.Append) End Sub End Class "); await VerifyVB.VerifyAnalyzerAsync(@" Imports System.IO Public Class NoDisposeClass Public newFile As FileStream Public Sub New(fs As FileStream) newFile = fs End Sub End Class "); } [Fact] public async Task CA1001BasicTestWithNoDisposeMethodInScopeAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System.IO ' This class violates the rule. Public Class [|NoDisposeMethod|] Dim newFile As FileStream Sub New() newFile = New FileStream("""", FileMode.Append) End Sub End Class "); } [Fact] public async Task CA1001BasicTestWithNoDisposeMethodOutOfScopeAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System.IO ' This class violates the rule. Public Class [|NoDisposeMethod|] Dim newFile As FileStream Sub New() newFile = New FileStream(Nothing, FileMode.Open) End Sub End Class Public Class SomeClass End Class "); } [Fact] public async Task CA1001BasicTestWithADisposeMethodAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System Imports System.IO ' This class satisfies the rule. Public Class HasDisposeMethod Implements IDisposable Dim newFile As FileStream Sub New() newFile = New FileStream(Nothing, FileMode.Open) End Sub Overloads Protected Overridable Sub Dispose(disposing As Boolean) If disposing Then ' dispose managed resources newFile.Close() End If ' free native resources End Sub 'Dispose Overloads Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub 'Dispose End Class "); } [Fact, WorkItem(1562, "https://github.com/dotnet/roslyn-analyzers/issues/1562")] public async Task CA1001BasicTestWithIDisposableFieldAsync() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System Imports System.IO Namespace ClassLibrary1 Class Class1 Private Readonly _disp1 As IDisposable = new MemoryStream() End Class End Namespace ", GetCA1001BasicResultAt(6, 11, "Class1", "_disp1")); } [Fact, WorkItem(3905, "https://github.com/dotnet/roslyn-analyzers/issues/3905")] public async Task CA1001_OnlyListDisposableFieldsAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System.IO; public class {|#0:NoDisposeClass|} { FileStream _fs1; FileStream _fs2; public NoDisposeClass(FileStream fs) { _fs1 = new FileStream(""data.txt"", FileMode.Append); _fs2 = fs; } } ", VerifyCS.Diagnostic().WithLocation(0).WithArguments("NoDisposeClass", "_fs1")); await VerifyVB.VerifyAnalyzerAsync(@" Imports System.IO Public Class {|#0:NoDisposeClass|} Private _fs1 As FileStream Private _fs2 As FileStream Public Sub New(ByVal fs As FileStream) _fs1 = New FileStream(""data.txt"", FileMode.Append) _fs2 = fs End Sub End Class ", VerifyVB.Diagnostic().WithLocation(0).WithArguments("NoDisposeClass", "_fs1")); } [Fact, WorkItem(3905, "https://github.com/dotnet/roslyn-analyzers/issues/3905")] public async Task CA1001_ListDisposableFieldsAsync() { await VerifyCS.VerifyAnalyzerAsync(@" using System.IO; public class {|#0:NoDisposeClass|} { FileStream _fs1 = new FileStream(""data.txt"", FileMode.Append), _fs2 = new FileStream(""data.txt"", FileMode.Append); FileStream _fs3; FileStream _fs4; public NoDisposeClass() { _fs3 = new FileStream(""data.txt"", FileMode.Append); _fs4 = new FileStream(""data.txt"", FileMode.Append); } } ", VerifyCS.Diagnostic().WithLocation(0).WithArguments("NoDisposeClass", "_fs1', '_fs2', '_fs3', '_fs4")); await VerifyVB.VerifyAnalyzerAsync(@" Imports System.IO Public Class {|#0:NoDisposeClass|} Private _fs1 As FileStream = new FileStream(""data.txt"", FileMode.Append), _fs2 As FileStream = new FileStream(""data.txt"", FileMode.Append) Private _fs3 As FileStream Private _fs4 As FileStream Public Sub New(ByVal fs As FileStream) _fs3 = new FileStream(""data.txt"", FileMode.Append) _fs4 = new FileStream(""data.txt"", FileMode.Append) End Sub End Class ", VerifyVB.Diagnostic().WithLocation(0).WithArguments("NoDisposeClass", "_fs1', '_fs2', '_fs3', '_fs4")); } [Theory, WorkItem(3905, "https://github.com/dotnet/roslyn-analyzers/issues/3905")] [InlineData("")] [InlineData("dotnet_code_quality.excluded_symbol_names = FileStream")] [InlineData("dotnet_code_quality.CA1001.excluded_symbol_names = FileStream")] [InlineData("dotnet_code_quality.CA1001.excluded_symbol_names = T:System.IO.FileStream")] [InlineData("dotnet_code_quality.CA1001.excluded_symbol_names = FileStr*")] public async Task CA1001_ExcludedSymbolNamesAsync(string editorConfigText) { var args = editorConfigText.Length == 0 ? "_fs', '_ms" : "_ms"; await new VerifyCS.Test { TestState = { Sources = { @" using System.IO; public class {|#0:SomeClass|} { private FileStream _fs = new FileStream(""data.txt"", FileMode.Append); private MemoryStream _ms = new MemoryStream(); } ", }, AnalyzerConfigFiles = { ("/.editorconfig", $@"root = true [*] {editorConfigText} "), }, ExpectedDiagnostics = { VerifyCS.Diagnostic().WithLocation(0).WithArguments("SomeClass", args), }, }, }.RunAsync(); await new VerifyVB.Test { TestState = { Sources = { @" Imports System.IO Public Class {|#0:SomeClass|} Private _fs As FileStream = new FileStream(""data.txt"", FileMode.Append) Private _ms As MemoryStream = new MemoryStream() End Class ", }, AnalyzerConfigFiles = { ("/.editorconfig", $@"root = true [*] {editorConfigText} "), }, ExpectedDiagnostics = { VerifyVB.Diagnostic().WithLocation(0).WithArguments("SomeClass", args), }, }, }.RunAsync(); } private static DiagnosticResult GetCA1001CSharpResultAt(int line, int column, string objectName, string disposableFields) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic() .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(objectName, disposableFields); private static DiagnosticResult GetCA1001BasicResultAt(int line, int column, string objectName, string disposableFields) #pragma warning disable RS0030 // Do not used banned APIs => VerifyVB.Diagnostic() .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(objectName, disposableFields); } }
#region License, Terms and Conditions // // Jayrock - JSON and JSON-RPC for Microsoft .NET Framework and Mono // Written by Atif Aziz ([email protected]) // Copyright (c) 2005 Atif Aziz. All rights reserved. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License as published by the Free // Software Foundation; either version 2.1 of the License, or (at your option) // any later version. // // This library is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more // details. // // You should have received a copy of the GNU Lesser General Public License // along with this library; if not, write to the Free Software Foundation, Inc., // 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #endregion namespace EZOper.NetSiteUtilities.Jayrock { #region Imports using System; using System.Diagnostics; #endregion /// <summary> /// Base implementation of <see cref="JsonWriter"/> that can be used /// as a starting point for sub-classes of <see cref="JsonWriter"/>. /// </summary> public abstract class JsonWriterBase : JsonWriter { private WriterStateStack _stateStack; private WriterState _state; public JsonWriterBase() { _state = new WriterState(JsonWriterBracket.Pending); } public sealed override int Depth { get { return HasStates ? States.Count : 0; } } public sealed override int Index { get { return Depth == 0 ? -1 : _state.Index; } } public sealed override JsonWriterBracket Bracket { get { return _state.Bracket; } } public sealed override void WriteStartObject() { EnsureNotEnded(); if (_state.Bracket != JsonWriterBracket.Pending) EnsureMemberOnObjectBracket(); WriteStartObjectImpl(); EnterBracket(JsonWriterBracket.Object); } public sealed override void WriteEndObject() { if (_state.Bracket != JsonWriterBracket.Object) throw new JsonException("JSON Object tail not expected at this time."); WriteEndObjectImpl(); ExitBracket(); } public sealed override void WriteMember(string name) { if (_state.Bracket != JsonWriterBracket.Object) throw new JsonException("A JSON Object member is not valid inside a JSON Array."); WriteMemberImpl(name); _state.Bracket = JsonWriterBracket.Member; } public sealed override void WriteStartArray() { EnsureNotEnded(); if (_state.Bracket != JsonWriterBracket.Pending) EnsureMemberOnObjectBracket(); WriteStartArrayImpl(); EnterBracket(JsonWriterBracket.Array); } public sealed override void WriteEndArray() { if (_state.Bracket != JsonWriterBracket.Array) throw new JsonException("JSON Array tail not expected at this time."); WriteEndArrayImpl(); ExitBracket(); } public sealed override void WriteString(string value) { if (Depth == 0) { WriteStartArray(); WriteString(value); WriteEndArray(); } else { EnsureMemberOnObjectBracket(); WriteStringImpl(value); OnValueWritten(); } } public sealed override void WriteNumber(string value) { if (Depth == 0) { WriteStartArray(); WriteNumber(value); WriteEndArray(); } else { EnsureMemberOnObjectBracket(); WriteNumberImpl(value); OnValueWritten(); } } public sealed override void WriteBoolean(bool value) { if (Depth == 0) { WriteStartArray(); WriteBoolean(value); WriteEndArray(); } else { EnsureMemberOnObjectBracket(); WriteBooleanImpl(value); OnValueWritten(); } } public sealed override void WriteNull() { if (Depth == 0) { WriteStartArray(); WriteNull(); WriteEndArray(); } else { EnsureMemberOnObjectBracket(); WriteNullImpl(); OnValueWritten(); } } // // Actual methods that need to be implemented by the subclass. // These methods do not need to check for the structural // integrity since this is checked by this base implementation. // protected abstract void WriteStartObjectImpl(); protected abstract void WriteEndObjectImpl(); protected abstract void WriteMemberImpl(string name); protected abstract void WriteStartArrayImpl(); protected abstract void WriteEndArrayImpl(); protected abstract void WriteStringImpl(string value); protected abstract void WriteNumberImpl(string value); protected abstract void WriteBooleanImpl(bool value); protected abstract void WriteNullImpl(); private bool HasStates { get { return _stateStack != null && _stateStack.Count > 0; } } private WriterStateStack States { get { if (_stateStack == null) _stateStack = new WriterStateStack(); return _stateStack; } } private void EnterBracket(JsonWriterBracket newBracket) { Debug.Assert(newBracket == JsonWriterBracket.Array || newBracket == JsonWriterBracket.Object); States.Push(_state); _state = new WriterState(newBracket); } private void ExitBracket() { _state = States.Pop(); if (_state.Bracket == JsonWriterBracket.Pending) _state.Bracket = JsonWriterBracket.Closed; else OnValueWritten(); } private void OnValueWritten() { if (_state.Bracket == JsonWriterBracket.Member) _state.Bracket = JsonWriterBracket.Object; _state.Index++; } private void EnsureMemberOnObjectBracket() { if (_state.Bracket == JsonWriterBracket.Object) throw new JsonException("A JSON member value inside a JSON object must be preceded by its member name."); } private void EnsureNotEnded() { if (_state.Bracket == JsonWriterBracket.Closed) throw new JsonException("JSON text has already been ended."); } [ Serializable ] private struct WriterState { public JsonWriterBracket Bracket; public int Index; public WriterState(JsonWriterBracket bracket) { Bracket = bracket; Index = 0; } } [ Serializable ] private sealed class WriterStateStack { private WriterState[] _states; private int _count; public int Count { get { return _count; } } public void Push(WriterState state) { if (_states == null) { _states = new WriterState[6]; } else if (_count == _states.Length) { WriterState[] items = new WriterState[_states.Length * 2]; _states.CopyTo(items, 0); _states = items; } _states[_count++] = state; } public WriterState Pop() { if (_count == 0) throw new InvalidOperationException(); WriterState state = _states[--_count]; if (_count == 0) _states = null; return state; } } } }
using System; using System.Collections.Generic; namespace Platform.VirtualFileSystem.Providers.Overlayed { public class OverlayedDirectory : DirectoryDelegationWrapper { private readonly INodeAddress nodeAddress; private readonly OverlayedFileSystem fileSystem; public OverlayedDirectory(OverlayedFileSystem fileSystem, INodeAddress nodeAddress, IDirectory directory) : base(directory) { this.fileSystem = fileSystem; this.nodeAddress = nodeAddress; } public override IFileSystem CreateView(string scheme, FileSystemOptions options) { return new View.ViewFileSystem(scheme, this, options); } public override INodeAddress Address { get { return nodeAddress; } } public override IFileSystem FileSystem { get { return fileSystem; } } public override IEnumerable<INode> GetAlternates() { return fileSystem.GetAlternates(this); } public override IDirectory Refresh(DirectoryRefreshMask mask) { foreach (var node in this.GetAlternates()) { ((IDirectory)node).Refresh(mask); } SetWrappee(fileSystem.GetOverlay(this.Wrappee.Address, this.Wrappee.NodeType)); return this; } /// <summary> /// <see cref="IResolver.Resolve(string, NodeType, AddressScope)"/> /// </summary> public override INode Resolve(string name, NodeType nodeType, AddressScope scope) { var address = this.Address.ResolveAddress(name, scope); return this.FileSystem.Resolve(address, nodeType); } public override IEnumerable<string> GetChildNames(NodeType nodeType, Predicate<string> acceptName) { var localNodes = nodes; localNodes.Clear(); try { foreach (IDirectory dir in this.GetAlternates()) { if (dir == this) { continue; } var childNames = dir.GetChildNames(nodeType).GetEnumerator(); using (childNames) { while (true) { try { if (!childNames.MoveNext()) { break; } } catch (DirectoryNodeNotFoundException) { break; } if (!localNodes.ContainsKey(childNames.Current)) { localNodes.Add(childNames.Current, true); yield return childNames.Current; } } } } } finally { localNodes.Clear(); } } [ThreadStatic] private IDictionary<string, bool> nodes = new Dictionary<string, bool>(StringComparer.CurrentCultureIgnoreCase); public override IEnumerable<INode> GetChildren(NodeType nodeType, Predicate<INode> acceptNode) { INode node; foreach (string name in this.GetChildNames(nodeType)) { node = fileSystem.Resolve(this.Address.ResolveAddress(name).AbsolutePath, nodeType); if (acceptNode(node)) { yield return node; } } } public override INode Create(bool createParent) { INode[] nodes; if (((OverlayedFileSystem)this.FileSystem).OverlayedNodeSelector.SelectNodeForOperation( (OverlayedFileSystem)this.FileSystem, FileSystemActivity.Created, this.Address, this.NodeType, out nodes)) { int count = 0; foreach (IDirectory node in nodes) { try { node.Create(createParent); count++; } catch (NodeNotFoundException) { continue; } } if (count == 0) { throw new NodeNotFoundException(this.Address); } } else { return base.Create(createParent); } return this; } public override IDirectory Delete(bool recursive) { INode[] nodes; if (((OverlayedFileSystem)this.FileSystem).OverlayedNodeSelector.SelectNodeForOperation( (OverlayedFileSystem)this.FileSystem, FileSystemActivity.Deleted, this.Address, this.NodeType, out nodes)) { int count = 0; foreach (IDirectory node in nodes) { try { node.Delete(recursive); count++; } catch (NodeNotFoundException) { continue; } } if (count == 0) { throw new NodeNotFoundException(this.Address); } } else { return base.Delete(recursive); } return this; } public override INode RenameTo(string name, bool overwrite) { INode[] nodes; if (((OverlayedFileSystem)this.FileSystem).OverlayedNodeSelector.SelectNodeForOperation( (OverlayedFileSystem)this.FileSystem, FileSystemActivity.Renamed, this.Address, this.NodeType, out nodes)) { int count = 0; foreach (IDirectory node in nodes) { try { node.RenameTo(name, overwrite); count++; } catch (NodeNotFoundException) { continue; } } if (count == 0) { throw new NodeNotFoundException(this.Address); } } else { return base.RenameTo(name, overwrite); } return this; } } }
/* * Reactor 3D MIT License * * Copyright (c) 2010 Reiser Games * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Storage; using Microsoft.Xna.Framework.Content; namespace Reactor { public class RScreen2D { #region Static static RScreen2D _instance; public static RScreen2D Instance { get { return _instance; } } #endregion #region Internal Members internal SpriteBatch _spritebatch; internal BasicEffect _basicEffect; internal VertexDeclaration _lineDeclaration; internal Texture2D _lineTexture; #endregion #region Public Methods public RScreen2D() { if (_instance == null) { _instance = this; _instance._spritebatch = new SpriteBatch(REngine.Instance._graphics.GraphicsDevice); _instance._basicEffect = new BasicEffect(REngine.Instance._graphics.GraphicsDevice); _instance._lineDeclaration = VertexPositionColor.VertexDeclaration; _instance._lineTexture = new Texture2D(REngine.Instance._graphics.GraphicsDevice, 1, 1); _instance._lineTexture.SetData(new Color[] { Color.White }); } else { } } public void Destroy() { _instance._spritebatch.Dispose(); } public void Action_Begin2D() { _instance._spritebatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend); } public void Action_End2D() { _instance._spritebatch.End(); } internal static void IAction_Begin2D() { REngine.Instance._graphics.GraphicsDevice.DepthStencilState = DepthStencilState.None; if (RAtmosphere.Instance != null) if (RAtmosphere.Instance.fogEnabled) REngine.Instance._graphics.GraphicsDevice.BlendState = BlendState.Opaque; //_instance._spritebatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Texture, SaveStateMode.SaveState); } internal void Update() { IAction_Begin2D(); REngine.Instance._game.game.Render2D(); REngine.Instance.DrawFps(); REngine.Instance._game.RenderWatermark(); IAction_End2D(); } internal static void IAction_End2D() { } public RFONT Create_TextureFont(string FontName, string FileName) { RFONT font = new RFONT(); font._name = FontName; font._spriteFont = REngine.Instance._content.Load<SpriteFont>(FileName); return font; } public void Draw_TextureFont(RFONT font, int X, int Y, string Message) { Draw_TextureFont(font, X, Y, Message, new R4DVECTOR(1f, 1f, 1f, 1f)); } public void Draw_Rect2D(int X, int Y, int Width, int Height, R4DVECTOR color) { Color c = new Color(color.vector); try { _instance._spritebatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend); _instance._spritebatch.Draw(_instance._lineTexture, new Rectangle(X, Y, Width, Height), c); _instance._spritebatch.End(); } catch { } } public void Draw_Line3D(R3DVECTOR start, R3DVECTOR end, R4DVECTOR color) { VertexPositionColor[] v = new VertexPositionColor[3]; v[0] = new VertexPositionColor(start.vector, new Color(color.vector)); v[1] = new VertexPositionColor(end.vector, new Color(color.vector)); _instance._basicEffect.View = REngine.Instance._camera.viewMatrix; _instance._basicEffect.Projection = REngine.Instance._camera.projMatrix; _instance._basicEffect.World = Matrix.Identity; _instance._basicEffect.VertexColorEnabled = true; _instance._basicEffect.CurrentTechnique.Passes[0].Apply(); // Draw the triangle. REngine.Instance._graphics.GraphicsDevice.DrawUserPrimitives(PrimitiveType.LineList, v, 0, 1); } public void Draw_TextureFont(RFONT font, int X, int Y, string Message, R4DVECTOR color) { Color c = new Color(color.vector); try { _instance._spritebatch.Begin(); _instance._spritebatch.DrawString(font._spriteFont, Message, new Vector2(X, Y), c); _instance._spritebatch.End(); } catch (Exception e) { Console.WriteLine(e.ToString()); REngine.Instance.AddToLog(e.ToString()); } } public void Draw_TextureFont(RFONT font, int X, int Y, string Message, R4DVECTOR color, float Rotation, R2DVECTOR RotationOrigin, R2DVECTOR Scale) { Color c = new Color(color.vector); try { _instance._spritebatch.Begin(); _instance._spritebatch.DrawString(font._spriteFont, Message, new Vector2(X, Y), c, Rotation, RotationOrigin.vector, Scale.vector, SpriteEffects.None, 0); _instance._spritebatch.End(); } catch (Exception e) { Console.WriteLine(e.ToString()); REngine.Instance.AddToLog(e.ToString()); } } public R3DVECTOR Unproject(R3DVECTOR Position, RSceneNode Node) { Vector3 v = REngine.Instance.GetViewport().Unproject(Position.vector, REngine.Instance._camera.projMatrix, REngine.Instance._camera.viewMatrix, Matrix.Identity); return R3DVECTOR.FromVector3(v); } public R3DVECTOR Project(R3DVECTOR Position, RSceneNode Node) { Vector3 v = REngine.Instance.GetViewport().Project(Position.vector, REngine.Instance._camera.projMatrix, REngine.Instance._camera.viewMatrix, Matrix.Identity); return R3DVECTOR.FromVector3(v); } public void Draw_Texture2D(int TextureID, int X, int Y, int Width, int Height, int scaleX, int scaleY) { Texture2D tex = (Texture2D)RTextureFactory.Instance._textureList[TextureID]; Rectangle rect = new Rectangle(X,Y,Width * scaleX,Height * scaleY); _instance._spritebatch.Begin(); _instance._spritebatch.Draw(tex, rect, Color.White); _instance._spritebatch.End(); } public void Draw_Texture2D(int TextureID, int X, int Y, int Width, int Height, int scaleX, int scaleY, R4DVECTOR color) { Color c = new Color(color.vector); Texture2D tex = (Texture2D)RTextureFactory.Instance._textureList[TextureID]; Rectangle rect = new Rectangle(X, Y, Width * scaleX, Height * scaleY); _instance._spritebatch.Begin(); _instance._spritebatch.Draw(tex, rect, c); _instance._spritebatch.End(); } public void Draw_Texture2D(int TextureID, int X, int Y, int Width, int Height, int SourceX, int SourceY, int SourceWidth, int SourceHeight, int scaleX, int scaleY, R4DVECTOR color) { Color c = new Color(color.vector); Texture2D tex = (Texture2D)RTextureFactory.Instance._textureList[TextureID]; Rectangle rect = new Rectangle(X, Y, Width * scaleX, Height * scaleY); Rectangle sourcerect = new Rectangle(SourceX, SourceY, SourceWidth, SourceHeight); _instance._spritebatch.Begin(); _instance._spritebatch.Draw(tex, rect, sourcerect, c); _instance._spritebatch.End(); } public void Draw_Texture2D(int TextureID, int X, int Y, int Width, int Height, int SourceX, int SourceY, int SourceWidth, int SourceHeight, int scaleX, int scaleY, R4DVECTOR color, float Rotation) { Color c = new Color(color.vector); Texture2D tex = (Texture2D)RTextureFactory.Instance._textureList[TextureID]; Rectangle rect = new Rectangle(X, Y, Width * scaleX, Height * scaleY); Rectangle sourcerect = new Rectangle(SourceX, SourceY, SourceWidth, SourceHeight); _instance._spritebatch.Begin(); _instance._spritebatch.Draw(tex, rect, sourcerect, c, Rotation, new Vector2(SourceWidth/2, SourceHeight/2), SpriteEffects.None, 1.0f); _instance._spritebatch.End(); } public void Draw_Texture2D(int TextureID, int X, int Y, int Width, int Height, int SourceX, int SourceY, int SourceWidth, int SourceHeight, int scaleX, int scaleY, R4DVECTOR color, float Rotation, bool FlipHorizontal) { Color c = new Color(color.vector); Texture2D tex = (Texture2D)RTextureFactory.Instance._textureList[TextureID]; Rectangle rect = new Rectangle(X, Y, Width * scaleX, Height * scaleY); Rectangle sourcerect = new Rectangle(SourceX, SourceY, SourceWidth, SourceHeight); SpriteEffects effects = SpriteEffects.None; if (FlipHorizontal) effects = SpriteEffects.FlipHorizontally; _instance._spritebatch.Begin(); _instance._spritebatch.Draw(tex, rect, sourcerect, c, Rotation, new Vector2((rect.Width / 2), (rect.Height / 2)), effects, 1.0f); _instance._spritebatch.End(); } #endregion } }