context
stringlengths
2.52k
185k
gt
stringclasses
1 value
//----------------------------------------------------------------------- // // Microsoft Windows Client Platform // Copyright (C) Microsoft Corporation, 2002 // // File: FamilyTypefaceCollection.cs // // Contents: FamilyTypefaceCollection // // Created: 2-5-05 Niklas Borson (niklasb) // //------------------------------------------------------------------------ using System; using System.Globalization; using SC=System.Collections; using System.Collections.Generic; using MS.Internal.FontFace; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; namespace System.Windows.Media { /// <summary> /// List of FamilyTypeface objects in a FontFamily, in lookup order. /// </summary> public sealed class FamilyTypefaceCollection : IList<FamilyTypeface>, SC.IList { private const int InitialCapacity = 2; private ICollection<Typeface> _innerList; private FamilyTypeface[] _items; private int _count; /// <summary> /// Constructs a read-write list of FamilyTypeface objects. /// </summary> internal FamilyTypefaceCollection() { _innerList = null; _items = null; _count = 0; } /// <summary> /// Constructes a read-only list that wraps an ICollection. /// </summary> internal FamilyTypefaceCollection(ICollection<Typeface> innerList) { _innerList = innerList; _items = null; _count = innerList.Count; } #region IEnumerable members /// <summary> /// Returns an enumerator for iterating through the list. /// </summary> public IEnumerator<FamilyTypeface> GetEnumerator() { return new Enumerator(this); } SC.IEnumerator SC.IEnumerable.GetEnumerator() { return new Enumerator(this); } #endregion #region ICollection methods /// <summary> /// Adds a FamilyTypeface to the font family. /// </summary> public void Add(FamilyTypeface item) { InsertItem(_count, item); } /// <summary> /// Removes all FamilyTypeface objects from the FontFamily. /// </summary> public void Clear() { ClearItems(); } /// <summary> /// Determines whether the FontFamily contains the specified FamilyTypeface. /// </summary> public bool Contains(FamilyTypeface item) { return FindItem(item) >= 0; } /// <summary> /// Copies the contents of the list to the specified array. /// </summary> public void CopyTo(FamilyTypeface[] array, int index) { CopyItems(array, index); } void SC.ICollection.CopyTo(Array array, int index) { CopyItems(array, index); } bool SC.ICollection.IsSynchronized { get { return false; } } object SC.ICollection.SyncRoot { get { return this; } } /// <summary> /// Removes the specified FamilyTypeface. /// </summary> public bool Remove(FamilyTypeface item) { VerifyChangeable(); int i = FindItem(item); if (i >= 0) { RemoveAt(i); return true; } return false; } /// <summary> /// Gets the number of items in the list. /// </summary> public int Count { get { return _count; } } /// <summary> /// Gets a value indicating whether the FamilyTypeface list can be changed. /// </summary> public bool IsReadOnly { get { return _innerList != null; } } #endregion #region IList members /// <summary> /// Gets the index of the specified FamilyTypeface. /// </summary> public int IndexOf(FamilyTypeface item) { return FindItem(item); } /// <summary> /// Inserts a FamilyTypeface into the list. /// </summary> public void Insert(int index, FamilyTypeface item) { InsertItem(index, item); } /// <summary> /// Removes the FamilyTypeface at the specified index. /// </summary> public void RemoveAt(int index) { RemoveItem(index); } /// <summary> /// Gets or sets the FamilyTypeface at the specified index. /// </summary> public FamilyTypeface this[int index] { get { return GetItem(index); } set { SetItem(index, value); } } int SC.IList.Add(object value) { return InsertItem(_count, ConvertValue(value)); } bool SC.IList.Contains(object value) { return FindItem(value as FamilyTypeface) >= 0; } int SC.IList.IndexOf(object value) { return FindItem(value as FamilyTypeface); } void SC.IList.Insert(int index, object item) { InsertItem(index, ConvertValue(item)); } void SC.IList.Remove(object value) { VerifyChangeable(); int i = FindItem(value as FamilyTypeface); if (i >= 0) RemoveItem(i); } bool SC.IList.IsFixedSize { get { return IsReadOnly; } } object SC.IList.this[int index] { get { return GetItem(index); } set { SetItem(index, ConvertValue(value)); } } #endregion #region Internal implementation private int InsertItem(int index, FamilyTypeface item) { if (item == null) throw new ArgumentNullException("item"); VerifyChangeable(); // Validate the index. if (index < 0 || index > Count) throw new ArgumentOutOfRangeException("index"); // We can't have two items with same style, weight, stretch. if (FindItem(item) >= 0) throw new ArgumentException(SR.Get(SRID.CompositeFont_DuplicateTypeface)); // Make room for the new item. if (_items == null) { _items = new FamilyTypeface[InitialCapacity]; } else if (_count == _items.Length) { FamilyTypeface[] items = new FamilyTypeface[_count * 2]; for (int i = 0; i < index; ++i) items[i] = _items[i]; for (int i = index; i < _count; ++i) items[i + 1] = _items[i]; _items = items; } else if (index < _count) { for (int i = _count - 1; i >= index; --i) _items[i + 1] = _items[i]; } // Add the item. _items[index] = item; _count++; return index; } private void InitializeItemsFromInnerList() { if (_innerList != null && _items == null) { // Create the array. FamilyTypeface[] items = new FamilyTypeface[_count]; // Create a FamilyTypeface for each Typeface in the inner list. int i = 0; foreach (Typeface face in _innerList) { items[i++] = new FamilyTypeface(face); } // For thread-safety, set _items to the fully-initialized array at the end. _items = items; } } private FamilyTypeface GetItem(int index) { RangeCheck(index); InitializeItemsFromInnerList(); return _items[index]; } private void SetItem(int index, FamilyTypeface item) { if (item == null) throw new ArgumentNullException("item"); VerifyChangeable(); RangeCheck(index); _items[index] = item; } private void ClearItems() { VerifyChangeable(); _count = 0; _items = null; } private void RemoveItem(int index) { VerifyChangeable(); RangeCheck(index); _count--; for (int i = index; i < _count; ++i) { _items[i] = _items[i + 1]; } _items[_count] = null; } private int FindItem(FamilyTypeface item) { InitializeItemsFromInnerList(); if (_count != 0 && item != null) { for (int i = 0; i < _count; ++i) { if (GetItem(i).Equals(item)) return i; } } return -1; } private void RangeCheck(int index) { if (index < 0 || index >= _count) throw new ArgumentOutOfRangeException("index"); } private void VerifyChangeable() { if (_innerList != null) throw new NotSupportedException(SR.Get(SRID.General_ObjectIsReadOnly)); } private FamilyTypeface ConvertValue(object obj) { if (obj == null) throw new ArgumentNullException("obj"); FamilyTypeface familyTypeface = obj as FamilyTypeface; if (familyTypeface == null) throw new ArgumentException(SR.Get(SRID.CannotConvertType, obj.GetType(), typeof(FamilyTypeface))); return familyTypeface; } private void CopyItems(Array array, int index) { if (array == null) throw new ArgumentNullException("array"); if (array.Rank != 1) throw new ArgumentException(SR.Get(SRID.Collection_CopyTo_ArrayCannotBeMultidimensional)); Type elementType = array.GetType().GetElementType(); if (!elementType.IsAssignableFrom(typeof(FamilyTypeface))) throw new ArgumentException(SR.Get(SRID.CannotConvertType, typeof(FamilyTypeface[]), elementType)); if (index >= array.Length) throw new ArgumentException(SR.Get(SRID.Collection_CopyTo_IndexGreaterThanOrEqualToArrayLength, "index", "array")); if (_count > array.Length - index) throw new ArgumentException(SR.Get(SRID.Collection_CopyTo_NumberOfElementsExceedsArrayLength, index, "array")); if (_count != 0) { InitializeItemsFromInnerList(); Array.Copy(_items, 0, array, index, _count); } } private class Enumerator : IEnumerator<FamilyTypeface>, SC.IEnumerator { FamilyTypefaceCollection _list; int _index; FamilyTypeface _current; internal Enumerator(FamilyTypefaceCollection list) { _list = list; _index = -1; _current = null; } public bool MoveNext() { int count = _list.Count; if (_index < count) { _index++; if (_index < count) { _current = _list[_index]; return true; } } _current = null; return false; } void SC.IEnumerator.Reset() { _index = -1; } public FamilyTypeface Current { get { return _current; } } object SC.IEnumerator.Current { get { // If there is no current item a non-generic IEnumerator should throw an exception, // but a generic IEnumerator<T> is not required to. if (_current == null) throw new InvalidOperationException(SR.Get(SRID.Enumerator_VerifyContext)); return _current; } } public void Dispose() { } } #endregion } }
using Android.Content; using Android.Content.PM; using Android.Content.Res; using Android.Gms.Common.Images; using Android.Gms.Vision; using Android.Gms.Vision.Barcodes; using Android.Graphics; using Android.Net; using Android.Support.V4.App; using Android.Views; using Java.IO; using Java.Util; using Java.Util.Concurrent; using System.Collections.Generic; namespace Com.Layer.Messenger.Flavor { public class AppIdScanner : ViewGroup { private SurfaceView mSurfaceView; private BarcodeDetector mBarcodeDetector; private Detector.IProcessor mAppIdProcessor; private CameraSource.Builder mCameraBuilder; private AppIdCallback mAppIdCallback; private bool mStartRequested; private bool mSurfaceAvailable; private CameraSource mCameraSource; public AppIdScanner(Context context) : base(context) { Init(); } public AppIdScanner(Context context, Android.Util.IAttributeSet attrs) : this(context, attrs, 0) { } public AppIdScanner(Context context, Android.Util.IAttributeSet attrs, int defStyleAttr) : base(context, attrs, defStyleAttr) { Init(); } private void Init() { mStartRequested = false; mSurfaceAvailable = false; mAppIdProcessor = new BarcodeDetectorProcessor(this); mBarcodeDetector = new BarcodeDetector.Builder(Context) .SetBarcodeFormats(BarcodeFormat.QrCode) .Build(); mBarcodeDetector.SetProcessor(mAppIdProcessor); mCameraBuilder = new CameraSource.Builder(Context, mBarcodeDetector) .SetFacing(CameraFacing.Back) .SetAutoFocusEnabled(true) .SetRequestedFps(30.0f); mSurfaceView = new SurfaceView(Context); mSurfaceView.Holder.AddCallback(new SurfaceCallback(this)); AddView(mSurfaceView); } public AppIdScanner SetAppIdCallback(AppIdCallback appIdCallback) { mAppIdCallback = appIdCallback; return this; } public void Start() { mStartRequested = true; StartIfReady(); } public void Stop() { if (mCameraSource != null) mCameraSource.Stop(); mSurfaceView.Visibility = ViewStates.Gone; } public void Release() { if (mCameraSource != null) mCameraSource.Release(); mBarcodeDetector.Release(); mAppIdProcessor.Release(); } private void StartIfReady() { if (!mStartRequested || !mSurfaceAvailable || mCameraSource == null) return; if (ActivityCompat.CheckSelfPermission(Context, Android.Manifest.Permission.Camera) != Permission.Granted) { if (Util.Log.IsLoggable(Util.Log.ERROR)) { Util.Log.e("Required permission `" + Android.Manifest.Permission.Camera + "` not granted."); } return; } try { mCameraSource.Start(mSurfaceView.Holder); mStartRequested = false; } catch (IOException e) { if (Util.Log.IsLoggable(Util.Log.ERROR)) { Util.Log.e(e.Message, e); } } } private class SurfaceCallback : Java.Lang.Object, ISurfaceHolderCallback { private AppIdScanner _appIdScanner; public SurfaceCallback(AppIdScanner appIdScanner) { _appIdScanner = appIdScanner; } public void SurfaceCreated(ISurfaceHolder surface) { _appIdScanner.mSurfaceAvailable = true; _appIdScanner.StartIfReady(); } public void SurfaceDestroyed(ISurfaceHolder surface) { _appIdScanner.mSurfaceAvailable = false; } public void SurfaceChanged(ISurfaceHolder holder, Format format, int width, int height) { } } private class BarcodeDetectorProcessor : Java.Lang.Object, Detector.IProcessor { private AppIdScanner _appIdScanner; public BarcodeDetectorProcessor(AppIdScanner appIdScanner) { _appIdScanner = appIdScanner; } public void Release() { } public void ReceiveDetections(Detector.Detections detections) { Android.Util.SparseArray barcodes = detections.DetectedItems; for (int i = 0; i < barcodes.Size(); i++) { Barcode barcode = barcodes.ValueAt(i) as Barcode; string value = barcode.DisplayValue; try { Uri appId = Uri.Parse(value); if (!appId.Scheme.Equals("layer")) { throw new Java.Lang.IllegalArgumentException("URI is not an App ID"); } if (!appId.Authority.Equals("")) { throw new Java.Lang.IllegalArgumentException("URI is not an App ID"); } IList<string> segments = appId.PathSegments; if (segments.Count != 3) { throw new Java.Lang.IllegalArgumentException("URI is not an App ID"); } if (!segments[0].Equals("apps")) { throw new Java.Lang.IllegalArgumentException("URI is not an App ID"); } if (!segments[1].Equals("staging") && !segments[1].Equals("production")) { throw new Java.Lang.IllegalArgumentException("URI is not an App ID"); } UUID uuid = UUID.FromString(segments[2]); if (Util.Log.IsLoggable(Util.Log.VERBOSE)) { Util.Log.v("Captured Layer App ID: " + appId + ", UUID: " + uuid); } if (_appIdScanner.mAppIdCallback == null) return; _appIdScanner.mAppIdCallback.OnLayerAppIdScanned(_appIdScanner, appId.ToString()); } catch (System.Exception e) { // Not this barcode... if (Util.Log.IsLoggable(Util.Log.ERROR)) { Util.Log.e("Barcode does not contain an App ID URI: " + value, e); } } } } } protected override void OnLayout(bool isChange, int left, int top, int right, int bottom) { if (!isChange) return; bool isPortrait = Context.Resources.Configuration.Orientation == Orientation.Portrait; int parentWidth = right - left; int parentHeight = bottom - top; mSurfaceView.Layout(0, 0, 1, 1); int requestWidth = isPortrait ? parentHeight : parentWidth; int requestHeight = isPortrait ? parentWidth : parentHeight; // Request camera preview if (mCameraSource != null) { mCameraSource.Stop(); mCameraSource.Release(); } if (Util.Log.IsLoggable(Util.Log.VERBOSE)) { Util.Log.v("Requesting camera preview: " + requestWidth + "x" + requestHeight); } mCameraSource = mCameraBuilder.SetRequestedPreviewSize(requestWidth, requestHeight).Build(); StartIfReady(); Post(() => { double parentWidth_ = Width; double parentHeight_ = Height; Size previewSize = mCameraSource.PreviewSize; while (previewSize == null) { previewSize = mCameraSource.PreviewSize; try { TimeUnit.Milliseconds.Sleep(15); } catch (Java.Lang.InterruptedException) { // OK } } if (Util.Log.IsLoggable(Util.Log.VERBOSE)) { Util.Log.v("Actual camera preview is: " + previewSize.Width + "x" + previewSize.Height); } bool isPortrait_ = Context.Resources.Configuration.Orientation == Orientation.Portrait; double previewWidth = isPortrait_ ? previewSize.Height : previewSize.Width; double previewHeight = isPortrait_ ? previewSize.Width : previewSize.Height; double widthRatio = previewWidth / parentWidth_; double heightRatio = previewHeight / parentHeight_; double surfaceWidth; double surfaceHeight; if (heightRatio < widthRatio) { surfaceWidth = parentHeight_ * previewWidth / previewHeight; surfaceHeight = parentHeight_; } else { surfaceWidth = parentWidth_; surfaceHeight = parentWidth_ * previewHeight / previewWidth; } double centerLeft = (parentWidth_ - surfaceWidth) / 2.0; double centerTop = (parentHeight_ - surfaceHeight) / 2.0; mSurfaceView.Layout((int) System.Math.Round(centerLeft), (int) System.Math.Round(centerTop), (int) System.Math.Round(surfaceWidth + centerLeft), (int) System.Math.Round(surfaceHeight + centerTop)); if (Util.Log.IsLoggable(Util.Log.VERBOSE)) { Util.Log.v("Resized preview layout to: " + (isPortrait_ ? mSurfaceView.Height : mSurfaceView.Width) + "x" + (isPortrait_ ? mSurfaceView.Width : mSurfaceView.Height)); } }); } public interface AppIdCallback { void OnLayerAppIdScanned(AppIdScanner scanner, string layerAppId); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using QuantConnect.Configuration; using QuantConnect.Logging; using QuantConnect.ToolBox.AlgoSeekFuturesConverter; using QuantConnect.ToolBox.AlgoSeekOptionsConverter; using QuantConnect.ToolBox.BinanceDownloader; using QuantConnect.ToolBox.BitfinexDownloader; using QuantConnect.ToolBox.CoarseUniverseGenerator; using QuantConnect.ToolBox.CoinApiDataConverter; using QuantConnect.ToolBox.CryptoiqDownloader; using QuantConnect.ToolBox.DukascopyDownloader; using QuantConnect.ToolBox.GDAXDownloader; using QuantConnect.ToolBox.IBDownloader; using QuantConnect.ToolBox.IEX; using QuantConnect.ToolBox.IQFeedDownloader; using QuantConnect.ToolBox.IVolatilityEquityConverter; using QuantConnect.ToolBox.KaikoDataConverter; using QuantConnect.ToolBox.KrakenDownloader; using QuantConnect.ToolBox.NseMarketDataConverter; using QuantConnect.ToolBox.OandaDownloader; using QuantConnect.ToolBox.Polygon; using QuantConnect.ToolBox.QuandlBitfinexDownloader; using QuantConnect.ToolBox.QuantQuoteConverter; using QuantConnect.ToolBox.RandomDataGenerator; using QuantConnect.ToolBox.YahooDownloader; using QuantConnect.Util; using QuantConnect.ToolBox.ZerodhaDownloader; using QuantConnect.ToolBox.AlphaVantageDownloader; namespace QuantConnect.ToolBox { public class Program { public static void Main(string[] args) { Log.DebuggingEnabled = Config.GetBool("debug-mode"); var destinationDir = Config.Get("results-destination-folder"); if (!string.IsNullOrEmpty(destinationDir)) { Directory.CreateDirectory(destinationDir); Log.FilePath = Path.Combine(destinationDir, "log.txt"); } Log.LogHandler = Composer.Instance.GetExportedValueByTypeName<ILogHandler>(Config.Get("log-handler", "CompositeLogHandler")); var optionsObject = ToolboxArgumentParser.ParseArguments(args); if (optionsObject.Count == 0) { PrintMessageAndExit(); } var targetApp = GetParameterOrExit(optionsObject, "app").ToLowerInvariant(); if (targetApp.Contains("download") || targetApp.EndsWith("dl")) { var fromDate = Parse.DateTimeExact(GetParameterOrExit(optionsObject, "from-date"), "yyyyMMdd-HH:mm:ss"); var resolution = optionsObject.ContainsKey("resolution") ? optionsObject["resolution"].ToString() : ""; var market = optionsObject.ContainsKey("market") ? optionsObject["market"].ToString() : ""; var securityType = optionsObject.ContainsKey("security-type") ? optionsObject["security-type"].ToString() : ""; var tickers = ToolboxArgumentParser.GetTickers(optionsObject); var toDate = optionsObject.ContainsKey("to-date") ? Parse.DateTimeExact(optionsObject["to-date"].ToString(), "yyyyMMdd-HH:mm:ss") : DateTime.UtcNow; switch (targetApp) { case "zdl": case "zerodhadownloader": ZerodhaDataDownloaderProgram.ZerodhaDataDownloader(tickers,market, resolution, securityType, fromDate, toDate); break; case "gdaxdl": case "gdaxdownloader": GDAXDownloaderProgram.GDAXDownloader(tickers, resolution, fromDate, toDate); break; case "cdl": case "cryptoiqdownloader": CryptoiqDownloaderProgram.CryptoiqDownloader(tickers, GetParameterOrExit(optionsObject, "exchange"), fromDate, toDate); break; case "ddl": case "dukascopydownloader": DukascopyDownloaderProgram.DukascopyDownloader(tickers, resolution, fromDate, toDate); break; case "ibdl": case "ibdownloader": IBDownloaderProgram.IBDownloader(tickers, resolution, fromDate, toDate); break; case "iexdl": case "iexdownloader": IEXDownloaderProgram.IEXDownloader(tickers, resolution, fromDate, toDate); break; case "iqfdl": case "iqfeeddownloader": IQFeedDownloaderProgram.IQFeedDownloader(tickers, resolution, fromDate, toDate); break; case "kdl": case "krakendownloader": KrakenDownloaderProgram.KrakenDownloader(tickers, resolution, fromDate, toDate); break; case "odl": case "oandadownloader": OandaDownloaderProgram.OandaDownloader(tickers, resolution, fromDate, toDate); break; case "qbdl": case "quandlbitfinexdownloader": QuandlBitfinexDownloaderProgram.QuandlBitfinexDownloader(fromDate, GetParameterOrExit(optionsObject, "api-key")); break; case "ydl": case "yahoodownloader": YahooDownloaderProgram.YahooDownloader(tickers, resolution, fromDate, toDate); break; case "bfxdl": case "bitfinexdownloader": BitfinexDownloaderProgram.BitfinexDownloader(tickers, resolution, fromDate, toDate); break; case "mbxdl": case "binancedownloader": BinanceDownloaderProgram.DataDownloader(tickers, resolution, fromDate, toDate); break; case "pdl": case "polygondownloader": PolygonDownloaderProgram.PolygonDownloader( tickers, GetParameterOrExit(optionsObject, "security-type"), GetParameterOrExit(optionsObject, "market"), resolution, fromDate, toDate); break; case "avdl": case "alphavantagedownloader": AlphaVantageDownloaderProgram.AlphaVantageDownloader( tickers, resolution, fromDate, toDate, GetParameterOrExit(optionsObject, "api-key") ); break; default: PrintMessageAndExit(1, "ERROR: Unrecognized --app value"); break; } } else if (targetApp.Contains("updater") || targetApp.EndsWith("spu")) { switch (targetApp) { case "mbxspu": case "binancesymbolpropertiesupdater": BinanceDownloaderProgram.ExchangeInfoDownloader(); break; default: PrintMessageAndExit(1, "ERROR: Unrecognized --app value"); break; } } else { switch (targetApp) { case "asfc": case "algoseekfuturesconverter": AlgoSeekFuturesProgram.AlgoSeekFuturesConverter(GetParameterOrExit(optionsObject, "date")); break; case "asoc": case "algoseekoptionsconverter": AlgoSeekOptionsConverterProgram.AlgoSeekOptionsConverter(GetParameterOrExit(optionsObject, "date")); break; case "ivec": case "ivolatilityequityconverter": IVolatilityEquityConverterProgram.IVolatilityEquityConverter(GetParameterOrExit(optionsObject, "source-dir"), GetParameterOrExit(optionsObject, "source-meta-dir"), GetParameterOrExit(optionsObject, "destination-dir"), GetParameterOrExit(optionsObject, "resolution")); break; case "kdc": case "kaikodataconverter": KaikoDataConverterProgram.KaikoDataConverter(GetParameterOrExit(optionsObject, "source-dir"), GetParameterOrExit(optionsObject, "date"), GetParameterOrDefault(optionsObject, "exchange", string.Empty)); break; case "cadc": case "coinapidataconverter": CoinApiDataConverterProgram.CoinApiDataProgram(GetParameterOrExit(optionsObject, "date"), GetParameterOrExit(optionsObject, "source-dir"), GetParameterOrExit(optionsObject, "destination-dir")); break; case "nmdc": case "nsemarketdataconverter": NseMarketDataConverterProgram.NseMarketDataConverter(GetParameterOrExit(optionsObject, "source-dir"), GetParameterOrExit(optionsObject, "destination-dir")); break; case "qqc": case "quantquoteconverter": QuantQuoteConverterProgram.QuantQuoteConverter(GetParameterOrExit(optionsObject, "destination-dir"), GetParameterOrExit(optionsObject, "source-dir"), GetParameterOrExit(optionsObject, "resolution")); break; case "cug": case "coarseuniversegenerator": CoarseUniverseGeneratorProgram.CoarseUniverseGenerator(); break; case "rdg": case "randomdatagenerator": RandomDataGeneratorProgram.RandomDataGenerator( GetParameterOrExit(optionsObject, "start"), GetParameterOrExit(optionsObject, "end"), GetParameterOrExit(optionsObject, "symbol-count"), GetParameterOrDefault(optionsObject, "market", null), GetParameterOrDefault(optionsObject, "security-type", "Equity"), GetParameterOrDefault(optionsObject, "resolution", "Minute"), GetParameterOrDefault(optionsObject, "data-density", "Dense"), GetParameterOrDefault(optionsObject, "include-coarse", "true"), GetParameterOrDefault(optionsObject, "quote-trade-ratio", "1"), GetParameterOrDefault(optionsObject, "random-seed", null), GetParameterOrDefault(optionsObject, "ipo-percentage", "5.0"), GetParameterOrDefault(optionsObject, "rename-percentage", "30.0"), GetParameterOrDefault(optionsObject, "splits-percentage", "15.0"), GetParameterOrDefault(optionsObject, "dividends-percentage", "60.0"), GetParameterOrDefault(optionsObject, "dividend-every-quarter-percentage", "30.0") ); break; default: PrintMessageAndExit(1, "ERROR: Unrecognized --app value"); break; } } } private static void PrintMessageAndExit(int exitCode = 0, string message = "") { if (!message.IsNullOrEmpty()) { Console.WriteLine("\n" + message); } Console.WriteLine("\nUse the '--help' parameter for more information"); Console.WriteLine("Press any key to quit"); Console.ReadLine(); Environment.Exit(exitCode); } private static string GetParameterOrExit(IReadOnlyDictionary<string, object> optionsObject, string parameter) { if (!optionsObject.ContainsKey(parameter)) { PrintMessageAndExit(1, "ERROR: REQUIRED parameter --" + parameter + "= is missing"); } return optionsObject[parameter].ToString(); } private static string GetParameterOrDefault(IReadOnlyDictionary<string, object> optionsObject, string parameter, string defaultValue) { object value; if (!optionsObject.TryGetValue(parameter, out value)) { Console.WriteLine($"'{parameter}' was not specified. Using default value: '{defaultValue}'"); return defaultValue; } return value.ToString(); } } }
// // TableViewBackend.cs // // Author: // Lluis Sanchez <[email protected]> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using MonoMac.AppKit; using Xwt.Backends; using System.Collections.Generic; using MonoMac.Foundation; using System.Linq; namespace Xwt.Mac { public abstract class TableViewBackend<T,S>: ViewBackend<NSScrollView,S>, ITableViewBackend, ICellSource where T:NSTableView where S:ITableViewEventSink { List<NSTableColumn> cols = new List<NSTableColumn> (); protected NSTableView Table; ScrollView scroll; NSObject selChangeObserver; NormalClipView clipView; Dictionary<CellView,CellInfo> cellViews = new Dictionary<CellView, CellInfo> (); class CellInfo { public ICellRenderer Cell; public int Column; } public TableViewBackend () { } public override void Initialize () { Table = CreateView (); scroll = new ScrollView (); clipView = new NormalClipView (); clipView.Scrolled += OnScrolled; scroll.ContentView = clipView; scroll.DocumentView = Table; scroll.BorderType = NSBorderType.BezelBorder; ViewObject = scroll; Widget.AutoresizingMask = NSViewResizingMask.HeightSizable | NSViewResizingMask.WidthSizable; Widget.AutoresizesSubviews = true; } protected override void Dispose (bool disposing) { base.Dispose (disposing); Util.DrainObjectCopyPool (); } public ScrollPolicy VerticalScrollPolicy { get { if (scroll.AutohidesScrollers && scroll.HasVerticalScroller) return ScrollPolicy.Automatic; else if (scroll.HasVerticalScroller) return ScrollPolicy.Always; else return ScrollPolicy.Never; } set { switch (value) { case ScrollPolicy.Automatic: scroll.AutohidesScrollers = true; scroll.HasVerticalScroller = true; break; case ScrollPolicy.Always: scroll.AutohidesScrollers = false; scroll.HasVerticalScroller = true; break; case ScrollPolicy.Never: scroll.HasVerticalScroller = false; break; } } } public ScrollPolicy HorizontalScrollPolicy { get { if (scroll.AutohidesScrollers && scroll.HasHorizontalScroller) return ScrollPolicy.Automatic; else if (scroll.HasHorizontalScroller) return ScrollPolicy.Always; else return ScrollPolicy.Never; } set { switch (value) { case ScrollPolicy.Automatic: scroll.AutohidesScrollers = true; scroll.HasHorizontalScroller = true; break; case ScrollPolicy.Always: scroll.AutohidesScrollers = false; scroll.HasHorizontalScroller = true; break; case ScrollPolicy.Never: scroll.HasHorizontalScroller = false; break; } } } ScrollControlBackend vertScroll; public IScrollControlBackend CreateVerticalScrollControl () { if (vertScroll == null) vertScroll = new ScrollControlBackend (ApplicationContext, scroll, true); return vertScroll; } ScrollControlBackend horScroll; public IScrollControlBackend CreateHorizontalScrollControl () { if (horScroll == null) horScroll = new ScrollControlBackend (ApplicationContext, scroll, false); return horScroll; } void OnScrolled (object o, EventArgs e) { if (vertScroll != null) vertScroll.NotifyValueChanged (); if (horScroll != null) horScroll.NotifyValueChanged (); } protected override Size GetNaturalSize () { return EventSink.GetDefaultNaturalSize (); } protected abstract NSTableView CreateView (); protected abstract string SelectionChangeEventName { get; } public override void EnableEvent (object eventId) { base.EnableEvent (eventId); if (eventId is TableViewEvent) { switch ((TableViewEvent)eventId) { case TableViewEvent.SelectionChanged: selChangeObserver = NSNotificationCenter.DefaultCenter.AddObserver (new NSString (SelectionChangeEventName), HandleTreeSelectionDidChange, Table); break; } } } public override void DisableEvent (object eventId) { base.DisableEvent (eventId); if (eventId is TableViewEvent) { switch ((TableViewEvent)eventId) { case TableViewEvent.SelectionChanged: if (selChangeObserver != null) NSNotificationCenter.DefaultCenter.RemoveObserver (selChangeObserver); break; } } } void HandleTreeSelectionDidChange (NSNotification notif) { ApplicationContext.InvokeUserCode (delegate { EventSink.OnSelectionChanged (); }); } public void SetSelectionMode (SelectionMode mode) { Table.AllowsMultipleSelection = mode == SelectionMode.Multiple; } public virtual NSTableColumn AddColumn (ListViewColumn col) { var tcol = new NSTableColumn (); tcol.Editable = true; cols.Add (tcol); var c = CellUtil.CreateCell (ApplicationContext, Table, this, col.Views, cols.Count - 1); tcol.DataCell = c; Table.AddColumn (tcol); var hc = new NSTableHeaderCell (); hc.Title = col.Title ?? ""; tcol.HeaderCell = hc; Widget.InvalidateIntrinsicContentSize (); MapColumn (cols.Count - 1, col, (CompositeCell)c); return tcol; } object IColumnContainerBackend.AddColumn (ListViewColumn col) { return AddColumn (col); } public void RemoveColumn (ListViewColumn col, object handle) { Table.RemoveColumn ((NSTableColumn)handle); } public void UpdateColumn (ListViewColumn col, object handle, ListViewColumnChange change) { NSTableColumn tcol = (NSTableColumn) handle; var c = CellUtil.CreateCell (ApplicationContext, Table, this, col.Views, cols.IndexOf (tcol)); tcol.DataCell = c; MapColumn (cols.IndexOf (tcol), col, (CompositeCell)c); } void MapColumn (int colindex, ListViewColumn col, CompositeCell cell) { foreach (var k in cellViews.Where (e => e.Value.Column == colindex).Select (e => e.Key).ToArray ()) cellViews.Remove (k); for (int i = 0; i < col.Views.Count; i++) { var v = col.Views [i]; var r = cell.Cells [i]; cellViews [v] = new CellInfo { Cell = r, Column = colindex }; } } public Rectangle GetCellBounds (int row, CellView cell, bool includeMargin) { var cellInfo = cellViews[cell]; var r = Table.GetCellFrame (cellInfo.Column, row); var container = Table.GetCell (cellInfo.Column, row) as CompositeCell; r = container.GetCellRect (r, (NSCell)cellInfo.Cell); r.Y -= scroll.DocumentVisibleRect.Y; r.X -= scroll.DocumentVisibleRect.X; if (HeadersVisible) r.Y += Table.HeaderView.Frame.Height; return new Rectangle (r.X, r.Y, r.Width, r.Height); } public Rectangle GetRowBounds (int row, bool includeMargin) { var rect = Rectangle.Zero; var columns = Table.TableColumns (); for (int i = 0; i < columns.Length; i++) { var r = Table.GetCellFrame (i, row); if (rect == Rectangle.Zero) rect = new Rectangle (r.X, r.Y, r.Width, r.Height); else rect = rect.Union (new Rectangle (r.X, r.Y, r.Width, r.Height)); } rect.Y -= scroll.DocumentVisibleRect.Y; rect.X -= scroll.DocumentVisibleRect.X; if (HeadersVisible) rect.Y += Table.HeaderView.Frame.Height; return rect; } public void SelectAll () { Table.SelectAll (null); } public void UnselectAll () { Table.DeselectAll (null); } public void ScrollToRow (int row) { Table.ScrollRowToVisible (row); } public abstract object GetValue (object pos, int nField); public abstract void SetValue (object pos, int nField, object value); public abstract void SetCurrentEventRow (object pos); float ICellSource.RowHeight { get { return Table.RowHeight; } set { Table.RowHeight = value; } } public bool BorderVisible { get { return scroll.BorderType == NSBorderType.BezelBorder;} set { scroll.BorderType = value ? NSBorderType.BezelBorder : NSBorderType.NoBorder; } } public bool HeadersVisible { get { return Table.HeaderView != null; } set { if (value) { if (Table.HeaderView == null) Table.HeaderView = new NSTableHeaderView (); } else { Table.HeaderView = null; } } } public GridLines GridLinesVisible { get { return Table.GridStyleMask.ToXwtValue (); } set { Table.GridStyleMask = value.ToMacValue (); } } } class ScrollView: NSScrollView, IViewObject { public ViewBackend Backend { get; set; } public NSView View { get { return this; } } } }
#region Using directives using System; using System.Drawing; using System.Runtime.InteropServices; using System.Windows.Forms; #endregion namespace DotNetControlsEx { [System.Security.SuppressUnmanagedCodeSecurity] [System.Runtime.InteropServices.ComVisible(false)] public sealed class NativeMethods { private NativeMethods() { } #region WindowStyle [Flags] public enum WindowStyle { WS_OVERLAPPED = 0x00000000, WS_POPUP = -2147483648, //0x80000000, WS_CHILD = 0x40000000, WS_MINIMIZE = 0x20000000, WS_VISIBLE = 0x10000000, WS_DISABLED = 0x08000000, WS_CLIPSIBLINGS = 0x04000000, WS_CLIPCHILDREN = 0x02000000, WS_MAXIMIZE = 0x01000000, WS_CAPTION = 0x00C00000, WS_BORDER = 0x00800000, WS_DLGFRAME = 0x00400000, WS_VSCROLL = 0x00200000, WS_HSCROLL = 0x00100000, WS_SYSMENU = 0x00080000, WS_THICKFRAME = 0x00040000, WS_GROUP = 0x00020000, WS_TABSTOP = 0x00010000, WS_MINIMIZEBOX = 0x00020000, WS_MAXIMIZEBOX = 0x00010000, WS_TILED = WS_OVERLAPPED, WS_ICONIC = WS_MINIMIZE, WS_SIZEBOX = WS_THICKFRAME, WS_TILEDWINDOW = WS_OVERLAPPEDWINDOW, WS_OVERLAPPEDWINDOW = (WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX), WS_POPUPWINDOW = (WS_POPUP | WS_BORDER | WS_SYSMENU), WS_CHILDWINDOW = (WS_CHILD) } #endregion //WindowStyle #region WindowStyleEx [Flags] public enum WindowStyleEx { WS_EX_DLGMODALFRAME = 0x00000001, WS_EX_NOPARENTNOTIFY = 0x00000004, WS_EX_TOPMOST = 0x00000008, WS_EX_ACCEPTFILES = 0x00000010, WS_EX_TRANSPARENT = 0x00000020, WS_EX_MDICHILD = 0x00000040, WS_EX_TOOLWINDOW = 0x00000080, WS_EX_WINDOWEDGE = 0x00000100, WS_EX_CLIENTEDGE = 0x00000200, WS_EX_CONTEXTHELP = 0x00000400, WS_EX_RIGHT = 0x00001000, WS_EX_LEFT = 0x00000000, WS_EX_RTLREADING = 0x00002000, WS_EX_LTRREADING = 0x00000000, WS_EX_LEFTSCROLLBAR = 0x00004000, WS_EX_RIGHTSCROLLBAR = 0x00000000, WS_EX_CONTROLPARENT = 0x00010000, WS_EX_STATICEDGE = 0x00020000, WS_EX_APPWINDOW = 0x00040000, WS_EX_OVERLAPPEDWINDOW = (WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE), WS_EX_PALETTEWINDOW = (WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST), WS_EX_LAYERED = 0x00080000, WS_EX_NOINHERITLAYOUT = 0x00100000, // Disable inheritence of mirroring by children WS_EX_LAYOUTRTL = 0x00400000, // Right to left mirroring WS_EX_COMPOSITED = 0x02000000, WS_EX_NOACTIVATE = 0x08000000, } #endregion //WindowStyleEx #region StaticStyle [Flags] public enum StaticStyle { SS_ETCHEDHORZ = 0x00000010, SS_ETCHEDVERT = 0x00000011, } #endregion #region WindowMessages public enum WindowMessages : int { WM_NULL = 0x0000, WM_CREATE = 0x0001, WM_DESTROY = 0x0002, WM_MOVE = 0x0003, WM_SIZE = 0x0005, WM_ACTIVATE = 0x0006, WM_SETFOCUS = 0x0007, WM_KILLFOCUS = 0x0008, WM_ENABLE = 0x000A, WM_SETREDRAW = 0x000B, WM_SETTEXT = 0x000C, WM_GETTEXT = 0x000D, WM_GETTEXTLENGTH = 0x000E, WM_PAINT = 0x000F, WM_CLOSE = 0x0010, WM_QUIT = 0x0012, WM_ERASEBKGND = 0x0014, WM_SYSCOLORCHANGE = 0x0015, WM_SHOWWINDOW = 0x0018, WM_ACTIVATEAPP = 0x001C, WM_SETCURSOR = 0x0020, WM_MOUSEACTIVATE = 0x0021, WM_GETMINMAXINFO = 0x24, WM_WINDOWPOSCHANGING = 0x0046, WM_WINDOWPOSCHANGED = 0x0047, WM_CONTEXTMENU = 0x007B, WM_STYLECHANGING = 0x007C, WM_STYLECHANGED = 0x007D, WM_DISPLAYCHANGE = 0x007E, WM_GETICON = 0x007F, WM_SETICON = 0x0080, // non client area WM_NCCREATE = 0x0081, WM_NCDESTROY = 0x0082, WM_NCCALCSIZE = 0x0083, WM_NCHITTEST = 0x84, WM_NCPAINT = 0x0085, WM_NCACTIVATE = 0x0086, WM_GETDLGCODE = 0x0087, WM_SYNCPAINT = 0x0088, // non client mouse WM_NCMOUSEMOVE = 0x00A0, WM_NCLBUTTONDOWN = 0x00A1, WM_NCLBUTTONUP = 0x00A2, WM_NCLBUTTONDBLCLK = 0x00A3, WM_NCRBUTTONDOWN = 0x00A4, WM_NCRBUTTONUP = 0x00A5, WM_NCRBUTTONDBLCLK = 0x00A6, WM_NCMBUTTONDOWN = 0x00A7, WM_NCMBUTTONUP = 0x00A8, WM_NCMBUTTONDBLCLK = 0x00A9, // keyboard WM_KEYDOWN = 0x0100, WM_KEYUP = 0x0101, WM_CHAR = 0x0102, WM_SYSCOMMAND = 0x0112, // menu WM_INITMENU = 0x0116, WM_INITMENUPOPUP = 0x0117, WM_MENUSELECT = 0x011F, WM_MENUCHAR = 0x0120, WM_ENTERIDLE = 0x0121, WM_MENURBUTTONUP = 0x0122, WM_MENUDRAG = 0x0123, WM_MENUGETOBJECT = 0x0124, WM_UNINITMENUPOPUP = 0x0125, WM_MENUCOMMAND = 0x0126, WM_CHANGEUISTATE = 0x0127, WM_UPDATEUISTATE = 0x0128, WM_QUERYUISTATE = 0x0129, // mouse WM_MOUSEFIRST = 0x0200, WM_MOUSEMOVE = 0x0200, WM_LBUTTONDOWN = 0x0201, WM_LBUTTONUP = 0x0202, WM_LBUTTONDBLCLK = 0x0203, WM_RBUTTONDOWN = 0x0204, WM_RBUTTONUP = 0x0205, WM_RBUTTONDBLCLK = 0x0206, WM_MBUTTONDOWN = 0x0207, WM_MBUTTONUP = 0x0208, WM_MBUTTONDBLCLK = 0x0209, WM_MOUSEWHEEL = 0x020A, WM_MOUSELAST = 0x020D, WM_PARENTNOTIFY = 0x0210, WM_ENTERMENULOOP = 0x0211, WM_EXITMENULOOP = 0x0212, WM_NEXTMENU = 0x0213, WM_SIZING = 0x0214, WM_CAPTURECHANGED = 0x0215, WM_MOVING = 0x0216, WM_ENTERSIZEMOVE = 0x0231, WM_EXITSIZEMOVE = 0x0232, WM_MOUSELEAVE = 0x02A3, WM_MOUSEHOVER = 0x02A1, WM_NCMOUSEHOVER = 0x02A0, WM_NCMOUSELEAVE = 0x02A2, WM_MDIACTIVATE = 0x0222, WM_HSCROLL = 0x0114, WM_VSCROLL = 0x0115, WM_PASTE = 0x0302, WM_PRINT = 0x0317, WM_PRINTCLIENT = 0x0318, } #endregion //WindowMessages #region SystemCommands public enum SystemCommands { SC_SIZE = 0xF000, SC_MOVE = 0xF010, SC_MINIMIZE = 0xF020, SC_MAXIMIZE = 0xF030, SC_MAXIMIZE2 = 0xF032, // fired from double-click on caption SC_NEXTWINDOW = 0xF040, SC_PREVWINDOW = 0xF050, SC_CLOSE = 0xF060, SC_VSCROLL = 0xF070, SC_HSCROLL = 0xF080, SC_MOUSEMENU = 0xF090, SC_KEYMENU = 0xF100, SC_ARRANGE = 0xF110, SC_RESTORE = 0xF120, SC_RESTORE2 = 0xF122, // fired from double-click on caption SC_TASKLIST = 0xF130, SC_SCREENSAVE = 0xF140, SC_HOTKEY = 0xF150, SC_DEFAULT = 0xF160, SC_MONITORPOWER = 0xF170, SC_CONTEXTHELP = 0xF180, SC_SEPARATOR = 0xF00F } #endregion // SystemCommands public enum WindowsHooks { WH_KEYBOARD = 2, WH_MOUSE = 7, WH_KEYBOARD_LL = 13, WH_MOUSE_LL = 14 } public enum States { CBS_NORMAL = 1, CBS_HOT = 2, CBS_PUSHED = 3 } internal enum WINDOWPARTS { WP_CAPTION = 1, WP_SMALLCAPTION = 2, WP_MINCAPTION = 3, WP_SMALLMINCAPTION = 4, WP_MAXCAPTION = 5, WP_SMALLMAXCAPTION = 6, WP_FRAMELEFT = 7, WP_FRAMERIGHT = 8, WP_FRAMEBOTTOM = 9, WP_SMALLFRAMELEFT = 10, WP_SMALLFRAMERIGHT = 11, WP_SMALLFRAMEBOTTOM = 12, WP_SYSBUTTON = 13, WP_MDISYSBUTTON = 14, WP_MINBUTTON = 15, WP_MDIMINBUTTON = 16, WP_MAXBUTTON = 17, WP_CLOSEBUTTON = 18, WP_SMALLCLOSEBUTTON = 19, WP_MDICLOSEBUTTON = 20, WP_RESTOREBUTTON = 21, WP_MDIRESTOREBUTTON = 22, WP_HELPBUTTON = 23, WP_MDIHELPBUTTON = 24, WP_HORZSCROLL = 25, WP_HORZTHUMB = 26, WP_VERTSCROLL = 27, WP_VERTTHUMB = 28, WP_DIALOG = 29, WP_CAPTIONSIZINGTEMPLATE = 30, WP_SMALLCAPTIONSIZINGTEMPLATE = 31, WP_FRAMELEFTSIZINGTEMPLATE = 32, WP_SMALLFRAMELEFTSIZINGTEMPLATE = 33, WP_FRAMERIGHTSIZINGTEMPLATE = 34, WP_SMALLFRAMERIGHTSIZINGTEMPLATE = 35, WP_FRAMEBOTTOMSIZINGTEMPLATE = 36, WP_SMALLFRAMEBOTTOMSIZINGTEMPLATE = 37, }; #region PeekMessageOptions [Flags] public enum PeekMessageOptions { PM_NOREMOVE = 0x0000, PM_REMOVE = 0x0001, PM_NOYIELD = 0x0002 } #endregion // PeekMessageOptions #region NCHITTEST enum /// <summary> /// Location of cursor hot spot returnet in WM_NCHITTEST. /// </summary> public enum NCHITTEST { /// <summary> /// On the screen background or on a dividing line between windows /// (same as HTNOWHERE, except that the DefWindowProc function produces a system beep to indicate an error). /// </summary> HTERROR = (-2), /// <summary> /// In a window currently covered by another window in the same thread /// (the message will be sent to underlying windows in the same thread until one of them returns a code that is not HTTRANSPARENT). /// </summary> HTTRANSPARENT = (-1), /// <summary> /// On the screen background or on a dividing line between windows. /// </summary> HTNOWHERE = 0, /// <summary>In a client area.</summary> HTCLIENT = 1, /// <summary>In a title bar.</summary> HTCAPTION = 2, /// <summary>In a window menu or in a Close button in a child window.</summary> HTSYSMENU = 3, /// <summary>In a size box (same as HTSIZE).</summary> HTGROWBOX = 4, /// <summary>In a menu.</summary> HTMENU = 5, /// <summary>In a horizontal scroll bar.</summary> HTHSCROLL = 6, /// <summary>In the vertical scroll bar.</summary> HTVSCROLL = 7, /// <summary>In a Minimize button.</summary> HTMINBUTTON = 8, /// <summary>In a Maximize button.</summary> HTMAXBUTTON = 9, /// <summary>In the left border of a resizable window /// (the user can click the mouse to resize the window horizontally).</summary> HTLEFT = 10, /// <summary> /// In the right border of a resizable window /// (the user can click the mouse to resize the window horizontally). /// </summary> HTRIGHT = 11, /// <summary>In the upper-horizontal border of a window.</summary> HTTOP = 12, /// <summary>In the upper-left corner of a window border.</summary> HTTOPLEFT = 13, /// <summary>In the upper-right corner of a window border.</summary> HTTOPRIGHT = 14, /// <summary> In the lower-horizontal border of a resizable window /// (the user can click the mouse to resize the window vertically).</summary> HTBOTTOM = 15, /// <summary>In the lower-left corner of a border of a resizable window /// (the user can click the mouse to resize the window diagonally).</summary> HTBOTTOMLEFT = 16, /// <summary> In the lower-right corner of a border of a resizable window /// (the user can click the mouse to resize the window diagonally).</summary> HTBOTTOMRIGHT = 17, /// <summary>In the border of a window that does not have a sizing border.</summary> HTBORDER = 18, HTOBJECT = 19, /// <summary>In a Close button.</summary> HTCLOSE = 20, /// <summary>In a Help button.</summary> HTHELP = 21, } #endregion //NCHITTEST #region DCX enum [Flags()] internal enum DCX { DCX_CACHE = 0x2, DCX_CLIPCHILDREN = 0x8, DCX_CLIPSIBLINGS = 0x10, DCX_EXCLUDERGN = 0x40, DCX_EXCLUDEUPDATE = 0x100, DCX_INTERSECTRGN = 0x80, DCX_INTERSECTUPDATE = 0x200, DCX_LOCKWINDOWUPDATE = 0x400, DCX_NORECOMPUTE = 0x100000, DCX_NORESETATTRS = 0x4, DCX_PARENTCLIP = 0x20, DCX_VALIDATE = 0x200000, DCX_WINDOW = 0x1, } #endregion //DCX #region ShowWindow flags [Flags] public enum ShowWindowOptions : int { SW_HIDE = 0, SW_SHOWNOACTIVATE = 4, } #endregion #region SetWindowPosition flags [Flags] public enum SetWindowPosOptions { SWP_NOSIZE = 0x0001, SWP_NOMOVE = 0x0002, SWP_NOZORDER = 0x0004, SWP_NOACTIVATE = 0x0010, SWP_FRAMECHANGED = 0x0020, /* The frame changed: send WM_NCCALCSIZE */ SWP_SHOWWINDOW = 0x0040, SWP_HIDEWINDOW = 0x0080, SWP_NOCOPYBITS = 0x0100, SWP_NOOWNERZORDER = 0x0200, /* Don't do owner Z ordering */ SWP_NOSENDCHANGING = 0x0400 /* Don't send WM_WINDOWPOSCHANGING */ } #endregion #region RedrawWindow flags [Flags] public enum RedrawWindowOptions { RDW_INVALIDATE = 0x0001, RDW_INTERNALPAINT = 0x0002, RDW_ERASE = 0x0004, RDW_VALIDATE = 0x0008, RDW_NOINTERNALPAINT = 0x0010, RDW_NOERASE = 0x0020, RDW_NOCHILDREN = 0x0040, RDW_ALLCHILDREN = 0x0080, RDW_UPDATENOW = 0x0100, RDW_ERASENOW = 0x0200, RDW_FRAME = 0x0400, RDW_NOFRAME = 0x0800 } #endregion #region RECT structure [StructLayout(LayoutKind.Sequential)] public struct RECT { public int left; public int top; public int right; public int bottom; public RECT(int left, int top, int right, int bottom) { this.left = left; this.top = top; this.right = right; this.bottom = bottom; } public Rectangle Rect { get { return new Rectangle(this.left, this.top, this.right - this.left, this.bottom - this.top); } } public static RECT FromXYWH(int x, int y, int width, int height) { return new RECT(x, y, x + width, y + height); } public static RECT FromRectangle(Rectangle rect) { return new RECT(rect.Left, rect.Top, rect.Right, rect.Bottom); } } #endregion RECT structure #region WINDOWPOS [StructLayout(LayoutKind.Sequential)] public struct WINDOWPOS { internal IntPtr hwnd; internal IntPtr hWndInsertAfter; internal int x; internal int y; internal int cx; internal int cy; internal uint flags; } #endregion //WINDOWPOS #region NCCALCSIZE_PARAMS //http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/windows/windowreference/windowstructures/nccalcsize_params.asp [StructLayout(LayoutKind.Sequential)] public struct NCCALCSIZE_PARAMS { /// <summary> /// Contains the new coordinates of a window that has been moved or resized, that is, it is the proposed new window coordinates. /// </summary> public RECT rectProposed; /// <summary> /// Contains the coordinates of the window before it was moved or resized. /// </summary> public RECT rectBeforeMove; /// <summary> /// Contains the coordinates of the window's client area before the window was moved or resized. /// </summary> public RECT rectClientBeforeMove; /// <summary> /// Pointer to a WINDOWPOS structure that contains the size and position values specified in the operation that moved or resized the window. /// </summary> public WINDOWPOS lpPos; } #endregion //NCCALCSIZE_PARAMS #region TRACKMOUSEEVENT structure [StructLayout(LayoutKind.Sequential)] public class TRACKMOUSEEVENT { public TRACKMOUSEEVENT() { this.cbSize = Marshal.SizeOf(typeof(NativeMethods.TRACKMOUSEEVENT)); this.dwHoverTime = 100; } public int cbSize; public int dwFlags; public IntPtr hwndTrack; public int dwHoverTime; } #endregion #region TrackMouseEventFalgs enum [Flags] public enum TrackMouseEventFalgs { TME_HOVER = 1, TME_LEAVE = 2, TME_NONCLIENT = 0x00000010 } #endregion public enum TernaryRasterOperations { SRCCOPY = 0x00CC0020, /* dest = source*/ SRCPAINT = 0x00EE0086, /* dest = source OR dest*/ SRCAND = 0x008800C6, /* dest = source AND dest*/ SRCINVERT = 0x00660046, /* dest = source XOR dest*/ SRCERASE = 0x00440328, /* dest = source AND (NOT dest )*/ NOTSRCCOPY = 0x00330008, /* dest = (NOT source)*/ NOTSRCERASE = 0x001100A6, /* dest = (NOT src) AND (NOT dest) */ MERGECOPY = 0x00C000CA, /* dest = (source AND pattern)*/ MERGEPAINT = 0x00BB0226, /* dest = (NOT source) OR dest*/ PATCOPY = 0x00F00021, /* dest = pattern*/ PATPAINT = 0x00FB0A09, /* dest = DPSnoo*/ PATINVERT = 0x005A0049, /* dest = pattern XOR dest*/ DSTINVERT = 0x00550009, /* dest = (NOT dest)*/ BLACKNESS = 0x00000042, /* dest = BLACK*/ WHITENESS = 0x00FF0062, /* dest = WHITE*/ }; public delegate Int32 HOOKPROC(Int32 nCode, Int32 wParam, IntPtr lParam); public static readonly IntPtr TRUE = new IntPtr(1); public static readonly IntPtr FALSE = new IntPtr(0); public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1); public static readonly Int32 HC_ACTION = 0; [DllImport("user32.dll")] public static extern Int32 SetWindowsHookEx(Int32 idHook, HOOKPROC lpfn, IntPtr hMod, uint dwThreadId); [DllImport("user32.dll")] public static extern Int32 CallNextHookEx(Int32 idHook, Int32 nCode, Int32 wParam, IntPtr lParam); [DllImport("user32.dll")] public static extern bool UnhookWindowsHookEx(Int32 idHook); [DllImport("UxTheme.dll")] public static extern Int32 IsThemeActive(); [DllImport("UxTheme.dll")] public static extern IntPtr OpenThemeData(IntPtr hWnd, [MarshalAs(UnmanagedType.LPTStr)] string classList); [DllImport("UxTheme.dll")] public static extern void CloseThemeData(IntPtr hTheme); [DllImport("UxTheme.dll")] public static extern void DrawThemeBackground(IntPtr hTheme, IntPtr hDC, Int32 partId, Int32 stateId, ref RECT rect, ref RECT clipRect); [DllImport("user32.dll")] public static extern IntPtr GetDesktopWindow(); [DllImport("user32.dll")] public static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hParent); [DllImport("user32.dll")] public static extern Int32 SetWindowLong(IntPtr hWnd, Int32 Offset, Int32 newLong); [DllImport("user32.dll")] public static extern Int32 GetWindowLong(IntPtr hWnd, Int32 Offset); [DllImport("user32.dll")] public static extern Int32 ShowWindow(IntPtr hWnd, Int32 dwFlags); [DllImport("user32.dll")] public static extern Int32 SetWindowPos(IntPtr hWnd, IntPtr hWndAfter, Int32 x, Int32 y, Int32 cx, Int32 cy, UInt32 uFlags); [DllImport("user32.dll")] public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll")] public static extern bool PeekMessage(ref Message msg, IntPtr hwnd, int msgMin, int msgMax, int remove); [DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, int flags); [DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr hWnd, Int32 hWndInsertAfter, Int32 X, Int32 Y, Int32 cx, Int32 cy, uint uFlags); [DllImport("user32.dll")] public static extern bool RedrawWindow(IntPtr hWnd, IntPtr rectUpdate, IntPtr hrgnUpdate, uint flags); [DllImport("user32.dll")] public static extern IntPtr GetDCEx(IntPtr hwnd, IntPtr hrgnclip, uint fdwOptions); [DllImport("user32.dll")] public static extern IntPtr GetWindowDC(IntPtr hwnd); [DllImport("user32.dll")] public static extern int ReleaseDC(IntPtr hwnd, IntPtr hDC); [DllImport("user32.dll")] public static extern int GetWindowRect(IntPtr hwnd, ref RECT lpRect); [DllImport("user32.dll")] public static extern void DisableProcessWindowsGhosting(); [DllImport("user32.dll")] public static extern short GetAsyncKeyState(int nVirtKey); public const int VK_LBUTTON = 0x01; public const int VK_RBUTTON = 0x02; [DllImport("uxtheme.dll")] public static extern int SetWindowTheme(IntPtr hwnd, String pszSubAppName, String pszSubIdList); [DllImport("comctl32.dll", SetLastError = true)] private static extern bool _TrackMouseEvent(TRACKMOUSEEVENT tme); public static bool TrackMouseEvent(TRACKMOUSEEVENT tme) { return _TrackMouseEvent(tme); } public static int GetLastError() { return System.Runtime.InteropServices.Marshal.GetLastWin32Error(); } [DllImport("gdi32.dll")] public static extern IntPtr CreateCompatibleDC(IntPtr hDC); [DllImport("gdi32.dll")] public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int nWidth, int nHeight); [DllImport("gdi32.dll")] public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject); [DllImport("gdi32.dll")] public static extern bool BitBlt(IntPtr hObject, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hObjSource, int nXSrc, int nYSrc, TernaryRasterOperations dwRop); [DllImport("gdi32.dll")] public static extern bool DeleteObject(IntPtr hObject); [DllImport("gdi32.dll")] public static extern bool DeleteDC(IntPtr hDC); #region AppBarInfo [StructLayout(LayoutKind.Sequential)] public struct APPBARDATA { public System.UInt32 cbSize; public System.IntPtr hWnd; public System.UInt32 uCallbackMessage; public System.UInt32 uEdge; public RECT rc; public System.Int32 lParam; } [DllImport("user32.dll")] public static extern System.IntPtr FindWindow(String lpClassName, String lpWindowName); [DllImport("shell32.dll")] public static extern System.UInt32 SHAppBarMessage(System.UInt32 dwMessage, ref APPBARDATA data); [DllImport("user32.dll")] public static extern System.Int32 SystemParametersInfo(System.UInt32 uiAction, System.UInt32 uiParam, System.IntPtr pvParam, System.UInt32 fWinIni); public class AppBarInfo { private APPBARDATA m_data; // Appbar messages private const int ABM_NEW = 0x00000000; private const int ABM_REMOVE = 0x00000001; private const int ABM_QUERYPOS = 0x00000002; private const int ABM_SETPOS = 0x00000003; private const int ABM_GETSTATE = 0x00000004; private const int ABM_GETTASKBARPOS = 0x00000005; private const int ABM_ACTIVATE = 0x00000006; // lParam == TRUE/FALSE means activate/deactivate private const int ABM_GETAUTOHIDEBAR = 0x00000007; private const int ABM_SETAUTOHIDEBAR = 0x00000008; // Appbar edge constants private const int ABE_LEFT = 0; private const int ABE_TOP = 1; private const int ABE_RIGHT = 2; private const int ABE_BOTTOM = 3; // SystemParametersInfo constants private const System.UInt32 SPI_GETWORKAREA = 0x0030; public enum ScreenEdge { Undefined = -1, Left = ABE_LEFT, Top = ABE_TOP, Right = ABE_RIGHT, Bottom = ABE_BOTTOM } public ScreenEdge Edge { get { return (ScreenEdge)m_data.uEdge; } } public Rectangle WorkArea { get { Int32 bResult = 0; RECT rc = new RECT(); IntPtr rawRect = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(rc)); bResult = SystemParametersInfo(SPI_GETWORKAREA, 0, rawRect, 0); rc = (RECT)System.Runtime.InteropServices.Marshal.PtrToStructure(rawRect, rc.GetType()); if (bResult == 1) { System.Runtime.InteropServices.Marshal.FreeHGlobal(rawRect); return new Rectangle(rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top); } return new Rectangle(0, 0, 0, 0); } } public void GetPosition(string strClassName, string strWindowName) { m_data = new APPBARDATA(); m_data.cbSize = (UInt32)System.Runtime.InteropServices.Marshal.SizeOf(m_data.GetType()); IntPtr hWnd = FindWindow(strClassName, strWindowName); if (hWnd != IntPtr.Zero) { UInt32 uResult = SHAppBarMessage(ABM_GETTASKBARPOS, ref m_data); if (uResult == 1) { } else { throw new Exception("Failed to communicate with the given AppBar"); } } else { throw new Exception("Failed to find an AppBar that matched the given criteria"); } } public void GetSystemTaskBarPosition() { GetPosition("Shell_TrayWnd", null); } } #endregion } }
using Microsoft.TeamFoundation.DistributedTask.WebApi; using Microsoft.VisualStudio.Services.Agent.Util; using Microsoft.VisualStudio.Services.Agent.Worker.Handlers; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Microsoft.VisualStudio.Services.Agent.Worker { [ServiceLocator(Default = typeof(TaskManager))] public interface ITaskManager : IAgentService { Task DownloadAsync(IExecutionContext executionContext, IEnumerable<TaskInstance> tasks); Definition Load(TaskReference task); } public sealed class TaskManager : AgentService, ITaskManager { private async Task DownloadAsync(IExecutionContext executionContext, TaskReference task) { Trace.Entering(); ArgUtil.NotNull(executionContext, nameof(executionContext)); ArgUtil.NotNull(task, nameof(task)); ArgUtil.NotNullOrEmpty(task.Version, nameof(task.Version)); var taskServer = HostContext.GetService<ITaskServer>(); // first check to see if we already have the task string destDirectory = GetDirectory(task); Trace.Info($"Ensuring task exists: ID '{task.Id}', version '{task.Version}', name '{task.Name}', directory '{destDirectory}'."); if (Directory.Exists(destDirectory)) { Trace.Info("Task already downloaded."); return; } Trace.Info("Getting task."); string zipFile; var version = new TaskVersion(task.Version); //download and extract task in a temp folder and rename it on success string tempDirectory = Path.Combine(IOUtil.GetTasksPath(HostContext), "_temp_" + Guid.NewGuid()); try { Directory.CreateDirectory(tempDirectory); zipFile = Path.Combine(tempDirectory, string.Format("{0}.zip", Guid.NewGuid())); //open zip stream in async mode using (FileStream fs = new FileStream(zipFile, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true)) { using (Stream result = await taskServer.GetTaskContentZipAsync(task.Id, version, executionContext.CancellationToken)) { //81920 is the default used by System.IO.Stream.CopyTo and is under the large object heap threshold (85k). await result.CopyToAsync(fs, 81920, executionContext.CancellationToken); await fs.FlushAsync(executionContext.CancellationToken); } } ZipFile.ExtractToDirectory(zipFile, tempDirectory); File.Delete(zipFile); Directory.CreateDirectory(Path.GetDirectoryName(destDirectory)); Directory.Move(tempDirectory, destDirectory); Trace.Info("Finished getting task."); } finally { try { //if the temp folder wasn't moved -> wipe it if (Directory.Exists(tempDirectory)) { Trace.Verbose("Deleting task temp folder: {0}", tempDirectory); IOUtil.DeleteDirectory(tempDirectory, CancellationToken.None); // Don't cancel this cleanup and should be pretty fast. } } catch (Exception ex) { //it is not critical if we fail to delete the temp folder Trace.Warning("Failed to delete temp folder '{0}'. Exception: {1}", tempDirectory, ex); executionContext.Warning(StringUtil.Loc("FailedDeletingTempDirectory0Message1", tempDirectory, ex.Message)); } } } private string GetDirectory(TaskReference task) { ArgUtil.NotEmpty(task.Id, nameof(task.Id)); ArgUtil.NotNull(task.Name, nameof(task.Name)); ArgUtil.NotNullOrEmpty(task.Version, nameof(task.Version)); return Path.Combine( IOUtil.GetTasksPath(HostContext), $"{task.Name}_{task.Id}", task.Version); } public async Task DownloadAsync(IExecutionContext executionContext, IEnumerable<TaskInstance> tasks) { ArgUtil.NotNull(executionContext, nameof(executionContext)); ArgUtil.NotNull(tasks, nameof(tasks)); //remove duplicate and disabled tasks IEnumerable<TaskInstance> uniqueTasks = from task in tasks where task.Enabled group task by new { task.Id, task.Version } into taskGrouping select taskGrouping.First(); foreach (TaskInstance task in uniqueTasks) { await DownloadAsync(executionContext, task); } } public Definition Load(TaskReference task) { // Validate args. Trace.Entering(); ArgUtil.NotNull(task, nameof(task)); // Initialize the definition wrapper object. var definition = new Definition() { Directory = GetDirectory(task) }; // Deserialize the JSON. string file = Path.Combine(definition.Directory, Constants.Path.TaskJsonFile); Trace.Info($"Loading task definition '{file}'."); string json = File.ReadAllText(file); definition.Data = JsonConvert.DeserializeObject<DefinitionData>(json); // Replace the macros within the handler data sections. foreach (HandlerData handlerData in (definition.Data?.Execution?.All as IEnumerable<HandlerData> ?? new HandlerData[0])) { handlerData?.ReplaceMacros(HostContext, definition); } return definition; } } public sealed class Definition { public DefinitionData Data { get; set; } public string Directory { get; set; } } public sealed class DefinitionData { public TaskInputDefinition[] Inputs { get; set; } public ExecutionData Execution { get; set; } } public sealed class ExecutionData { private readonly List<HandlerData> _all = new List<HandlerData>(); private AzurePowerShellHandlerData _azurePowerShell; private NodeHandlerData _node; private PowerShellHandlerData _powerShell; private PowerShell3HandlerData _powerShell3; private PowerShellExeHandlerData _powerShellExe; private ProcessHandlerData _process; [JsonIgnore] public List<HandlerData> All => _all; #if !OS_WINDOWS [JsonIgnore] #endif public AzurePowerShellHandlerData AzurePowerShell { get { return _azurePowerShell; } set { _azurePowerShell = value; Add(value); } } public NodeHandlerData Node { get { return _node; } set { _node = value; Add(value); } } #if !OS_WINDOWS [JsonIgnore] #endif public PowerShellHandlerData PowerShell { get { return _powerShell; } set { _powerShell = value; Add(value); } } #if !OS_WINDOWS [JsonIgnore] #endif public PowerShell3HandlerData PowerShell3 { get { return _powerShell3; } set { _powerShell3 = value; Add(value); } } #if !OS_WINDOWS [JsonIgnore] #endif public PowerShellExeHandlerData PowerShellExe { get { return _powerShellExe; } set { _powerShellExe = value; Add(value); } } #if !OS_WINDOWS [JsonIgnore] #endif public ProcessHandlerData Process { get { return _process; } set { _process = value; Add(value); } } private void Add(HandlerData data) { if (data != null) { _all.Add(data); } } } public abstract class HandlerData { public Dictionary<string, string> Inputs { get; } public string[] Platforms { get; set; } [JsonIgnore] public abstract int Priority { get; } public string Target { get { return GetInput(nameof(Target)); } set { SetInput(nameof(Target), value); } } public HandlerData() { Inputs = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); } public bool PreferredOnCurrentPlatform() { #if OS_WINDOWS const string CurrentPlatform = "windows"; return Platforms?.Any(x => string.Equals(x, CurrentPlatform, StringComparison.OrdinalIgnoreCase)) ?? false; #else return false; #endif } public void ReplaceMacros(IHostContext context, Definition definition) { var handlerVariables = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); handlerVariables["currentdirectory"] = definition.Directory; VarUtil.ExpandValues(context, source: handlerVariables, target: Inputs); } protected string GetInput(string name) { string value; if (Inputs.TryGetValue(name, out value)) { return value ?? string.Empty; } return string.Empty; } protected void SetInput(string name, string value) { Inputs[name] = value; } } public sealed class NodeHandlerData : HandlerData { public override int Priority => 1; public string WorkingDirectory { get { return GetInput(nameof(WorkingDirectory)); } set { SetInput(nameof(WorkingDirectory), value); } } } public sealed class PowerShell3HandlerData : HandlerData { public override int Priority => 2; } public sealed class PowerShellHandlerData : HandlerData { public string ArgumentFormat { get { return GetInput(nameof(ArgumentFormat)); } set { SetInput(nameof(ArgumentFormat), value); } } public override int Priority => 3; public string WorkingDirectory { get { return GetInput(nameof(WorkingDirectory)); } set { SetInput(nameof(WorkingDirectory), value); } } } public sealed class AzurePowerShellHandlerData : HandlerData { public string ArgumentFormat { get { return GetInput(nameof(ArgumentFormat)); } set { SetInput(nameof(ArgumentFormat), value); } } public override int Priority => 4; public string WorkingDirectory { get { return GetInput(nameof(WorkingDirectory)); } set { SetInput(nameof(WorkingDirectory), value); } } } public sealed class PowerShellExeHandlerData : HandlerData { public string ArgumentFormat { get { return GetInput(nameof(ArgumentFormat)); } set { SetInput(nameof(ArgumentFormat), value); } } public string FailOnStandardError { get { return GetInput(nameof(FailOnStandardError)); } set { SetInput(nameof(FailOnStandardError), value); } } public string InlineScript { get { return GetInput(nameof(InlineScript)); } set { SetInput(nameof(InlineScript), value); } } public override int Priority => 5; public string ScriptType { get { return GetInput(nameof(ScriptType)); } set { SetInput(nameof(ScriptType), value); } } public string WorkingDirectory { get { return GetInput(nameof(WorkingDirectory)); } set { SetInput(nameof(WorkingDirectory), value); } } } public sealed class ProcessHandlerData : HandlerData { public string ArgumentFormat { get { return GetInput(nameof(ArgumentFormat)); } set { SetInput(nameof(ArgumentFormat), value); } } public string ModifyEnvironment { get { return GetInput(nameof(ModifyEnvironment)); } set { SetInput(nameof(ModifyEnvironment), value); } } public override int Priority => 6; public string WorkingDirectory { get { return GetInput(nameof(WorkingDirectory)); } set { SetInput(nameof(WorkingDirectory), value); } } } }
using System; using System.Threading.Tasks; using System.Windows.Input; namespace Dependinator.Utils.UI.Mvvm { public class Command : ICommand { private Command<object> command; public Command(Action executeMethod, string memberName) { SetCommand(executeMethod, memberName); } public Command(Action executeMethod, Func<bool> canExecuteMethod, string memberName) { SetCommand(executeMethod, canExecuteMethod, memberName); } public Command(Func<Task> executeMethodAsync, string memberName) { SetCommand(executeMethodAsync, memberName); } public Command(Func<Task> executeMethodAsync, Func<bool> canExecuteMethod, string memberName) { SetCommand(executeMethodAsync, canExecuteMethod, memberName); } protected Command() { SetCommand(RunAsync, CanRun, GetType().FullName); } public event EventHandler CanExecuteChanged { add { command.CanExecuteChanged += value; } remove { command.CanExecuteChanged -= value; } } bool ICommand.CanExecute(object parameter) { return CanExecute(); } void ICommand.Execute(object parameter) { Execute(); } public bool CanExecute() { return command.CanExecute(null); } public void Execute() { command.Execute(null); } public Task ExecuteAsync() { return command.ExecuteAsync(null); } public void RaiseCanExecuteChanaged() { command.RaiseCanExecuteChanaged(); } private void SetCommand(Action executeMethod, string memberName) { command = new Command<object>(_ => executeMethod(), memberName); } private void SetCommand(Action executeMethod, Func<bool> canExecuteMethod, string memberName) { command = new Command<object>(_ => executeMethod(), _ => canExecuteMethod(), memberName); } private void SetCommand(Func<Task> executeMethodAsync, string memberName) { command = new Command<object>(_ => executeMethodAsync(), memberName); } private void SetCommand(Func<Task> executeMethodAsync, Func<bool> canExecuteMethod, string memberName) { command = new Command<object>(_ => executeMethodAsync(), _ => canExecuteMethod(), memberName); } protected virtual Task RunAsync() { return Task.CompletedTask; } protected virtual bool CanRun() { return true; } } public class Command<T> : ICommand { private readonly Action<T> executeMethod; private bool canExecute = true; private Func<T, bool> canExecuteMethod; private Func<T, Task> executeMethodAsync; private string memberName; protected Command() { SetCommand(RunAsync, CanRun, GetType().FullName); } public Command(Action<T> executeMethod, string memberName) { Asserter.NotNull(executeMethod); this.executeMethod = executeMethod; this.memberName = memberName; } public Command(Action<T> executeMethod, Func<T, bool> canExecuteMethod, string memberName) { Asserter.NotNull(executeMethod); Asserter.NotNull(canExecuteMethod); this.executeMethod = executeMethod; this.canExecuteMethod = canExecuteMethod; this.memberName = memberName; } public Command(Func<T, Task> executeMethodAsync, string memberName) { SetCommand(executeMethodAsync, memberName); } public Command( Func<T, Task> executeMethodAsync, Func<T, bool> canExecuteMethod, string memberName) { Asserter.NotNull(executeMethodAsync); Asserter.NotNull(canExecuteMethod); this.executeMethodAsync = executeMethodAsync; this.canExecuteMethod = canExecuteMethod; this.memberName = memberName; } public bool IsCompleted { get; private set; } public bool IsNotCompleted => !IsCompleted; // NOTE: Should use weak event if command instance is longer than UI object //public event EventHandler CanExecuteChanged; public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } bool ICommand.CanExecute(object parameter) { return CanExecute((T)parameter); } void ICommand.Execute(object parameter) { Execute((T)parameter); } private void SetCommand(Func<T, Task> methodAsync, Func<T, bool> canRun, string name) { Asserter.NotNull(methodAsync); Asserter.NotNull(canExecute); executeMethodAsync = methodAsync; canExecuteMethod = canRun; memberName = name; } private void SetCommand(Func<T, Task> methodAsync, string name) { Asserter.NotNull(methodAsync); executeMethodAsync = methodAsync; memberName = name; } public Command With(Func<T> parameterFunc) { Command cmd = new Command(() => Execute(parameterFunc()), () => CanExecute(parameterFunc()), memberName); //CanExecuteChanged += (s, e) => cmd.RaiseCanExecuteChanaged(); return cmd; } public bool CanExecute(T parameter) { if (canExecuteMethod != null) { return canExecuteMethod(parameter); } return canExecute; } public async void Execute(T parameter) { await ExecuteAsync(parameter); } public void RaiseCanExecuteChanaged() { CommandManager.InvalidateRequerySuggested(); } public async Task ExecuteAsync(T parameter) { try { IsCompleted = false; canExecute = false; RaiseCanExecuteChanaged(); Log.Usage(memberName); if (executeMethod != null) { // Sync command executeMethod(parameter); } else { // Async command await executeMethodAsync(parameter); } } catch (Exception e) when (e.IsNotFatal()) { Asserter.FailFast($"Unhandled command exception {e}"); } finally { IsCompleted = false; canExecute = true; RaiseCanExecuteChanaged(); } } protected virtual Task RunAsync(T parameter) { return Task.CompletedTask; } protected virtual bool CanRun(T parameter) { return true; } } }
namespace EIDSS.FlexibleForms { partial class FFParameterTypesEditor { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FFParameterTypesEditor)); this.panelControl1 = new DevExpress.XtraEditors.PanelControl(); this.gcParameterTypes = new DevExpress.XtraGrid.GridControl(); this.gvParameterTypes = new DevExpress.XtraGrid.Views.Grid.GridView(); this.colParameterTypeDefaultName = new DevExpress.XtraGrid.Columns.GridColumn(); this.colParameterTypeNationalName = new DevExpress.XtraGrid.Columns.GridColumn(); this.colParameterTypeSystem = new DevExpress.XtraGrid.Columns.GridColumn(); this.icbParameterTypeSystem = new DevExpress.XtraEditors.Repository.RepositoryItemImageComboBox(); this.imglst = new DevExpress.Utils.ImageCollection(this.components); this.barManager1 = new DevExpress.XtraBars.BarManager(this.components); this.barParameterTypes = new DevExpress.XtraBars.Bar(); this.btnAddParameterType = new DevExpress.XtraBars.BarButtonItem(); this.btnRemoveParameterType = new DevExpress.XtraBars.BarButtonItem(); this.standaloneBarDockControl1 = new DevExpress.XtraBars.StandaloneBarDockControl(); this.barFixedePresetValues = new DevExpress.XtraBars.Bar(); this.btnAddFixedPresetValue = new DevExpress.XtraBars.BarButtonItem(); this.btnRemoveFixedPresetValue = new DevExpress.XtraBars.BarButtonItem(); this.btnUp = new DevExpress.XtraBars.BarButtonItem(); this.btnDown = new DevExpress.XtraBars.BarButtonItem(); this.standaloneBarDockControl2 = new DevExpress.XtraBars.StandaloneBarDockControl(); this.barDockControlTop = new DevExpress.XtraBars.BarDockControl(); this.barDockControlBottom = new DevExpress.XtraBars.BarDockControl(); this.barDockControlLeft = new DevExpress.XtraBars.BarDockControl(); this.barDockControlRight = new DevExpress.XtraBars.BarDockControl(); this.panelControl2 = new DevExpress.XtraEditors.PanelControl(); this.gcFixedPresetValues = new DevExpress.XtraGrid.GridControl(); this.gvFixedPresetValues = new DevExpress.XtraGrid.Views.Grid.GridView(); this.colFixedPresetValueDefaultName = new DevExpress.XtraGrid.Columns.GridColumn(); this.colcolFixedPresetValueNationalName = new DevExpress.XtraGrid.Columns.GridColumn(); this.pnlReferenceType = new DevExpress.XtraEditors.PanelControl(); this.leReferenceType = new DevExpress.XtraEditors.LookUpEdit(); this.labelControl1 = new DevExpress.XtraEditors.LabelControl(); this.splitterControl1 = new DevExpress.XtraEditors.SplitterControl(); this.bar2 = new DevExpress.XtraBars.Bar(); ((System.ComponentModel.ISupportInitialize)(this.panelControl1)).BeginInit(); this.panelControl1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.gcParameterTypes)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.gvParameterTypes)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.icbParameterTypeSystem)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.imglst)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barManager1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.panelControl2)).BeginInit(); this.panelControl2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.gcFixedPresetValues)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.gvFixedPresetValues)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pnlReferenceType)).BeginInit(); this.pnlReferenceType.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.leReferenceType.Properties)).BeginInit(); this.SuspendLayout(); // // panelControl1 // this.panelControl1.Controls.Add(this.gcParameterTypes); this.panelControl1.Controls.Add(this.standaloneBarDockControl1); resources.ApplyResources(this.panelControl1, "panelControl1"); this.panelControl1.Name = "panelControl1"; // // gcParameterTypes // resources.ApplyResources(this.gcParameterTypes, "gcParameterTypes"); this.gcParameterTypes.MainView = this.gvParameterTypes; this.gcParameterTypes.MenuManager = this.barManager1; this.gcParameterTypes.Name = "gcParameterTypes"; this.gcParameterTypes.RepositoryItems.AddRange(new DevExpress.XtraEditors.Repository.RepositoryItem[] { this.icbParameterTypeSystem}); this.gcParameterTypes.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] { this.gvParameterTypes}); // // gvParameterTypes // this.gvParameterTypes.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] { this.colParameterTypeDefaultName, this.colParameterTypeNationalName, this.colParameterTypeSystem}); this.gvParameterTypes.GridControl = this.gcParameterTypes; this.gvParameterTypes.Name = "gvParameterTypes"; this.gvParameterTypes.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.False; this.gvParameterTypes.OptionsBehavior.AllowDeleteRows = DevExpress.Utils.DefaultBoolean.False; this.gvParameterTypes.OptionsCustomization.AllowColumnMoving = false; this.gvParameterTypes.OptionsCustomization.AllowFilter = false; this.gvParameterTypes.OptionsDetail.ShowDetailTabs = false; this.gvParameterTypes.OptionsDetail.SmartDetailExpand = false; this.gvParameterTypes.OptionsNavigation.EnterMoveNextColumn = true; this.gvParameterTypes.OptionsView.ShowGroupPanel = false; this.gvParameterTypes.FocusedRowChanged += new DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventHandler(this.OnGvParameterTypesFocusedRowChanged); // // colParameterTypeDefaultName // resources.ApplyResources(this.colParameterTypeDefaultName, "colParameterTypeDefaultName"); this.colParameterTypeDefaultName.FieldName = "DefaultName"; this.colParameterTypeDefaultName.Name = "colParameterTypeDefaultName"; // // colParameterTypeNationalName // resources.ApplyResources(this.colParameterTypeNationalName, "colParameterTypeNationalName"); this.colParameterTypeNationalName.FieldName = "NationalName"; this.colParameterTypeNationalName.Name = "colParameterTypeNationalName"; // // colParameterTypeSystem // resources.ApplyResources(this.colParameterTypeSystem, "colParameterTypeSystem"); this.colParameterTypeSystem.ColumnEdit = this.icbParameterTypeSystem; this.colParameterTypeSystem.FieldName = "System"; this.colParameterTypeSystem.Name = "colParameterTypeSystem"; // // icbParameterTypeSystem // resources.ApplyResources(this.icbParameterTypeSystem, "icbParameterTypeSystem"); this.icbParameterTypeSystem.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("icbParameterTypeSystem.Buttons"))))}); this.icbParameterTypeSystem.Items.AddRange(new DevExpress.XtraEditors.Controls.ImageComboBoxItem[] { new DevExpress.XtraEditors.Controls.ImageComboBoxItem(resources.GetString("icbParameterTypeSystem.Items"), resources.GetString("icbParameterTypeSystem.Items1"), ((int)(resources.GetObject("icbParameterTypeSystem.Items2")))), new DevExpress.XtraEditors.Controls.ImageComboBoxItem(resources.GetString("icbParameterTypeSystem.Items3"), resources.GetString("icbParameterTypeSystem.Items4"), ((int)(resources.GetObject("icbParameterTypeSystem.Items5"))))}); this.icbParameterTypeSystem.Name = "icbParameterTypeSystem"; this.icbParameterTypeSystem.SmallImages = this.imglst; // // imglst // this.imglst.ImageStream = ((DevExpress.Utils.ImageCollectionStreamer)(resources.GetObject("imglst.ImageStream"))); this.imglst.Images.SetKeyName(0, "Books.bmp"); this.imglst.Images.SetKeyName(1, "Document 2 Edit 2.png"); // // barManager1 // this.barManager1.AllowCustomization = false; this.barManager1.Bars.AddRange(new DevExpress.XtraBars.Bar[] { this.barParameterTypes, this.barFixedePresetValues}); this.barManager1.DockControls.Add(this.barDockControlTop); this.barManager1.DockControls.Add(this.barDockControlBottom); this.barManager1.DockControls.Add(this.barDockControlLeft); this.barManager1.DockControls.Add(this.barDockControlRight); this.barManager1.DockControls.Add(this.standaloneBarDockControl1); this.barManager1.DockControls.Add(this.standaloneBarDockControl2); this.barManager1.Form = this; this.barManager1.Items.AddRange(new DevExpress.XtraBars.BarItem[] { this.btnAddParameterType, this.btnRemoveParameterType, this.btnAddFixedPresetValue, this.btnRemoveFixedPresetValue, this.btnUp, this.btnDown}); this.barManager1.MaxItemId = 6; // // barParameterTypes // this.barParameterTypes.BarName = "ParameterTypes"; this.barParameterTypes.DockCol = 0; this.barParameterTypes.DockRow = 0; this.barParameterTypes.DockStyle = DevExpress.XtraBars.BarDockStyle.Standalone; this.barParameterTypes.FloatLocation = new System.Drawing.Point(114, 259); this.barParameterTypes.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.btnAddParameterType), new DevExpress.XtraBars.LinkPersistInfo(this.btnRemoveParameterType)}); this.barParameterTypes.OptionsBar.AllowQuickCustomization = false; this.barParameterTypes.OptionsBar.DisableClose = true; this.barParameterTypes.OptionsBar.DisableCustomization = true; this.barParameterTypes.StandaloneBarDockControl = this.standaloneBarDockControl1; resources.ApplyResources(this.barParameterTypes, "barParameterTypes"); // // btnAddParameterType // resources.ApplyResources(this.btnAddParameterType, "btnAddParameterType"); this.btnAddParameterType.Glyph = ((System.Drawing.Image)(resources.GetObject("btnAddParameterType.Glyph"))); this.btnAddParameterType.Id = 0; this.btnAddParameterType.Name = "btnAddParameterType"; this.btnAddParameterType.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.OnBtnAddParameterTypeItemClick); // // btnRemoveParameterType // resources.ApplyResources(this.btnRemoveParameterType, "btnRemoveParameterType"); this.btnRemoveParameterType.Glyph = ((System.Drawing.Image)(resources.GetObject("btnRemoveParameterType.Glyph"))); this.btnRemoveParameterType.Id = 1; this.btnRemoveParameterType.Name = "btnRemoveParameterType"; this.btnRemoveParameterType.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.OnBtnRemoveParameterTypeItemClick); // // standaloneBarDockControl1 // this.standaloneBarDockControl1.CausesValidation = false; resources.ApplyResources(this.standaloneBarDockControl1, "standaloneBarDockControl1"); this.standaloneBarDockControl1.Name = "standaloneBarDockControl1"; // // barFixedePresetValues // this.barFixedePresetValues.BarName = "FixedePresetValues"; this.barFixedePresetValues.DockCol = 0; this.barFixedePresetValues.DockRow = 0; this.barFixedePresetValues.DockStyle = DevExpress.XtraBars.BarDockStyle.Standalone; this.barFixedePresetValues.FloatLocation = new System.Drawing.Point(310, 166); this.barFixedePresetValues.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.btnAddFixedPresetValue), new DevExpress.XtraBars.LinkPersistInfo(this.btnRemoveFixedPresetValue), new DevExpress.XtraBars.LinkPersistInfo(this.btnUp), new DevExpress.XtraBars.LinkPersistInfo(this.btnDown)}); this.barFixedePresetValues.Offset = 3; this.barFixedePresetValues.OptionsBar.AllowQuickCustomization = false; this.barFixedePresetValues.OptionsBar.AllowRename = true; this.barFixedePresetValues.OptionsBar.DisableClose = true; this.barFixedePresetValues.OptionsBar.DisableCustomization = true; this.barFixedePresetValues.StandaloneBarDockControl = this.standaloneBarDockControl2; resources.ApplyResources(this.barFixedePresetValues, "barFixedePresetValues"); // // btnAddFixedPresetValue // resources.ApplyResources(this.btnAddFixedPresetValue, "btnAddFixedPresetValue"); this.btnAddFixedPresetValue.Glyph = ((System.Drawing.Image)(resources.GetObject("btnAddFixedPresetValue.Glyph"))); this.btnAddFixedPresetValue.Id = 2; this.btnAddFixedPresetValue.Name = "btnAddFixedPresetValue"; this.btnAddFixedPresetValue.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.OnBtnAddFixedPresetValueItemClick); // // btnRemoveFixedPresetValue // resources.ApplyResources(this.btnRemoveFixedPresetValue, "btnRemoveFixedPresetValue"); this.btnRemoveFixedPresetValue.Glyph = ((System.Drawing.Image)(resources.GetObject("btnRemoveFixedPresetValue.Glyph"))); this.btnRemoveFixedPresetValue.Id = 3; this.btnRemoveFixedPresetValue.Name = "btnRemoveFixedPresetValue"; this.btnRemoveFixedPresetValue.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.OnBtnRemoveFixedPresetValueItemClick); // // btnUp // resources.ApplyResources(this.btnUp, "btnUp"); this.btnUp.Glyph = ((System.Drawing.Image)(resources.GetObject("btnUp.Glyph"))); this.btnUp.Id = 4; this.btnUp.Name = "btnUp"; this.btnUp.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.OnBtnUpItemClick); // // btnDown // resources.ApplyResources(this.btnDown, "btnDown"); this.btnDown.Glyph = ((System.Drawing.Image)(resources.GetObject("btnDown.Glyph"))); this.btnDown.Id = 5; this.btnDown.Name = "btnDown"; this.btnDown.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.OnBtnDownItemClick); // // standaloneBarDockControl2 // this.standaloneBarDockControl2.CausesValidation = false; resources.ApplyResources(this.standaloneBarDockControl2, "standaloneBarDockControl2"); this.standaloneBarDockControl2.Name = "standaloneBarDockControl2"; // // barDockControlTop // this.barDockControlTop.CausesValidation = false; resources.ApplyResources(this.barDockControlTop, "barDockControlTop"); // // barDockControlBottom // this.barDockControlBottom.CausesValidation = false; resources.ApplyResources(this.barDockControlBottom, "barDockControlBottom"); // // barDockControlLeft // this.barDockControlLeft.CausesValidation = false; resources.ApplyResources(this.barDockControlLeft, "barDockControlLeft"); // // barDockControlRight // this.barDockControlRight.CausesValidation = false; resources.ApplyResources(this.barDockControlRight, "barDockControlRight"); // // panelControl2 // this.panelControl2.Controls.Add(this.gcFixedPresetValues); this.panelControl2.Controls.Add(this.pnlReferenceType); this.panelControl2.Controls.Add(this.standaloneBarDockControl2); resources.ApplyResources(this.panelControl2, "panelControl2"); this.panelControl2.Name = "panelControl2"; // // gcFixedPresetValues // resources.ApplyResources(this.gcFixedPresetValues, "gcFixedPresetValues"); this.gcFixedPresetValues.MainView = this.gvFixedPresetValues; this.gcFixedPresetValues.MenuManager = this.barManager1; this.gcFixedPresetValues.Name = "gcFixedPresetValues"; this.gcFixedPresetValues.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] { this.gvFixedPresetValues}); // // gvFixedPresetValues // this.gvFixedPresetValues.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] { this.colFixedPresetValueDefaultName, this.colcolFixedPresetValueNationalName}); this.gvFixedPresetValues.GridControl = this.gcFixedPresetValues; this.gvFixedPresetValues.Name = "gvFixedPresetValues"; this.gvFixedPresetValues.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.False; this.gvFixedPresetValues.OptionsBehavior.AllowDeleteRows = DevExpress.Utils.DefaultBoolean.False; this.gvFixedPresetValues.OptionsCustomization.AllowColumnMoving = false; this.gvFixedPresetValues.OptionsCustomization.AllowFilter = false; this.gvFixedPresetValues.OptionsNavigation.EnterMoveNextColumn = true; this.gvFixedPresetValues.OptionsView.ShowGroupPanel = false; // // colFixedPresetValueDefaultName // resources.ApplyResources(this.colFixedPresetValueDefaultName, "colFixedPresetValueDefaultName"); this.colFixedPresetValueDefaultName.FieldName = "DefaultName"; this.colFixedPresetValueDefaultName.Name = "colFixedPresetValueDefaultName"; // // colcolFixedPresetValueNationalName // resources.ApplyResources(this.colcolFixedPresetValueNationalName, "colcolFixedPresetValueNationalName"); this.colcolFixedPresetValueNationalName.FieldName = "NationalName"; this.colcolFixedPresetValueNationalName.Name = "colcolFixedPresetValueNationalName"; // // pnlReferenceType // this.pnlReferenceType.Controls.Add(this.leReferenceType); this.pnlReferenceType.Controls.Add(this.labelControl1); resources.ApplyResources(this.pnlReferenceType, "pnlReferenceType"); this.pnlReferenceType.Name = "pnlReferenceType"; // // leReferenceType // resources.ApplyResources(this.leReferenceType, "leReferenceType"); this.leReferenceType.MenuManager = this.barManager1; this.leReferenceType.Name = "leReferenceType"; this.leReferenceType.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("leReferenceType.Properties.Buttons"))))}); this.leReferenceType.Properties.Columns.AddRange(new DevExpress.XtraEditors.Controls.LookUpColumnInfo[] { new DevExpress.XtraEditors.Controls.LookUpColumnInfo(resources.GetString("leReferenceType.Properties.Columns"), resources.GetString("leReferenceType.Properties.Columns1"))}); this.leReferenceType.Properties.DisplayMember = "NationalName"; this.leReferenceType.Properties.NullText = resources.GetString("leReferenceType.Properties.NullText"); this.leReferenceType.Properties.ShowFooter = false; this.leReferenceType.Properties.ShowHeader = false; this.leReferenceType.Properties.ValueMember = "idfsReferenceType"; this.leReferenceType.EditValueChanged += new System.EventHandler(this.OnLeReferenceTypeEditValueChanged); // // labelControl1 // resources.ApplyResources(this.labelControl1, "labelControl1"); this.labelControl1.Name = "labelControl1"; // // splitterControl1 // resources.ApplyResources(this.splitterControl1, "splitterControl1"); this.splitterControl1.Name = "splitterControl1"; this.splitterControl1.TabStop = false; // // bar2 // this.bar2.BarName = "Tools"; this.bar2.DockCol = 0; this.bar2.DockRow = 0; this.bar2.DockStyle = DevExpress.XtraBars.BarDockStyle.Standalone; this.bar2.FloatLocation = new System.Drawing.Point(114, 259); this.bar2.StandaloneBarDockControl = this.standaloneBarDockControl1; resources.ApplyResources(this.bar2, "bar2"); // // FFParameterTypesEditor // resources.ApplyResources(this, "$this"); this.Controls.Add(this.splitterControl1); this.Controls.Add(this.panelControl2); this.Controls.Add(this.panelControl1); this.Controls.Add(this.barDockControlLeft); this.Controls.Add(this.barDockControlRight); this.Controls.Add(this.barDockControlBottom); this.Controls.Add(this.barDockControlTop); this.Cursor = System.Windows.Forms.Cursors.Default; this.FormID = "F02"; this.HelpTopicID = "Parameter_types_matrix"; this.LeftIcon = global::EIDSS.FlexibleForms.Properties.Resources.Parameter_Types_Editor__large__48_; this.Name = "FFParameterTypesEditor"; this.ShowDeleteButton = false; this.Sizable = true; this.Controls.SetChildIndex(this.barDockControlTop, 0); this.Controls.SetChildIndex(this.barDockControlBottom, 0); this.Controls.SetChildIndex(this.barDockControlRight, 0); this.Controls.SetChildIndex(this.barDockControlLeft, 0); this.Controls.SetChildIndex(this.cmdOk, 0); this.Controls.SetChildIndex(this.panelControl1, 0); this.Controls.SetChildIndex(this.panelControl2, 0); this.Controls.SetChildIndex(this.splitterControl1, 0); ((System.ComponentModel.ISupportInitialize)(this.panelControl1)).EndInit(); this.panelControl1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.gcParameterTypes)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.gvParameterTypes)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.icbParameterTypeSystem)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.imglst)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barManager1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.panelControl2)).EndInit(); this.panelControl2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.gcFixedPresetValues)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.gvFixedPresetValues)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pnlReferenceType)).EndInit(); this.pnlReferenceType.ResumeLayout(false); this.pnlReferenceType.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.leReferenceType.Properties)).EndInit(); this.ResumeLayout(false); } #endregion private DevExpress.XtraEditors.PanelControl panelControl1; private DevExpress.XtraBars.StandaloneBarDockControl standaloneBarDockControl1; private DevExpress.XtraBars.BarManager barManager1; private DevExpress.XtraBars.Bar barParameterTypes; private DevExpress.XtraBars.BarDockControl barDockControlTop; private DevExpress.XtraBars.BarDockControl barDockControlBottom; private DevExpress.XtraBars.BarDockControl barDockControlLeft; private DevExpress.XtraBars.BarDockControl barDockControlRight; private DevExpress.XtraGrid.GridControl gcParameterTypes; private DevExpress.XtraGrid.Views.Grid.GridView gvParameterTypes; private DevExpress.XtraEditors.SplitterControl splitterControl1; private DevExpress.XtraEditors.PanelControl panelControl2; private DevExpress.XtraBars.StandaloneBarDockControl standaloneBarDockControl2; private DevExpress.XtraBars.Bar bar2; private DevExpress.XtraBars.Bar barFixedePresetValues; private DevExpress.XtraGrid.Columns.GridColumn colParameterTypeDefaultName; private DevExpress.XtraGrid.Columns.GridColumn colParameterTypeNationalName; private DevExpress.XtraGrid.Columns.GridColumn colParameterTypeSystem; private DevExpress.XtraEditors.Repository.RepositoryItemImageComboBox icbParameterTypeSystem; private DevExpress.Utils.ImageCollection imglst; private DevExpress.XtraBars.BarButtonItem btnAddParameterType; private DevExpress.XtraBars.BarButtonItem btnRemoveParameterType; private DevExpress.XtraBars.BarButtonItem btnAddFixedPresetValue; private DevExpress.XtraBars.BarButtonItem btnRemoveFixedPresetValue; private DevExpress.XtraGrid.GridControl gcFixedPresetValues; private DevExpress.XtraGrid.Views.Grid.GridView gvFixedPresetValues; private DevExpress.XtraGrid.Columns.GridColumn colFixedPresetValueDefaultName; private DevExpress.XtraGrid.Columns.GridColumn colcolFixedPresetValueNationalName; private DevExpress.XtraEditors.PanelControl pnlReferenceType; private DevExpress.XtraEditors.LookUpEdit leReferenceType; private DevExpress.XtraEditors.LabelControl labelControl1; private DevExpress.XtraBars.BarButtonItem btnUp; private DevExpress.XtraBars.BarButtonItem btnDown; } }
using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Xml; using System.Xml.Linq; using Umbraco.Core.Configuration; using Umbraco.Core.Models; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Strings; using umbraco.interfaces; namespace Umbraco.Core.Services { //TODO: Move the rest of the logic for the PackageService.Export methods to here! /// <summary> /// A helper class to serialize entities to XML /// </summary> internal class EntityXmlSerializer { /// <summary> /// Exports an <see cref="IContent"/> item to xml as an <see cref="XElement"/> /// </summary> /// <param name="contentService"></param> /// <param name="dataTypeService"></param> /// <param name="content">Content to export</param> /// <param name="deep">Optional parameter indicating whether to include descendents</param> /// <returns><see cref="XElement"/> containing the xml representation of the Content object</returns> public XElement Serialize(IContentService contentService, IDataTypeService dataTypeService, IContent content, bool deep = false) { //nodeName should match Casing.SafeAliasWithForcingCheck(content.ContentType.Alias); var nodeName = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? "node" : content.ContentType.Alias.ToSafeAliasWithForcingCheck(); var xml = Serialize(dataTypeService, content, nodeName); xml.Add(new XAttribute("nodeType", content.ContentType.Id)); xml.Add(new XAttribute("creatorName", content.GetCreatorProfile().Name)); xml.Add(new XAttribute("writerName", content.GetWriterProfile().Name)); xml.Add(new XAttribute("writerID", content.WriterId)); xml.Add(new XAttribute("template", content.Template == null ? "0" : content.Template.Id.ToString(CultureInfo.InvariantCulture))); xml.Add(new XAttribute("nodeTypeAlias", content.ContentType.Alias)); if (deep) { var descendants = contentService.GetDescendants(content).ToArray(); var currentChildren = descendants.Where(x => x.ParentId == content.Id); AddChildXml(contentService, dataTypeService, descendants, currentChildren, xml); } return xml; } /// <summary> /// Exports an <see cref="IMedia"/> item to xml as an <see cref="XElement"/> /// </summary> /// <param name="mediaService"></param> /// <param name="dataTypeService"></param> /// <param name="media">Media to export</param> /// <param name="deep">Optional parameter indicating whether to include descendents</param> /// <returns><see cref="XElement"/> containing the xml representation of the Media object</returns> public XElement Serialize(IMediaService mediaService, IDataTypeService dataTypeService, IMedia media, bool deep = false) { //nodeName should match Casing.SafeAliasWithForcingCheck(content.ContentType.Alias); var nodeName = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? "node" : media.ContentType.Alias.ToSafeAliasWithForcingCheck(); var xml = Serialize(dataTypeService, media, nodeName); xml.Add(new XAttribute("nodeType", media.ContentType.Id)); xml.Add(new XAttribute("writerName", media.GetCreatorProfile().Name)); xml.Add(new XAttribute("writerID", media.CreatorId)); xml.Add(new XAttribute("version", media.Version)); xml.Add(new XAttribute("template", 0)); xml.Add(new XAttribute("nodeTypeAlias", media.ContentType.Alias)); if (deep) { var descendants = mediaService.GetDescendants(media).ToArray(); var currentChildren = descendants.Where(x => x.ParentId == media.Id); AddChildXml(mediaService, dataTypeService, descendants, currentChildren, xml); } return xml; } /// <summary> /// Exports an <see cref="IMedia"/> item to xml as an <see cref="XElement"/> /// </summary> /// <param name="dataTypeService"></param> /// <param name="member">Member to export</param> /// <returns><see cref="XElement"/> containing the xml representation of the Member object</returns> public XElement Serialize(IDataTypeService dataTypeService, IMember member) { //nodeName should match Casing.SafeAliasWithForcingCheck(content.ContentType.Alias); var nodeName = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? "node" : member.ContentType.Alias.ToSafeAliasWithForcingCheck(); var xml = Serialize(dataTypeService, member, nodeName); xml.Add(new XAttribute("nodeType", member.ContentType.Id)); xml.Add(new XAttribute("nodeTypeAlias", member.ContentType.Alias)); xml.Add(new XAttribute("loginName", member.Username)); xml.Add(new XAttribute("email", member.Email)); xml.Add(new XAttribute("key", member.Key)); return xml; } public XElement Serialize(IDataTypeService dataTypeService, Property property) { var propertyType = property.PropertyType; var nodeName = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? "data" : property.Alias.ToSafeAlias(); var xElement = new XElement(nodeName); //Add the property alias to the legacy schema if (UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema) { var a = new XAttribute("alias", property.Alias.ToSafeAlias()); xElement.Add(a); } //Get the property editor for thsi property and let it convert it to the xml structure var propertyEditor = PropertyEditorResolver.Current.GetByAlias(property.PropertyType.PropertyEditorAlias); if (propertyEditor != null) { var xmlValue = propertyEditor.ValueEditor.ConvertDbToXml(property, propertyType, dataTypeService); xElement.Add(xmlValue); } return xElement; } /// <summary> /// Exports an <see cref="IDataTypeDefinition"/> item to xml as an <see cref="XElement"/> /// </summary> /// <param name="dataTypeService"></param> /// <param name="dataTypeDefinition">IDataTypeDefinition type to export</param> /// <returns><see cref="XElement"/> containing the xml representation of the IDataTypeDefinition object</returns> public XElement Serialize(IDataTypeService dataTypeService, IDataTypeDefinition dataTypeDefinition) { var prevalues = new XElement("PreValues"); var prevalueList = dataTypeService.GetPreValuesCollectionByDataTypeId(dataTypeDefinition.Id) .FormatAsDictionary(); var sort = 0; foreach (var pv in prevalueList) { var prevalue = new XElement("PreValue"); prevalue.Add(new XAttribute("Id", pv.Value.Id)); prevalue.Add(new XAttribute("Value", pv.Value.Value ?? "")); prevalue.Add(new XAttribute("Alias", pv.Key)); prevalue.Add(new XAttribute("SortOrder", sort)); prevalues.Add(prevalue); sort++; } var xml = new XElement("DataType", prevalues); xml.Add(new XAttribute("Name", dataTypeDefinition.Name)); //The 'ID' when exporting is actually the property editor alias (in pre v7 it was the IDataType GUID id) xml.Add(new XAttribute("Id", dataTypeDefinition.PropertyEditorAlias)); xml.Add(new XAttribute("Definition", dataTypeDefinition.Key)); xml.Add(new XAttribute("DatabaseType", dataTypeDefinition.DatabaseType.ToString())); return xml; } public XElement Serialize(IDictionaryItem dictionaryItem) { var xml = new XElement("DictionaryItem", new XAttribute("Key", dictionaryItem.ItemKey)); foreach (var translation in dictionaryItem.Translations) { xml.Add(new XElement("Value", new XAttribute("LanguageId", translation.Language.Id), new XAttribute("LanguageCultureAlias", translation.Language.IsoCode), new XCData(translation.Value))); } return xml; } public XElement Serialize(ILanguage language) { var xml = new XElement("Language", new XAttribute("Id", language.Id), new XAttribute("CultureAlias", language.IsoCode), new XAttribute("FriendlyName", language.CultureName)); return xml; } public XElement Serialize(ITemplate template) { var xml = new XElement("Template"); xml.Add(new XElement("Name", template.Name)); xml.Add(new XElement("Alias", template.Alias)); xml.Add(new XElement("Design", new XCData(template.Content))); var concreteTemplate = template as Template; if (concreteTemplate != null && concreteTemplate.MasterTemplateId != null) { if (concreteTemplate.MasterTemplateId.IsValueCreated && concreteTemplate.MasterTemplateId.Value != default(int)) { xml.Add(new XElement("Master", concreteTemplate.MasterTemplateId.ToString())); xml.Add(new XElement("MasterAlias", concreteTemplate.MasterTemplateAlias)); } } return xml; } public XElement Serialize(IDataTypeService dataTypeService, IMediaType mediaType) { var info = new XElement("Info", new XElement("Name", mediaType.Name), new XElement("Alias", mediaType.Alias), new XElement("Icon", mediaType.Icon), new XElement("Thumbnail", mediaType.Thumbnail), new XElement("Description", mediaType.Description), new XElement("AllowAtRoot", mediaType.AllowedAsRoot.ToString())); var masterContentType = mediaType.CompositionAliases().FirstOrDefault(); if (masterContentType != null) info.Add(new XElement("Master", masterContentType)); var structure = new XElement("Structure"); foreach (var allowedType in mediaType.AllowedContentTypes) { structure.Add(new XElement("MediaType", allowedType.Alias)); } var genericProperties = new XElement("GenericProperties"); foreach (var propertyType in mediaType.PropertyTypes) { var definition = dataTypeService.GetDataTypeDefinitionById(propertyType.DataTypeDefinitionId); var propertyGroup = mediaType.PropertyGroups.FirstOrDefault(x => x.Id == propertyType.PropertyGroupId.Value); var genericProperty = new XElement("GenericProperty", new XElement("Name", propertyType.Name), new XElement("Alias", propertyType.Alias), new XElement("Type", propertyType.PropertyEditorAlias), new XElement("Definition", definition.Key), new XElement("Tab", propertyGroup == null ? "" : propertyGroup.Name), new XElement("Mandatory", propertyType.Mandatory.ToString()), new XElement("Validation", propertyType.ValidationRegExp), new XElement("Description", new XCData(propertyType.Description))); genericProperties.Add(genericProperty); } var tabs = new XElement("Tabs"); foreach (var propertyGroup in mediaType.PropertyGroups) { var tab = new XElement("Tab", new XElement("Id", propertyGroup.Id.ToString(CultureInfo.InvariantCulture)), new XElement("Caption", propertyGroup.Name)); tabs.Add(tab); } var xml = new XElement("MediaType", info, structure, genericProperties, tabs); return xml; } public XElement Serialize(IMacro macro) { var xml = new XElement("macro"); xml.Add(new XElement("name", macro.Name)); xml.Add(new XElement("alias", macro.Alias)); xml.Add(new XElement("scriptType", macro.ControlType)); xml.Add(new XElement("scriptAssembly", macro.ControlAssembly)); xml.Add(new XElement("scriptingFile", macro.ScriptPath)); xml.Add(new XElement("xslt", macro.XsltPath)); xml.Add(new XElement("useInEditor", macro.UseInEditor.ToString())); xml.Add(new XElement("dontRender", macro.DontRender.ToString())); xml.Add(new XElement("refreshRate", macro.CacheDuration.ToString(CultureInfo.InvariantCulture))); xml.Add(new XElement("cacheByMember", macro.CacheByMember.ToString())); xml.Add(new XElement("cacheByPage", macro.CacheByPage.ToString())); var properties = new XElement("properties"); foreach (var property in macro.Properties) { properties.Add(new XElement("property", new XAttribute("name", property.Name), new XAttribute("alias", property.Alias), new XAttribute("sortOrder", property.SortOrder), new XAttribute("propertyType", property.EditorAlias))); } xml.Add(properties); return xml; } /// <summary> /// Exports an <see cref="IContentType"/> item to xml as an <see cref="XElement"/> /// </summary> /// <param name="dataTypeService"></param> /// <param name="contentType">Content type to export</param> /// <returns><see cref="XElement"/> containing the xml representation of the IContentType object</returns> public XElement Serialize(IDataTypeService dataTypeService, IContentType contentType) { var info = new XElement("Info", new XElement("Name", contentType.Name), new XElement("Alias", contentType.Alias), new XElement("Icon", contentType.Icon), new XElement("Thumbnail", contentType.Thumbnail), new XElement("Description", contentType.Description), new XElement("AllowAtRoot", contentType.AllowedAsRoot.ToString()), new XElement("IsListView", contentType.IsContainer.ToString())); var masterContentType = contentType.CompositionAliases().FirstOrDefault(); if (masterContentType != null) info.Add(new XElement("Master", masterContentType)); var allowedTemplates = new XElement("AllowedTemplates"); foreach (var template in contentType.AllowedTemplates) { allowedTemplates.Add(new XElement("Template", template.Alias)); } info.Add(allowedTemplates); if (contentType.DefaultTemplate != null && contentType.DefaultTemplate.Id != 0) info.Add(new XElement("DefaultTemplate", contentType.DefaultTemplate.Alias)); else info.Add(new XElement("DefaultTemplate", "")); var structure = new XElement("Structure"); foreach (var allowedType in contentType.AllowedContentTypes) { structure.Add(new XElement("DocumentType", allowedType.Alias)); } var genericProperties = new XElement("GenericProperties"); foreach (var propertyType in contentType.PropertyTypes) { var definition = dataTypeService.GetDataTypeDefinitionById(propertyType.DataTypeDefinitionId); var propertyGroup = propertyType.PropertyGroupId == null ? null : contentType.PropertyGroups.FirstOrDefault(x => x.Id == propertyType.PropertyGroupId.Value); var genericProperty = new XElement("GenericProperty", new XElement("Name", propertyType.Name), new XElement("Alias", propertyType.Alias), new XElement("Type", propertyType.PropertyEditorAlias), new XElement("Definition", definition.Key), new XElement("Tab", propertyGroup == null ? "" : propertyGroup.Name), new XElement("Mandatory", propertyType.Mandatory.ToString()), new XElement("Validation", propertyType.ValidationRegExp), new XElement("Description", new XCData(propertyType.Description))); genericProperties.Add(genericProperty); } var tabs = new XElement("Tabs"); foreach (var propertyGroup in contentType.PropertyGroups) { var tab = new XElement("Tab", new XElement("Id", propertyGroup.Id.ToString(CultureInfo.InvariantCulture)), new XElement("Caption", propertyGroup.Name)); tabs.Add(tab); } return new XElement("DocumentType", info, structure, genericProperties, tabs); } /// <summary> /// Used by Media Export to recursively add children /// </summary> /// <param name="mediaService"></param> /// <param name="dataTypeService"></param> /// <param name="originalDescendants"></param> /// <param name="currentChildren"></param> /// <param name="currentXml"></param> private void AddChildXml(IMediaService mediaService, IDataTypeService dataTypeService, IMedia[] originalDescendants, IEnumerable<IMedia> currentChildren, XElement currentXml) { foreach (var child in currentChildren) { //add the child's xml var childXml = Serialize(mediaService, dataTypeService, child); currentXml.Add(childXml); //copy local (out of closure) var c = child; //get this item's children var children = originalDescendants.Where(x => x.ParentId == c.Id); //recurse and add it's children to the child xml element AddChildXml(mediaService, dataTypeService, originalDescendants, children, childXml); } } /// <summary> /// Part of the export of IContent and IMedia and IMember which is shared /// </summary> /// <param name="dataTypeService"></param> /// <param name="contentBase">Base Content or Media to export</param> /// <param name="nodeName">Name of the node</param> /// <returns><see cref="XElement"/></returns> private XElement Serialize(IDataTypeService dataTypeService, IContentBase contentBase, string nodeName) { //NOTE: that one will take care of umbracoUrlName var url = contentBase.GetUrlSegment(); var xml = new XElement(nodeName, new XAttribute("id", contentBase.Id), new XAttribute("parentID", contentBase.Level > 1 ? contentBase.ParentId : -1), new XAttribute("level", contentBase.Level), new XAttribute("creatorID", contentBase.CreatorId), new XAttribute("sortOrder", contentBase.SortOrder), new XAttribute("createDate", contentBase.CreateDate.ToString("s")), new XAttribute("updateDate", contentBase.UpdateDate.ToString("s")), new XAttribute("nodeName", contentBase.Name), new XAttribute("urlName", url), new XAttribute("path", contentBase.Path), new XAttribute("isDoc", "")); foreach (var property in contentBase.Properties.Where(p => p != null && p.Value != null && p.Value.ToString().IsNullOrWhiteSpace() == false)) { xml.Add(Serialize(dataTypeService, property)); } return xml; } /// <summary> /// Used by Content Export to recursively add children /// </summary> /// <param name="contentService"></param> /// <param name="dataTypeService"></param> /// <param name="originalDescendants"></param> /// <param name="currentChildren"></param> /// <param name="currentXml"></param> private void AddChildXml(IContentService contentService, IDataTypeService dataTypeService, IContent[] originalDescendants, IEnumerable<IContent> currentChildren, XElement currentXml) { foreach (var child in currentChildren) { //add the child's xml var childXml = Serialize(contentService, dataTypeService, child); currentXml.Add(childXml); //copy local (out of closure) var c = child; //get this item's children var children = originalDescendants.Where(x => x.ParentId == c.Id); //recurse and add it's children to the child xml element AddChildXml(contentService, dataTypeService, originalDescendants, children, childXml); } } } }
using System; using System.Collections.Generic; using System.Text; using System.Drawing; using System.Runtime.InteropServices; using System.Xml; using System.Security.Cryptography; using System.Security.Cryptography.Xml; namespace pwtool_texturebuilder { public class SubImage { public SubImage( string filename, string name, Rectangle rect, bool rotated ) { mFilename = filename; mName = name; mRect = rect; mRotated = rotated; } public string mFilename = ""; public string mName = ""; public Rectangle mRect; public bool mRotated = false; // Only makes sense to rotate an input bitmap 90 degrees } public class OutputBitmap : IDisposable { Bitmap mBitmap = null; List<Rectangle> mAvailableRectsList = new List<Rectangle>(); // same list, just sorted by size List<SubImage> mSubImages = new List<SubImage>(); Size mVirtualSize = new Size( 1, 1 ); string mOutputFilename; public string OutputFilename { get { return mOutputFilename; } } public List<Rectangle> AvailableRects { get { return mAvailableRectsList; } } public List<SubImage> SubImages { get { return mSubImages; } } bool mSingleImageOutput = false; public bool SingleImageOutput { get { return mSingleImageOutput; } } [DllImport( "msvcrt.dll", EntryPoint = "memcpy" )] unsafe static extern void CopyMemory( IntPtr pDest, IntPtr pSrc, int length ); static IntPtr AddPtr( IntPtr src, int offset ) { return new IntPtr( src.ToInt64() + offset ); } public void CopyImageIntoImage( Bitmap source, Point destPos, bool isRotated ) { if ( !isRotated ) { System.Drawing.Imaging.BitmapData destData = mBitmap.LockBits( new Rectangle( destPos, source.Size ), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb ); System.Drawing.Imaging.BitmapData srcData = source.LockBits( new Rectangle( 0, 0, source.Width, source.Height ), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb ); for ( int line = 0; line < source.Height; ++line ) { CopyMemory( AddPtr( destData.Scan0, line * destData.Stride ), AddPtr( srcData.Scan0, line * srcData.Stride ), srcData.Width * 4 ); } source.UnlockBits( srcData ); mBitmap.UnlockBits( destData ); } else { for ( int x = 0; x < source.Height; ++x ) { for ( int y = 0; y < source.Width; ++y ) { mBitmap.SetPixel( destPos.X + x, destPos.Y + y, source.GetPixel( source.Width - y - 1, x ) ); } } } } int SortRectComparer( Rectangle lhs, Rectangle rhs ) { int lhsArea = lhs.Width * lhs.Height; int rhsArea = rhs.Width * rhs.Height; if ( lhsArea > rhsArea ) return -1; else if ( lhsArea < rhsArea ) return 1; else return 0; } public void SortRectList() { mAvailableRectsList.Sort( new Comparison<Rectangle>( SortRectComparer ) ); } public OutputBitmap( string outputName, int index ) { mOutputFilename = String.Format( "{0}_{1:d3}.png", outputName, index ); mBitmap = new Bitmap( Settings.Instance.OutputBitmapSize.Width, Settings.Instance.OutputBitmapSize.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb ); } public OutputBitmap( string outputName, int index, int bitmapWidth, int bitmapHeight ) { mSingleImageOutput = true; mOutputFilename = String.Format( "{0}_{1:d3}.png", outputName, index ); mBitmap = new Bitmap( bitmapWidth, bitmapHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb ); } public void Dispose() { if ( mBitmap != null ) mBitmap.Dispose(); } public bool IncreaseVirtualSize() { if ( mVirtualSize.Width >= Settings.Instance.OutputBitmapSize.Width && mVirtualSize.Height >= Settings.Instance.OutputBitmapSize.Height ) { return false; } int extremeX = 0, extremeY = 0; GetImageExtremes( out extremeX, out extremeY ); int spareWidth = mVirtualSize.Width - extremeX; int spareHeight = mVirtualSize.Height - extremeY; // determine if it will be more efficient to increase on right or bottom side bool increasingWidth = true; if ( mVirtualSize.Width >= Settings.Instance.OutputBitmapSize.Width ) increasingWidth = false; // always expand height if width is maximum else if ( mVirtualSize.Height >= Settings.Instance.OutputBitmapSize.Height ) increasingWidth = true; // always expand width if height is maximum else { // calculate area size is we expand both via the width and height, and expand in the direction which will result in less space int expandedSpareWidth = mVirtualSize.Width * 2 + spareWidth; int expandedSpareHeight = mVirtualSize.Height * 2 + spareHeight; int expandedSpareWidthVolume = expandedSpareWidth * mVirtualSize.Height; int expandedSpareHeightVolume = expandedSpareHeight * mVirtualSize.Width; increasingWidth = expandedSpareHeightVolume > expandedSpareWidthVolume; } // then create new available rect which covers new virtual size, and merge it with any available space on that side Rectangle newRect = new Rectangle(); if ( increasingWidth ) newRect = new Rectangle( extremeX, 0, mVirtualSize.Width + spareWidth, mVirtualSize.Height ); else newRect = new Rectangle( 0, extremeY, mVirtualSize.Width, mVirtualSize.Height + spareHeight ); Size newVirtualSize = new Size( mVirtualSize.Width * (increasingWidth ? 2 : 1), mVirtualSize.Height * (increasingWidth ? 1 : 2) ); // and reduce the size of any rectangles which occupied that merged space List<KeyValuePair<Rectangle, Rectangle>> replacementList = new List<KeyValuePair<Rectangle, Rectangle>>(); foreach ( Rectangle rect in mAvailableRectsList ) { if ( newRect.Contains( rect ) ) { replacementList.Add( new KeyValuePair<Rectangle, Rectangle>( rect, new Rectangle() ) ); } else if ( newRect.IntersectsWith( rect ) ) { int diffX = rect.Right - newRect.Left; if ( diffX < 0 ) diffX = 0; int diffY = rect.Bottom - newRect.Top; if ( diffY < 0 ) diffY = 0; Rectangle newSubRect = new Rectangle( rect.X, rect.Y, rect.Width - diffX, rect.Height - diffY ); replacementList.Add( new KeyValuePair<Rectangle, Rectangle>( rect, newSubRect ) ); } } foreach ( KeyValuePair<Rectangle, Rectangle> kvp in replacementList ) { mAvailableRectsList.Remove( kvp.Key ); if ( !kvp.Value.IsEmpty ) mAvailableRectsList.Add( kvp.Value ); } mAvailableRectsList.Add( newRect ); SortRectList(); mVirtualSize = newVirtualSize; return true; } public void InitVirtualSize( Size size ) { mVirtualSize = new Size( Util.RoundUpToPowerOf2( size.Width ), Util.RoundUpToPowerOf2( size.Height ) ); mAvailableRectsList.Add( new Rectangle( new Point( 0, 0 ), mVirtualSize ) ); } void GetImageExtremes( out int extremeX, out int extremeY ) { extremeX = extremeY = 0; foreach ( SubImage subimage in mSubImages ) { if ( subimage.mRect.Right > extremeX ) extremeX = subimage.mRect.Right; if ( subimage.mRect.Bottom > extremeY ) extremeY = subimage.mRect.Bottom; } } void ShrinkIfNecessary() { System.Diagnostics.Debug.Assert( mBitmap != null ); // find highest y coord and furthest right x coord to find image size int highestX = 0; int highestY = 0; GetImageExtremes( out highestX, out highestY ); highestX = Util.RoundUpToPowerOf2( highestX ); highestY = Util.RoundUpToPowerOf2( highestY ); Bitmap newBitmap = new Bitmap( highestX, highestY ); System.Drawing.Imaging.BitmapData destData = newBitmap.LockBits( new Rectangle( 0, 0, highestX, highestY ), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb ); System.Drawing.Imaging.BitmapData srcData = mBitmap.LockBits( new Rectangle( 0, 0, highestX, highestY ), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb ); for ( int line = 0; line < highestY; ++line ) { CopyMemory( AddPtr( destData.Scan0, line * destData.Stride ), AddPtr( srcData.Scan0, line * srcData.Stride ), srcData.Width * 4 ); } newBitmap.UnlockBits( srcData ); mBitmap.UnlockBits( destData ); mBitmap.Dispose(); mBitmap = newBitmap; } public void SaveFile() { if ( !mSingleImageOutput ) ShrinkIfNecessary(); System.IO.Directory.CreateDirectory( Settings.Instance.OutputDir ); string filename = System.IO.Path.Combine( Settings.Instance.OutputDir, mOutputFilename ); if ( PWLib.Platform.Windows.File.Exists( filename ) ) PWLib.Platform.Windows.File.Delete( filename ); DevIL.DevIL.SaveBitmap( filename, mBitmap ); System.Console.WriteLine( "Created " + PWLib.Platform.Windows.Path.GetFileName( filename ) + " (containing " + mSubImages.Count + " sub images)" ); } public static bool IsInputImageValidSize( Bitmap inputBitmap ) { return inputBitmap.Width < Settings.Instance.OutputBitmapSize.Width && inputBitmap.Height < Settings.Instance.OutputBitmapSize.Height; } static void SignXmlFile( string outputName ) { CspParameters cspParams = new CspParameters(); cspParams.KeyContainerName = "XML_DSIG_RSA_KEY"; RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider( cspParams ); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.PreserveWhitespace = true; xmlDoc.Load( outputName ); SignedXml signedXml = new SignedXml( xmlDoc ); signedXml.SigningKey = rsaKey; // Create a Reference object that describes what to sign. To sign the entire document, set the Uri property to "". Reference reference = new Reference(); reference.Uri = ""; // Add an XmlDsigEnvelopedSignatureTransform object to the Reference object. A transformation allows the verifier to represent the XML data in the identical manner that the signer used. // XML data can be represented in different ways, so this step is vital to verification. XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform( env ); signedXml.AddReference( reference ); signedXml.ComputeSignature(); XmlElement xmlDigitalSignature = signedXml.GetXml(); xmlDoc.DocumentElement.AppendChild( xmlDoc.ImportNode( xmlDigitalSignature, true ) ); xmlDoc.Save( outputName ); } public static void OutputXmlFile( List<OutputBitmap> outputList, string outputName ) { string dirName = System.IO.Path.GetDirectoryName( outputName ); System.IO.Directory.CreateDirectory( dirName ); XmlTextWriter xmlWriter = new XmlTextWriter( outputName, Encoding.ASCII ); xmlWriter.Formatting = Formatting.Indented; xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement( "TextureBuilder" ); xmlWriter.WriteAttributeString( "Version", "0.1" ); Settings.Instance.OutputToXml( xmlWriter ); foreach ( OutputBitmap outputBitmap in outputList ) { outputBitmap.OutputToXml( xmlWriter ); } xmlWriter.WriteFullEndElement(); xmlWriter.Close(); System.Console.WriteLine( "Signing XML " + outputName ); // sign XML document after is has been saved SignXmlFile( outputName ); System.Console.WriteLine( "Created " + outputName ); } public void OutputToXml( XmlWriter xmlWriter ) { xmlWriter.WriteStartElement( "Image" ); xmlWriter.WriteAttributeString( "Filename", mOutputFilename ); xmlWriter.WriteAttributeString( "w", mSingleImageOutput ? mBitmap.Width.ToString() : mVirtualSize.Width.ToString() ); xmlWriter.WriteAttributeString( "h", mSingleImageOutput ? mBitmap.Height.ToString() : mVirtualSize.Height.ToString() ); foreach ( SubImage subImage in mSubImages ) { xmlWriter.WriteStartElement( "SubImage" ); xmlWriter.WriteAttributeString( "name", subImage.mName ); xmlWriter.WriteAttributeString( "x", subImage.mRect.X.ToString() ); xmlWriter.WriteAttributeString( "y", subImage.mRect.Y.ToString() ); xmlWriter.WriteAttributeString( "w", subImage.mRect.Width.ToString() ); xmlWriter.WriteAttributeString( "h", subImage.mRect.Height.ToString() ); xmlWriter.WriteAttributeString( "rotated", subImage.mRotated.ToString() ); xmlWriter.WriteAttributeString( "lastmodified", PWLib.Platform.Windows.Directory.GetLastWriteTimeUtc( subImage.mFilename ).Ticks.ToString() ); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } } }
using System; using System.Collections.Generic; using System.Reflection; using System.Xml; using VersionOne.SDK.APIClient; using VersionOne.ServiceHost.Eventing; using VersionOne.Profile; using VersionOne.ServiceHost.Core.Configuration; using VersionOne.ServiceHost.Core.Logging; namespace VersionOne.ServiceHost.Core.Services { // TODO apply ServerConnector public abstract class V1WriterServiceBase : IHostedService { private IServices services; protected XmlElement Config; protected IEventManager EventManager; protected ILogger Logger; private const string MemberType = "Member"; private const string DefaultRoleNameProperty = "DefaultRole.Name"; protected virtual IServices Services { get { if (services == null) { try { var settings = VersionOneSettings.FromXmlElement(Config); var connector = V1Connector .WithInstanceUrl(settings.Url) .WithUserAgentHeader("VersionOne.Integration.JIRASync", Assembly.GetEntryAssembly().GetName().Version.ToString()); ICanSetProxyOrEndpointOrGetConnector connectorWithAuth; switch (settings.AuthenticationType) { case AuthenticationTypes.AccessToken: connectorWithAuth = connector.WithAccessToken(settings.AccessToken); break; default: throw new Exception("Invalid authentication type"); } if (settings.ProxySettings.Enabled) { connectorWithAuth.WithProxy( new ProxyProvider( new Uri(settings.ProxySettings.Url), settings.ProxySettings.Username, settings.ProxySettings.Password, settings.ProxySettings.Domain) ); } services = new SDK.APIClient.Services(connectorWithAuth.Build()); if (!services.LoggedIn.IsNull) { LogVersionOneConnectionInformation(); } } catch (Exception ex) { Logger.Log("Failed to connect to VersionOne server", ex); throw; } } return services; } } private void LogVersionOneConnectionInformation() { try { var metaVersion = ((MetaModel) Services.Meta).Version.ToString(); var memberOid = Services.LoggedIn.Momentless.ToString(); var defaultRole = GetLoggedInMemberRole(); Logger.LogVersionOneConnectionInformation(LogMessage.SeverityType.Info, metaVersion, memberOid, defaultRole); } catch (Exception ex) { Logger.Log(LogMessage.SeverityType.Warning, "Failed to log VersionOne connection information.", ex); } } private string GetLoggedInMemberRole() { var query = new Query(Services.LoggedIn); var defaultRoleAttribute = Services.Meta.GetAssetType(MemberType).GetAttributeDefinition(DefaultRoleNameProperty); query.Selection.Add(defaultRoleAttribute); var asset = Services.Retrieve(query).Assets[0]; var role = asset.GetAttribute(defaultRoleAttribute); return Services.Localization(role.Value.ToString()); } public virtual void Initialize(XmlElement config, IEventManager eventManager, IProfile profile) { Config = config; EventManager = eventManager; Logger = new Logger(eventManager); Logger.LogVersionOneConfiguration(LogMessage.SeverityType.Info, Config["Settings"]); } public void Start() { // TODO move subscriptions to timer events, etc. here } protected abstract IEnumerable<NeededAssetType> NeededAssetTypes { get; } protected void VerifyMeta() { try { VerifyNeededMeta(NeededAssetTypes); VerifyRuntimeMeta(); } catch (MetaException ex) { throw new ApplicationException("Necessary meta is not present in this VersionOne system", ex); } } protected virtual void VerifyRuntimeMeta() { } protected struct NeededAssetType { public readonly string Name; public readonly string[] AttributeDefinitionNames; public NeededAssetType(string name, string[] attributedefinitionnames) { Name = name; AttributeDefinitionNames = attributedefinitionnames; } } protected void VerifyNeededMeta(IEnumerable<NeededAssetType> neededassettypes) { foreach (var neededAssetType in neededassettypes) { var assettype = Services.Meta.GetAssetType(neededAssetType.Name); foreach (var attributeDefinitionName in neededAssetType.AttributeDefinitionNames) { var attribdef = assettype.GetAttributeDefinition(attributeDefinitionName); } } } #region Meta wrappers protected IAssetType RequestType { get { return Services.Meta.GetAssetType("Request"); } } protected IAssetType DefectType { get { return Services.Meta.GetAssetType("Defect"); } } protected IAssetType StoryType { get { return Services.Meta.GetAssetType("Story"); } } protected IAssetType ReleaseVersionType { get { return Services.Meta.GetAssetType("StoryCategory"); } } protected IAssetType LinkType { get { return Services.Meta.GetAssetType("Link"); } } protected IAssetType NoteType { get { return Services.Meta.GetAssetType("Note"); } } protected IAttributeDefinition DefectName { get { return DefectType.GetAttributeDefinition("Name"); } } protected IAttributeDefinition DefectDescription { get { return DefectType.GetAttributeDefinition("Description"); } } protected IAttributeDefinition DefectOwners { get { return DefectType.GetAttributeDefinition("Owners"); } } protected IAttributeDefinition DefectScope { get { return DefectType.GetAttributeDefinition("Scope"); } } protected IAttributeDefinition DefectAssetState { get { return RequestType.GetAttributeDefinition("AssetState"); } } protected IAttributeDefinition RequestCompanyName { get { return RequestType.GetAttributeDefinition("Name"); } } protected IAttributeDefinition RequestNumber { get { return RequestType.GetAttributeDefinition("Number"); } } protected IAttributeDefinition RequestSuggestedInstance { get { return RequestType.GetAttributeDefinition("Reference"); } } protected IAttributeDefinition RequestMethodology { get { return RequestType.GetAttributeDefinition("Source"); } } protected IAttributeDefinition RequestMethodologyName { get { return RequestType.GetAttributeDefinition("Source.Name"); } } protected IAttributeDefinition RequestCommunityEdition { get { return RequestType.GetAttributeDefinition("Custom_CommunityEdition"); } } protected IAttributeDefinition RequestAssetState { get { return RequestType.GetAttributeDefinition("AssetState"); } } protected IAttributeDefinition RequestCreateDate { get { return RequestType.GetAttributeDefinition("CreateDate"); } } protected IAttributeDefinition RequestCreatedBy { get { return RequestType.GetAttributeDefinition("CreatedBy"); } } protected IOperation RequestInactivate { get { return Services.Meta.GetOperation("Request.Inactivate"); } } protected IAttributeDefinition StoryName { get { return StoryType.GetAttributeDefinition("Name"); } } protected IAttributeDefinition StoryActualInstance { get { return StoryType.GetAttributeDefinition("Reference"); } } protected IAttributeDefinition StoryRequests { get { return StoryType.GetAttributeDefinition("Requests"); } } protected IAttributeDefinition StoryReleaseVersion { get { return StoryType.GetAttributeDefinition("Category"); } } protected IAttributeDefinition StoryMethodology { get { return StoryType.GetAttributeDefinition("Source"); } } protected IAttributeDefinition StoryCommunitySite { get { return StoryType.GetAttributeDefinition("Custom_CommunitySite"); } } protected IAttributeDefinition StoryScope { get { return StoryType.GetAttributeDefinition("Scope"); } } protected IAttributeDefinition StoryOwners { get { return StoryType.GetAttributeDefinition("Owners"); } } protected IAttributeDefinition ReleaseVersionName { get { return ReleaseVersionType.GetAttributeDefinition("Name"); } } protected IAttributeDefinition LinkAsset { get { return LinkType.GetAttributeDefinition("Asset"); } } protected IAttributeDefinition LinkOnMenu { get { return LinkType.GetAttributeDefinition("OnMenu"); } } protected IAttributeDefinition LinkUrl { get { return LinkType.GetAttributeDefinition("URL"); } } protected IAttributeDefinition LinkName { get { return LinkType.GetAttributeDefinition("Name"); } } protected IAttributeDefinition NoteName { get { return NoteType.GetAttributeDefinition("Name"); } } protected IAttributeDefinition NoteAsset { get { return NoteType.GetAttributeDefinition("Asset"); } } protected IAttributeDefinition NotePersonal { get { return NoteType.GetAttributeDefinition("Personal"); } } protected IAttributeDefinition NoteContent { get { return NoteType.GetAttributeDefinition("Content"); } } #endregion } }
using System; using log4net; #if !LATE_BIND using HSVSESSIONLib; using HFMWSESSIONLib; using HSXSERVERLib; #endif using Command; namespace HFM { /// <summary> /// Represents a connection to a single HFM application. The main purpose of /// a Session is to obtain references to other functional modules for the /// current application. /// Instances of this class are created by a Factory method on the /// Connection class in the Client module. /// </summary> public class Session { // Reference to class logger protected static readonly ILog _log = LogManager.GetLogger( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Reference to Connection object private readonly Connection _connection; // Cluster name this session is with private readonly string _cluster; // Application name this session is with private readonly string _application; #if LATE_BIND // Reference to HFM HsvSession object private dynamic _hsvSession; // Reference to a WebSession private dynamic _hfmwSession; #else // Reference to HFM HsvSession object private HsvSession _hsvSession; // Reference to a WebSession private HFMwSession _hfmwSession; #endif // Reference to a Server object private Server _server; // Reference to a Metadata object private Metadata _metadata; // Reference to a ProcessFlow object private ProcessFlow _processFlow; // Reference to a Security object private Security _security; // Reference to a Data object private Data _data; // Reference to a Calculate object private Calculate _calculate; // Reference to a SystemInfo object private SystemInfo _systemInfo; /// Returns the name of the application to which this session belongs public string Application { get { return _application; } } /// Returns the name of the cluster on which this session exists public string Cluster { get { return _cluster; } } public Session(Connection conn, string cluster, string application) { _log.Trace("Constructing Session object"); _connection = conn; _cluster = cluster; _application = application; } #if LATE_BIND internal dynamic HsvSession #else internal HsvSession HsvSession #endif { get { if(_hsvSession == null) { InitSession(); } return _hsvSession; } } #if LATE_BIND internal dynamic HFMwSession #else internal HFMwSession HFMwSession #endif { get { if(_hfmwSession == null) { object hfmwSession = null; HFM.Try(string.Format("Opening web application {0} on {1}", _application, _cluster), () => hfmwSession = _connection.HFMwManageApplications.OpenApplication(_cluster, _application)); #if LATE_BIND _hfmwSession = hfmwSession; #else _hfmwSession = (HFMwSession)hfmwSession; #endif } return _hfmwSession; } } public Server Server { get { if(_server == null) { InitSession(); } return _server; } } [Factory] public Metadata Metadata { get { if(_metadata == null) { _metadata = new Metadata(this); } return _metadata; } } [Factory] public ProcessFlow ProcessFlow { get { if(_processFlow == null) { if(Metadata.UsesPhasedSubmissions) { _processFlow = new PhasedSubmissionProcessFlow(this); } else { _processFlow = new ProcessUnitProcessFlow(this); } } return _processFlow; } } [Factory] public Security Security { get { if(_security == null) { _security = new Security(this); } return _security; } } [Factory] public Data Data { get { if(_data == null) { _data = new Data(this); } return _data; } } [Factory] public Calculate Calculate { get { if(_calculate == null) { _calculate = new Calculate(this); } return _calculate; } } [Factory] public SystemInfo SystemInfo { get { if(_systemInfo == null) { _systemInfo = new SystemInfo(this); } return _systemInfo; } } private void InitSession() { object hsxServer = null, hsvSession = null; HFM.Try(string.Format("Opening application {0} on {1}", _application, _cluster), () => _connection.Client.HsxClient.OpenApplication(_cluster, "Financial Management", _application, out hsxServer, out hsvSession)); #if LATE_BIND _hsvSession = hsvSession; _server = new Server(hsxServer); #else _hsvSession = (HsvSession)hsvSession; _server = new Server((HsxServer)hsxServer); #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.Collections.Generic; using System.Text; using NUnit.Framework; using Microsoft.Build.BuildEngine; using Microsoft.Build.Framework; using System.Collections; namespace Microsoft.Build.UnitTests { [TestFixture] public class SharedMemory_Test { [Test] public void TestItemsInandOutOfSharedMemory() { string name = Guid.NewGuid().ToString(); // Create the shared memory buffer SharedMemory readSharedMemory = new SharedMemory ( name, SharedMemoryType.ReadOnly, true ); SharedMemory writeSharedMemory = new SharedMemory ( name, SharedMemoryType.WriteOnly, true ); DualQueue<LocalCallDescriptor> queue = new DualQueue<LocalCallDescriptor>(); DualQueue<LocalCallDescriptor> hiPriQueue = new DualQueue<LocalCallDescriptor>(); LocalCallDescriptorForPostLoggingMessagesToHost LargeLogEvent = CreatePostMessageCallDescriptor(1); LocalCallDescriptorForUpdateNodeSettings updateNodeSettings = new LocalCallDescriptorForUpdateNodeSettings(true, true, true); LocalCallDescriptorForPostBuildResult buildResult = new LocalCallDescriptorForPostBuildResult(CreateBuildResult()); LocalCallDescriptorForPostBuildRequests buildRequests = new LocalCallDescriptorForPostBuildRequests(CreateBuildRequest()); LocalCallDescriptorForRequestStatus requestStatus = new LocalCallDescriptorForRequestStatus(4); LocalCallDescriptorForPostStatus nodeStatusNoExcept = new LocalCallDescriptorForPostStatus(new NodeStatus(1, true, 2, 3, 4, true)); LocalCallDescriptorForPostStatus nodeStatusExcept = new LocalCallDescriptorForPostStatus(new NodeStatus(new Exception("I am bad"))); LocalCallDescriptorForShutdownNode shutdownNode = new LocalCallDescriptorForShutdownNode(Node.NodeShutdownLevel.BuildCompleteSuccess, true); LocalCallDescriptorForShutdownComplete shutdownComplete = new LocalCallDescriptorForShutdownComplete(Node.NodeShutdownLevel.BuildCompleteFailure, 0); LocalCallDescriptorForInitializationComplete initializeComplete = new LocalCallDescriptorForInitializationComplete(99); BuildPropertyGroup propertyGroup = new BuildPropertyGroup(); BuildProperty propertyToAdd = new BuildProperty("PropertyName", "Value"); propertyGroup.SetProperty(propertyToAdd); CacheEntry[] entries = CreateCacheEntries(); LocalCallDescriptorForGettingCacheEntriesFromHost getCacheEntries = new LocalCallDescriptorForGettingCacheEntriesFromHost(new string[] { "Hi", "Hello" }, "Name", propertyGroup, "3.5", CacheContentType.Properties); LocalCallDescriptorForPostingCacheEntriesToHost postCacheEntries = new LocalCallDescriptorForPostingCacheEntriesToHost(entries, "ScopeName", propertyGroup, "3.5", CacheContentType.BuildResults); LocalReplyCallDescriptor replyDescriptor1 = new LocalReplyCallDescriptor(1, entries); LocalReplyCallDescriptor replyDescriptor2 = new LocalReplyCallDescriptor(6, "Foo"); IDictionary environmentVariables = Environment.GetEnvironmentVariables(); Hashtable environmentVariablesHashtable = new Hashtable(environmentVariables); string className = "Class"; string loggerAssemblyName = "Class"; string loggerFileAssembly = null; string loggerSwitchParameters = "Class"; LoggerVerbosity verbosity = LoggerVerbosity.Detailed; LoggerDescription description = new LoggerDescription(className, loggerAssemblyName, loggerFileAssembly, loggerSwitchParameters, verbosity); LocalCallDescriptorForInitializeNode initializeNode = new LocalCallDescriptorForInitializeNode(environmentVariablesHashtable, new LoggerDescription[] { description }, 4, propertyGroup, ToolsetDefinitionLocations.ConfigurationFile, 5, String.Empty); queue.Enqueue(LargeLogEvent); queue.Enqueue(updateNodeSettings); queue.Enqueue(buildResult); queue.Enqueue(buildRequests); queue.Enqueue(requestStatus); queue.Enqueue(nodeStatusNoExcept); queue.Enqueue(nodeStatusExcept); queue.Enqueue(shutdownNode); queue.Enqueue(shutdownComplete); queue.Enqueue(initializeComplete); queue.Enqueue(getCacheEntries); queue.Enqueue(postCacheEntries); queue.Enqueue(replyDescriptor1); queue.Enqueue(replyDescriptor2); queue.Enqueue(initializeNode); writeSharedMemory.Write(queue, hiPriQueue, false); IList localCallDescriptorList = readSharedMemory.Read(); Assert.IsTrue(localCallDescriptorList.Count == 15); LocalCallDescriptorForPostLoggingMessagesToHost messageCallDescriptor = localCallDescriptorList[0] as LocalCallDescriptorForPostLoggingMessagesToHost; VerifyPostMessagesToHost(messageCallDescriptor, 1); LocalCallDescriptorForUpdateNodeSettings updateSettingsCallDescriptor = localCallDescriptorList[1] as LocalCallDescriptorForUpdateNodeSettings; VerifyUpdateSettings(updateSettingsCallDescriptor); LocalCallDescriptorForPostBuildResult buildResultCallDescriptor = localCallDescriptorList[2] as LocalCallDescriptorForPostBuildResult; CompareBuildResult(buildResultCallDescriptor); LocalCallDescriptorForPostBuildRequests buildRequestsCallDescriptor = localCallDescriptorList[3] as LocalCallDescriptorForPostBuildRequests; ComparebuildRequests(buildRequestsCallDescriptor); LocalCallDescriptorForRequestStatus requestStatusCallDescriptor = localCallDescriptorList[4] as LocalCallDescriptorForRequestStatus; Assert.IsTrue(requestStatusCallDescriptor.RequestId == 4); LocalCallDescriptorForPostStatus nodeStatus1CallDescriptor = localCallDescriptorList[5] as LocalCallDescriptorForPostStatus; VerifyNodeStatus1(nodeStatus1CallDescriptor); LocalCallDescriptorForPostStatus nodeStatus2CallDescriptor = localCallDescriptorList[6] as LocalCallDescriptorForPostStatus; VerifyNodeStatus2(nodeStatus2CallDescriptor); LocalCallDescriptorForShutdownNode shutdownNodeCallDescriptor = localCallDescriptorList[7] as LocalCallDescriptorForShutdownNode; Assert.IsTrue(shutdownNodeCallDescriptor.ShutdownLevel == Node.NodeShutdownLevel.BuildCompleteSuccess); Assert.IsTrue(shutdownNodeCallDescriptor.ExitProcess); LocalCallDescriptorForShutdownComplete shutdownNodeCompleteCallDescriptor = localCallDescriptorList[8] as LocalCallDescriptorForShutdownComplete; Assert.IsTrue(shutdownNodeCompleteCallDescriptor.ShutdownLevel == Node.NodeShutdownLevel.BuildCompleteFailure); LocalCallDescriptorForInitializationComplete initializeCompleteCallDescriptor = localCallDescriptorList[9] as LocalCallDescriptorForInitializationComplete; Assert.IsTrue(initializeCompleteCallDescriptor.ProcessId == 99); LocalCallDescriptorForGettingCacheEntriesFromHost getCacheEntriesCallDescriptor = localCallDescriptorList[10] as LocalCallDescriptorForGettingCacheEntriesFromHost; VerifyGetCacheEntryFromHost(getCacheEntriesCallDescriptor); LocalCallDescriptorForPostingCacheEntriesToHost postCacheEntriesCallDescriptor = localCallDescriptorList[11] as LocalCallDescriptorForPostingCacheEntriesToHost; Assert.IsTrue(string.Compare(postCacheEntriesCallDescriptor.ScopeName, "ScopeName", StringComparison.OrdinalIgnoreCase) == 0); Assert.IsTrue(string.Compare(postCacheEntriesCallDescriptor.ScopeProperties["PropertyName"].Value, "Value", StringComparison.OrdinalIgnoreCase) == 0); Assert.IsTrue(string.Compare(postCacheEntriesCallDescriptor.ScopeToolsVersion, "3.5", StringComparison.OrdinalIgnoreCase) == 0); Assert.IsTrue(postCacheEntriesCallDescriptor.ContentType == CacheContentType.BuildResults); VerifyGetCacheEntries(postCacheEntriesCallDescriptor.Entries); LocalReplyCallDescriptor reply1CallDescriptor = localCallDescriptorList[12] as LocalReplyCallDescriptor; Assert.IsTrue(reply1CallDescriptor.RequestingCallNumber == 1); VerifyGetCacheEntries((CacheEntry[])reply1CallDescriptor.ReplyData); LocalReplyCallDescriptor reply2CallDescriptor = localCallDescriptorList[13] as LocalReplyCallDescriptor; Assert.IsTrue(reply2CallDescriptor.RequestingCallNumber == 6); Assert.IsTrue(string.Compare("Foo", (string)reply2CallDescriptor.ReplyData, StringComparison.OrdinalIgnoreCase) == 0); LocalCallDescriptorForInitializeNode initializeCallDescriptor = localCallDescriptorList[14] as LocalCallDescriptorForInitializeNode; Assert.IsTrue(initializeCallDescriptor.ParentProcessId == 5); Assert.IsTrue(initializeCallDescriptor.NodeId == 4); Assert.IsTrue(initializeCallDescriptor.ToolsetSearchLocations == ToolsetDefinitionLocations.ConfigurationFile); Assert.IsTrue(string.Compare(initializeCallDescriptor.ParentGlobalProperties["PropertyName"].Value, "Value", StringComparison.OrdinalIgnoreCase) == 0); Assert.IsTrue(string.Compare(initializeCallDescriptor.NodeLoggers[0].Name, "Class", StringComparison.OrdinalIgnoreCase) == 0); IDictionary variables = Environment.GetEnvironmentVariables(); Assert.IsTrue(variables.Count == initializeCallDescriptor.EnvironmentVariables.Count); foreach (string key in variables.Keys) { Assert.IsTrue(string.Compare((string)initializeCallDescriptor.EnvironmentVariables[key], (string)variables[key], StringComparison.OrdinalIgnoreCase) == 0); } writeSharedMemory.Reset(); readSharedMemory.Reset(); readSharedMemory = null; writeSharedMemory = null; } [Test] public void TestLargeSharedMemorySend() { string name = Guid.NewGuid().ToString(); // Create the shared memory buffer SharedMemory readSharedMemory = new SharedMemory ( name, SharedMemoryType.ReadOnly, true ); SharedMemory writeSharedMemory = new SharedMemory ( name, SharedMemoryType.WriteOnly, true ); DualQueue<LocalCallDescriptor> queue = new DualQueue<LocalCallDescriptor>(); DualQueue<LocalCallDescriptor> hiPriQueue = new DualQueue<LocalCallDescriptor>(); int numberOfEvents = 2500; LocalCallDescriptorForPostLoggingMessagesToHost LargeLogEvent = CreatePostMessageCallDescriptor(numberOfEvents); queue.Enqueue(LargeLogEvent); writeSharedMemory.Write(queue, hiPriQueue, false); IList localCallDescriptorList = readSharedMemory.Read(); while (localCallDescriptorList == null || localCallDescriptorList.Count == 0) { writeSharedMemory.Write(queue, hiPriQueue, false); localCallDescriptorList = readSharedMemory.Read(); } VerifyPostMessagesToHost((LocalCallDescriptorForPostLoggingMessagesToHost)localCallDescriptorList[0], numberOfEvents); writeSharedMemory.Reset(); readSharedMemory.Reset(); readSharedMemory = null; writeSharedMemory = null; } [Test] public void TestHiPrioritySend() { string name = Guid.NewGuid().ToString(); // Create the shared memory buffer SharedMemory readSharedMemory = new SharedMemory ( name, SharedMemoryType.ReadOnly, true ); SharedMemory writeSharedMemory = new SharedMemory ( name, SharedMemoryType.WriteOnly, true ); DualQueue<LocalCallDescriptor> queue = new DualQueue<LocalCallDescriptor>(); DualQueue<LocalCallDescriptor> hiPriQueue = new DualQueue<LocalCallDescriptor>(); int numberOfEvents = 20; LocalCallDescriptorForPostLoggingMessagesToHost LargeLogEvent = CreatePostMessageCallDescriptor(numberOfEvents); queue.Enqueue(LargeLogEvent); LocalCallDescriptorForPostStatus nodeStatusExcept = new LocalCallDescriptorForPostStatus(new NodeStatus(new Exception("I am bad"))); hiPriQueue.Enqueue(nodeStatusExcept); writeSharedMemory.Write(queue, hiPriQueue, true); IList localCallDescriptorList = readSharedMemory.Read(); Assert.IsTrue(localCallDescriptorList.Count == 2); VerifyNodeStatus2((LocalCallDescriptorForPostStatus)localCallDescriptorList[0]); VerifyPostMessagesToHost((LocalCallDescriptorForPostLoggingMessagesToHost)localCallDescriptorList[1], numberOfEvents); writeSharedMemory.Reset(); readSharedMemory.Reset(); readSharedMemory = null; writeSharedMemory = null; } [Test] public void TestExistingBufferDetection() { string name = Guid.NewGuid().ToString(); // Create the shared memory buffer SharedMemory sharedMemory = new SharedMemory ( name, SharedMemoryType.ReadOnly, false // disallow duplicates ); Assert.IsTrue(sharedMemory.IsUsable, "Shared memory should be usable"); SharedMemory sharedMemoryDuplicate = new SharedMemory ( name, SharedMemoryType.ReadOnly, false // disallow duplicates ); Assert.IsFalse(sharedMemoryDuplicate.IsUsable, "Shared memory should not be usable"); sharedMemoryDuplicate.Dispose(); sharedMemoryDuplicate = new SharedMemory ( name, SharedMemoryType.ReadOnly, true // allow duplicates ); Assert.IsTrue(sharedMemoryDuplicate.IsUsable, "Shared memory should be usable"); sharedMemoryDuplicate.Dispose(); sharedMemory.Dispose(); } private void VerifyGetCacheEntries(CacheEntry[] entries) { Assert.IsTrue(entries[0] is BuildItemCacheEntry); Assert.IsTrue(string.Compare(entries[0].Name, "Badger" , StringComparison.OrdinalIgnoreCase) == 0); BuildItem[] buildItemArray = ((BuildItemCacheEntry)entries[0]).BuildItems; Assert.IsTrue(buildItemArray.Length == 2); Assert.IsTrue(string.Compare(buildItemArray[0].Include, "TestInclude1", StringComparison.OrdinalIgnoreCase) == 0); Assert.IsTrue(string.Compare(buildItemArray[1].Include, "TestInclude2", StringComparison.OrdinalIgnoreCase) == 0); Assert.IsTrue(string.Compare(buildItemArray[1].Name, "BuildItem2", StringComparison.OrdinalIgnoreCase) == 0); Assert.IsTrue(entries[1] is BuildResultCacheEntry); Assert.IsTrue(string.Compare(entries[1].Name, "Koi", StringComparison.OrdinalIgnoreCase) == 0); Assert.IsTrue(((BuildResultCacheEntry)entries[1]).BuildResult); buildItemArray = ((BuildResultCacheEntry)entries[1]).BuildItems; Assert.IsTrue(buildItemArray.Length == 2); Assert.IsTrue(string.Compare(buildItemArray[0].Include, "TestInclude1", StringComparison.OrdinalIgnoreCase) == 0); Assert.IsTrue(string.Compare(buildItemArray[1].Include, "TestInclude2", StringComparison.OrdinalIgnoreCase) == 0); Assert.IsTrue(string.Compare(buildItemArray[1].Name, "BuildItem2", StringComparison.OrdinalIgnoreCase) == 0); Assert.IsTrue(entries[2] is PropertyCacheEntry); Assert.IsTrue(string.Compare(((PropertyCacheEntry)entries[2]).Name, "Seagull", StringComparison.OrdinalIgnoreCase) == 0); Assert.IsTrue(string.Compare(((PropertyCacheEntry)entries[2]).Value, "bread", StringComparison.OrdinalIgnoreCase) == 0); } private static CacheEntry[] CreateCacheEntries() { CacheEntry[] entries = new CacheEntry[3]; BuildItem buildItem1 = new BuildItem("BuildItem1", "Item1"); BuildItem buildItem2 = new BuildItem("BuildItem2", "Item2"); buildItem1.Include = "TestInclude1"; buildItem2.Include = "TestInclude2"; BuildItem[] buildItems = new BuildItem[2]; buildItems[0] = buildItem1; buildItems[1] = buildItem2; entries[0] = new BuildItemCacheEntry("Badger", buildItems); entries[1] = new BuildResultCacheEntry("Koi", buildItems, true); entries[2] = new PropertyCacheEntry("Seagull", "bread"); return entries; } private static void VerifyGetCacheEntryFromHost(LocalCallDescriptorForGettingCacheEntriesFromHost getCacheEntriesCallDescriptor) { Assert.IsTrue(string.Compare(getCacheEntriesCallDescriptor.Names[0], "Hi", StringComparison.OrdinalIgnoreCase) == 0); Assert.IsTrue(string.Compare(getCacheEntriesCallDescriptor.Names[1], "Hello", StringComparison.OrdinalIgnoreCase) == 0); Assert.IsTrue(string.Compare(getCacheEntriesCallDescriptor.ScopeName, "Name", StringComparison.OrdinalIgnoreCase) == 0); Assert.IsTrue(string.Compare(getCacheEntriesCallDescriptor.ScopeProperties["PropertyName"].Value, "Value", StringComparison.OrdinalIgnoreCase) == 0); Assert.IsTrue(string.Compare(getCacheEntriesCallDescriptor.ScopeToolsVersion, "3.5", StringComparison.OrdinalIgnoreCase) == 0); Assert.IsTrue(getCacheEntriesCallDescriptor.ContentType == CacheContentType.Properties); } private static void VerifyNodeStatus2(LocalCallDescriptorForPostStatus nodeStatus2CallDescriptor) { Assert.IsTrue(nodeStatus2CallDescriptor.StatusOfNode.IsActive); Assert.IsFalse(nodeStatus2CallDescriptor.StatusOfNode.IsLaunchInProgress); Assert.IsTrue(nodeStatus2CallDescriptor.StatusOfNode.QueueDepth == 0); Assert.IsTrue(nodeStatus2CallDescriptor.StatusOfNode.RequestId == -1); Assert.IsTrue(string.Compare(nodeStatus2CallDescriptor.StatusOfNode.UnhandledException.Message, "I am bad", StringComparison.OrdinalIgnoreCase) == 0); } private static void VerifyNodeStatus1(LocalCallDescriptorForPostStatus nodeStatus1CallDescriptor) { Assert.IsTrue(nodeStatus1CallDescriptor.StatusOfNode.IsActive); Assert.IsTrue(nodeStatus1CallDescriptor.StatusOfNode.IsLaunchInProgress); Assert.IsTrue(nodeStatus1CallDescriptor.StatusOfNode.LastLoopActivity == 4); Assert.IsTrue(nodeStatus1CallDescriptor.StatusOfNode.LastTaskActivity == 3); Assert.IsTrue(nodeStatus1CallDescriptor.StatusOfNode.QueueDepth == 2); Assert.IsTrue(nodeStatus1CallDescriptor.StatusOfNode.RequestId == 1); Assert.IsTrue(nodeStatus1CallDescriptor.StatusOfNode.UnhandledException == null); } private static void ComparebuildRequests(LocalCallDescriptorForPostBuildRequests buildRequestsCallDescriptor) { BuildRequest[] requests = buildRequestsCallDescriptor.BuildRequests; Assert.IsTrue(requests.Length == 2); BuildEventContext testContext = new BuildEventContext(1, 2, 3, 4); ; foreach (BuildRequest request1 in requests) { Assert.IsTrue(request1.HandleId == 4, "Expected HandleId to Match"); Assert.IsTrue(request1.RequestId == 1, "Expected Request to Match"); Assert.IsTrue(string.Compare(request1.ProjectFileName, "ProjectFileName", StringComparison.OrdinalIgnoreCase) == 0, "Expected ProjectFileName to Match"); Assert.IsTrue(string.Compare(request1.TargetNames[0], "Build", StringComparison.OrdinalIgnoreCase) == 0, "Expected TargetNames to Match"); Assert.IsTrue(string.Compare(request1.ToolsetVersion, "Tool35", StringComparison.OrdinalIgnoreCase) == 0, "Expected ToolsetVersion to Match"); Assert.IsTrue(request1.TargetNames.Length == 1, "Expected there to be one TargetName"); Assert.IsTrue(request1.UnloadProjectsOnCompletion, "Expected UnloadProjectsOnCompletion to be true"); Assert.IsTrue(request1.UseResultsCache, "Expected UseResultsCache to be true"); Assert.IsTrue(string.Compare(request1.GlobalProperties["PropertyName"].Value, "Value", StringComparison.OrdinalIgnoreCase) == 0); Assert.AreEqual(request1.ParentBuildEventContext, testContext, "Expected BuildEventContext to Match"); } } private static BuildRequest[] CreateBuildRequest() { string projectFileName = "ProjectFileName"; string[] targetNames = new string[] { "Build" }; BuildPropertyGroup globalProperties = null; string toolsVersion = "Tool35"; int requestId = 1; int handleId = 4; globalProperties = new BuildPropertyGroup(); BuildProperty propertyToAdd = new BuildProperty("PropertyName", "Value"); globalProperties.SetProperty(propertyToAdd); BuildRequest[] requests = new BuildRequest[2]; requests[0] = new BuildRequest(handleId, projectFileName, targetNames, globalProperties, toolsVersion, requestId, true, true); requests[0].ParentBuildEventContext = new BuildEventContext(1, 2, 3, 4); requests[1] = new BuildRequest(handleId, projectFileName, targetNames, globalProperties, toolsVersion, requestId, true, true); requests[1].ParentBuildEventContext = new BuildEventContext(1, 2, 3, 4); return requests; } private static void CompareBuildResult(LocalCallDescriptorForPostBuildResult buildResultCallDescriptor) { BuildResult result = buildResultCallDescriptor.ResultOfBuild; Assert.IsTrue(result.ResultByTarget.Count == 1); Assert.IsTrue(((Target.BuildState)result.ResultByTarget["ONE"]) == Target.BuildState.CompletedSuccessfully); Assert.AreEqual(result.HandleId, 0, "Expected HandleId to Match"); Assert.AreEqual(result.RequestId, 1, "Expected RequestId to Match"); Assert.AreEqual(result.UseResultCache, true, "Expected UseResultCache to Match"); Assert.IsTrue(string.Compare(result.InitialTargets, "Fighter", StringComparison.OrdinalIgnoreCase) == 0, "Expected InitialTargets to Match"); Assert.IsTrue(string.Compare(result.DefaultTargets, "Foo", StringComparison.OrdinalIgnoreCase) == 0, "Expected DefaultTargets to Match"); BuildItem[] buildItemArray = ((BuildItem[])result.OutputsByTarget["TaskItems"]); Assert.IsTrue(buildItemArray.Length == 3); Assert.IsTrue(string.Compare(buildItemArray[0].Include, "TestInclude1", StringComparison.OrdinalIgnoreCase) == 0); Assertion.AssertEquals("m1", buildItemArray[0].GetMetadata("m")); Assertion.AssertEquals("n1", buildItemArray[0].GetMetadata("n")); Assert.IsTrue(string.Compare(buildItemArray[1].Include, "TestInclude2", StringComparison.OrdinalIgnoreCase) == 0); Assert.IsTrue(string.Compare(buildItemArray[1].Name, "BuildItem2", StringComparison.OrdinalIgnoreCase) == 0); Assertion.AssertEquals("m1", buildItemArray[2].GetMetadata("m")); Assertion.AssertEquals("n1", buildItemArray[2].GetMetadata("n")); Assertion.AssertEquals("o2", buildItemArray[2].GetMetadata("o")); Assert.AreEqual(result.TotalTime, 1, "Expected TotalTime to Match"); Assert.AreEqual(result.EngineTime, 2, "Expected EngineTime to Match"); Assert.AreEqual(result.TaskTime, 3, "Expected TaskTime to Match"); } private static BuildResult CreateBuildResult() { BuildItem buildItem1 = new BuildItem(null, "Item1"); BuildItem buildItem2 = new BuildItem("BuildItem2", "Item2"); BuildItem buildItem3 = BuildItem_Tests.GetXmlBackedItemWithDefinitionLibrary(); // default metadata m=m1 and o=o1 buildItem1.Include = "TestInclude1"; buildItem2.Include = "TestInclude2"; buildItem1.SetMetadata("m", "m1"); buildItem1.SetMetadata("n", "n1"); buildItem3.SetMetadata("n", "n1"); buildItem3.SetMetadata("o", "o2"); BuildItem[] taskItems = new BuildItem[3]; taskItems[0] = buildItem1; taskItems[1] = buildItem2; taskItems[2] = buildItem3; Dictionary<object, object> dictionary = new Dictionary<object, object>(); dictionary.Add("TaskItems", taskItems); BuildResult resultWithOutputs = new BuildResult(dictionary, new Hashtable(StringComparer.OrdinalIgnoreCase), true, 0, 1, 2, true, "Foo", "Fighter", 1, 2, 3); resultWithOutputs.ResultByTarget.Add("ONE", Target.BuildState.CompletedSuccessfully); resultWithOutputs.HandleId = 0; resultWithOutputs.RequestId = 1; return resultWithOutputs; } private static void VerifyUpdateSettings(LocalCallDescriptorForUpdateNodeSettings updateSettingsCallDescriptor) { Assert.IsNotNull(updateSettingsCallDescriptor); Assert.IsTrue(updateSettingsCallDescriptor.LogOnlyCriticalEvents); Assert.IsTrue(updateSettingsCallDescriptor.UseBreadthFirstTraversal); Assert.IsTrue(updateSettingsCallDescriptor.CentralizedLogging); } private static void VerifyPostMessagesToHost(LocalCallDescriptorForPostLoggingMessagesToHost messageCallDescriptor, int count) { Assert.IsTrue(messageCallDescriptor.BuildEvents.Length == count); for (int i = 0; i < count; i++) { Assert.IsTrue(string.Compare("aaaaaaaaaaaaaaa", messageCallDescriptor.BuildEvents[i].BuildEvent.Message, StringComparison.OrdinalIgnoreCase) == 0); } } private static LocalCallDescriptorForPostLoggingMessagesToHost CreatePostMessageCallDescriptor(int numberEvents) { NodeLoggingEvent[] eventArray = new NodeLoggingEvent[numberEvents]; for (int i = 0; i< numberEvents; i++) { BuildMessageEventArgs message = new BuildMessageEventArgs("aaaaaaaaaaaaaaa", "aaa", "a", MessageImportance.High); message.BuildEventContext = new BuildEventContext(1, 2, 3, 4); eventArray[i] = new NodeLoggingEvent(message); } LocalCallDescriptorForPostLoggingMessagesToHost LargeLogEvent = new LocalCallDescriptorForPostLoggingMessagesToHost(eventArray); return LargeLogEvent; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Threading.Tasks; using Newtonsoft.Json; using TM.Data.Pluralsight.Json; using TM.Shared; using TM.Shared.DownloadManager; namespace TM.Data.Pluralsight { internal class PluralsightArchiveDataService : DataServiceBase { private AsyncLazy<Dictionary<string, string>> _authorsInfoArchive; private AsyncLazy<Dictionary<string, string>> _coursesInfoArchive; private AsyncLazy<Dictionary<string, string>> _coursesToCArchive; private AsyncLazy<Dictionary<string, Specializations>> _courseSpecializationsArchive; private readonly string _archiveFolderPath; /// <exception cref="ArgumentNullException"> /// <paramref name="archiveFolderPath"/> or /// <paramref name="fileSystemProxy"/> is <see langword="null" />.</exception> public PluralsightArchiveDataService(string archiveFolderPath, IFileSystemProxy fileSystemProxy) : base(fileSystemProxy) { if (archiveFolderPath == null) throw new ArgumentNullException("archiveFolderPath"); if (fileSystemProxy == null) throw new ArgumentNullException("fileSystemProxy"); _archiveFolderPath = archiveFolderPath; _authorsInfoArchive = new AsyncLazy<Dictionary<string, string>>(async () => await MergeArchivesAsync<string>(AuthorsArchiveNamePrefix)); _coursesInfoArchive = new AsyncLazy<Dictionary<string, string>>(async () => { foreach (var entry in await _authorsInfoArchive) { UpdateAuthorCoursesDictionary(entry.Value); } return await MergeArchivesAsync<string>(CoursesArchiveNamePrefix); }); _coursesToCArchive = new AsyncLazy<Dictionary<string, string>>(async () => await MergeArchivesAsync<string>(CoursesToCArchiveNamePrefix)); _courseSpecializationsArchive = new AsyncLazy<Dictionary<string, Specializations>>(async () => await InitializeCourseSpecializationContainerAsync()); } #region DataServiceBase Overrides /// <exception cref="KeyNotFoundException"><paramref name="urlName" /> does not exist in the authors archive.</exception> protected internal override async Task<string> GetAuthorJsonDataAsync(string urlName) { var archive = await _authorsInfoArchive; try { var jsonData = archive[urlName]; return jsonData; } catch (KeyNotFoundException ex) { return AsyncHelper.RunSync(() => PluralsightWebDataService.CreateForDataQuery(new HttpDownloadManager()).GetAuthorJsonDataAsync(urlName)); } } protected override void UpdateAuthorsArchive(string urlName, string jsonData) { // no need to update archive } /// <exception cref="KeyNotFoundException"><paramref name="urlName" /> does not exist in the courses archive.</exception> protected internal override async Task<string> GetCourseJsonDataAsync(string urlName) { try { var archive = await _coursesInfoArchive; var jsonData = archive[urlName]; return jsonData; } catch (KeyNotFoundException ex) { return AsyncHelper.RunSync(() => PluralsightWebDataService.CreateForDataQuery(new HttpDownloadManager()).GetCourseJsonDataAsync(urlName)); } } protected override void UpdateCourseArchive(string urlName, string jsonData) { // no need to update archive } /// <exception cref="KeyNotFoundException"><paramref name="urlName" /> does not exist in the coursesToC archive.</exception> protected internal override async Task<string> GetCourseToCJsonDataAsync(string urlName) { try { var archive = await _coursesToCArchive; var jsonData = archive[urlName]; return jsonData; } catch (KeyNotFoundException ex) { return AsyncHelper.RunSync(() => PluralsightWebDataService.CreateForDataQuery(new HttpDownloadManager()).GetCourseToCJsonDataAsync(urlName)); } } protected override void UpdateCourseToCArchive(string urlName, string jsonData) { // no need to update archive } protected override async Task<Dictionary<string, Specializations>> InitializeCourseSpecializationContainerAsync() { var courseSpecializationsArchive = await GetLatestArchiveAsync<Specializations>(CourseSpecializationsArchiveNamePrefix); return courseSpecializationsArchive; } protected override async Task<Dictionary<string, Specializations>> GetInstanceOfCourseSpecializationsContainerAsync() { return await _courseSpecializationsArchive; } protected override void Dispose(bool disposing) { if (disposing) { _authorsInfoArchive = null; _coursesInfoArchive = null; _coursesToCArchive = null; _courseSpecializationsArchive = null; } base.Dispose(disposing); } #endregion #region Helpers internal async Task<Dictionary<string, TValue>> GetArchiveContentAsync<TValue>(string archivePath) { var fileText = await FileSystemProxy.ReadTextFromFileAsync(archivePath); var archiveFile = JsonConvert.DeserializeObject<ArchiveFile<TValue>>(fileText); var archiveContent = archiveFile.Content; return archiveContent; } internal async Task<Dictionary<string, TValue>> GetLatestArchiveAsync<TValue>(string archiveNamePrefix) { var archiveFilesName = FileSystemProxy.EnumerateFiles(_archiveFolderPath, archiveNamePrefix + "*", SearchOption.AllDirectories) .OrderByDescending(x => ExtractDateTime(x, archiveNamePrefix)) .First(); var archiveContent = await GetArchiveContentAsync<TValue>(archiveFilesName); return archiveContent; } internal async Task<Dictionary<string, TValue>> MergeArchivesAsync<TValue>(string archiveNamePrefix) { var archiveFilesNames = FileSystemProxy.EnumerateFiles(_archiveFolderPath, archiveNamePrefix + "*", SearchOption.AllDirectories) .OrderBy(x => ExtractDateTime(x, archiveNamePrefix)); var mergedArchivesContent = new Dictionary<string, TValue>(); foreach (var filesName in archiveFilesNames) { var archiveContent = await GetArchiveContentAsync<TValue>(filesName); foreach (var item in archiveContent) { mergedArchivesContent[item.Key] = item.Value; } } return mergedArchivesContent; } internal DateTime ExtractDateTime(string fileName, string archiveNamePrefix) { var extractedDateTimeString = fileName.Split(new[] { archiveNamePrefix, ArchiveFileExtension }, StringSplitOptions.RemoveEmptyEntries).Last().Trim(); var extractedDateTime = DateTime.ParseExact(extractedDateTimeString, DateTimeFormatPattern, DateTimeFormatInfo.InvariantInfo); return extractedDateTime; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Threading; using System; #if !ES_BUILD_AGAINST_DOTNET_V35 using Contract = System.Diagnostics.Contracts.Contract; #else using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract; #endif #if ES_BUILD_AGAINST_DOTNET_V35 using Microsoft.Internal; // for Tuple (can't define alias for open generic types so we "use" the whole namespace) #endif #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { // New in CLR4.0 internal enum ControllerCommand { // Strictly Positive numbers are for provider-specific commands, negative number are for 'shared' commands. 256 // The first 256 negative numbers are reserved for the framework. Update = 0, // Not used by EventPrividerBase. SendManifest = -1, Enable = -2, Disable = -3, }; /// <summary> /// Only here because System.Diagnostics.EventProvider needs one more extensibility hook (when it gets a /// controller callback) /// </summary> [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] internal partial class EventProvider : IDisposable { // This is the windows EVENT_DATA_DESCRIPTOR structure. We expose it because this is what // subclasses of EventProvider use when creating efficient (but unsafe) version of // EventWrite. We do make it a nested type because we really don't expect anyone to use // it except subclasses (and then only rarely). public struct EventData { internal unsafe ulong Ptr; internal uint Size; internal uint Reserved; } /// <summary> /// A struct characterizing ETW sessions (identified by the etwSessionId) as /// activity-tracing-aware or legacy. A session that's activity-tracing-aware /// has specified one non-zero bit in the reserved range 44-47 in the /// 'allKeywords' value it passed in for a specific EventProvider. /// </summary> public struct SessionInfo { internal int sessionIdBit; // the index of the bit used for tracing in the "reserved" field of AllKeywords internal int etwSessionId; // the machine-wide ETW session ID internal SessionInfo(int sessionIdBit_, int etwSessionId_) { sessionIdBit = sessionIdBit_; etwSessionId = etwSessionId_; } } private static bool m_setInformationMissing; [SecurityCritical] UnsafeNativeMethods.ManifestEtw.EtwEnableCallback m_etwCallback; // Trace Callback function private long m_regHandle; // Trace Registration Handle private byte m_level; // Tracing Level private long m_anyKeywordMask; // Trace Enable Flags private long m_allKeywordMask; // Match all keyword private List<SessionInfo> m_liveSessions; // current live sessions (Tuple<sessionIdBit, etwSessionId>) private bool m_enabled; // Enabled flag from Trace callback private Guid m_providerId; // Control Guid internal bool m_disposed; // when true provider has unregistered [ThreadStatic] private static WriteEventErrorCode s_returnCode; // The last return code private const int s_basicTypeAllocationBufferSize = 16; private const int s_etwMaxNumberArguments = 64; private const int s_etwAPIMaxRefObjCount = 8; private const int s_maxEventDataDescriptors = 128; private const int s_traceEventMaximumSize = 65482; private const int s_traceEventMaximumStringSize = 32724; [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] public enum WriteEventErrorCode : int { //check mapping to runtime codes NoError = 0, NoFreeBuffers = 1, EventTooBig = 2, NullInput = 3, TooManyArgs = 4, Other = 5, }; // Because callbacks happen on registration, and we need the callbacks for those setup // we can't call Register in the constructor. // // Note that EventProvider should ONLY be used by EventSource. In particular because // it registers a callback from native code you MUST dispose it BEFORE shutdown, otherwise // you may get native callbacks during shutdown when we have destroyed the delegate. // EventSource has special logic to do this, no one else should be calling EventProvider. internal EventProvider() { } /// <summary> /// This method registers the controlGuid of this class with ETW. We need to be running on /// Vista or above. If not a PlatformNotSupported exception will be thrown. If for some /// reason the ETW Register call failed a NotSupported exception will be thrown. /// </summary> // <SecurityKernel Critical="True" Ring="0"> // <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventRegister(System.Guid&,Microsoft.Win32.UnsafeNativeMethods.ManifestEtw+EtwEnableCallback,System.Void*,System.Int64&):System.UInt32" /> // <SatisfiesLinkDemand Name="Win32Exception..ctor(System.Int32)" /> // <ReferencesCritical Name="Method: EtwEnableCallBack(Guid&, Int32, Byte, Int64, Int64, Void*, Void*):Void" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] internal unsafe void Register(Guid providerGuid) { m_providerId = providerGuid; uint status; m_etwCallback = new UnsafeNativeMethods.ManifestEtw.EtwEnableCallback(EtwEnableCallBack); status = EventRegister(ref m_providerId, m_etwCallback); if (status != 0) { throw new ArgumentException(Win32Native.GetMessage(unchecked((int)status))); } } // // implement Dispose Pattern to early deregister from ETW insted of waiting for // the finalizer to call deregistration. // Once the user is done with the provider it needs to call Close() or Dispose() // If neither are called the finalizer will unregister the provider anyway // public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } // <SecurityKernel Critical="True" TreatAsSafe="Does not expose critical resource" Ring="1"> // <ReferencesCritical Name="Method: Deregister():Void" Ring="1" /> // </SecurityKernel> [System.Security.SecuritySafeCritical] protected virtual void Dispose(bool disposing) { // // explicit cleanup is done by calling Dispose with true from // Dispose() or Close(). The disposing arguement is ignored because there // are no unmanaged resources. // The finalizer calls Dispose with false. // // // check if the object has been allready disposed // if (m_disposed) return; // Disable the provider. m_enabled = false; // Do most of the work under a lock to avoid shutdown race. lock (EventListener.EventListenersLock) { // Double check if (m_disposed) return; Deregister(); m_disposed = true; } } /// <summary> /// This method deregisters the controlGuid of this class with ETW. /// /// </summary> public virtual void Close() { Dispose(); } ~EventProvider() { Dispose(false); } /// <summary> /// This method un-registers from ETW. /// </summary> // <SecurityKernel Critical="True" Ring="0"> // <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventUnregister(System.Int64):System.Int32" /> // </SecurityKernel> // TODO Check return code from UnsafeNativeMethods.ManifestEtw.EventUnregister [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "Microsoft.Win32.UnsafeNativeMethods.ManifestEtw.EventUnregister(System.Int64)"), System.Security.SecurityCritical] private unsafe void Deregister() { // // Unregister from ETW using the RegHandle saved from // the register call. // if (m_regHandle != 0) { EventUnregister(); m_regHandle = 0; } } // <SecurityKernel Critical="True" Ring="0"> // <UsesUnsafeCode Name="Parameter filterData of type: Void*" /> // <UsesUnsafeCode Name="Parameter callbackContext of type: Void*" /> // </SecurityKernel> [System.Security.SecurityCritical] unsafe void EtwEnableCallBack( [In] ref System.Guid sourceId, [In] int controlCode, [In] byte setLevel, [In] long anyKeyword, [In] long allKeyword, [In] UnsafeNativeMethods.ManifestEtw.EVENT_FILTER_DESCRIPTOR* filterData, [In] void* callbackContext ) { // This is an optional callback API. We will therefore ignore any failures that happen as a // result of turning on this provider as to not crash the app. // EventSource has code to validate whether initialization it expected to occur actually occurred try { ControllerCommand command = ControllerCommand.Update; IDictionary<string, string> args = null; bool skipFinalOnControllerCommand = false; if (controlCode == UnsafeNativeMethods.ManifestEtw.EVENT_CONTROL_CODE_ENABLE_PROVIDER) { m_enabled = true; m_level = setLevel; m_anyKeywordMask = anyKeyword; m_allKeywordMask = allKeyword; // ES_SESSION_INFO is a marker for additional places we #ifdeffed out to remove // references to EnumerateTraceGuidsEx. This symbol is actually not used because // today we use FEATURE_ACTIVITYSAMPLING to determine if this code is there or not. // However we put it in the #if so that we don't lose the fact that this feature // switch is at least partially independent of FEATURE_ACTIVITYSAMPLING List<Tuple<SessionInfo, bool>> sessionsChanged = GetSessions(); foreach (var session in sessionsChanged) { int sessionChanged = session.Item1.sessionIdBit; int etwSessionId = session.Item1.etwSessionId; bool bEnabling = session.Item2; skipFinalOnControllerCommand = true; args = null; // reinitialize args for every session... // if we get more than one session changed we have no way // of knowing which one "filterData" belongs to if (sessionsChanged.Count > 1) filterData = null; // read filter data only when a session is being *added* byte[] data; int keyIndex; if (bEnabling && GetDataFromController(etwSessionId, filterData, out command, out data, out keyIndex)) { args = new Dictionary<string, string>(4); while (keyIndex < data.Length) { int keyEnd = FindNull(data, keyIndex); int valueIdx = keyEnd + 1; int valueEnd = FindNull(data, valueIdx); if (valueEnd < data.Length) { string key = System.Text.Encoding.UTF8.GetString(data, keyIndex, keyEnd - keyIndex); string value = System.Text.Encoding.UTF8.GetString(data, valueIdx, valueEnd - valueIdx); args[key] = value; } keyIndex = valueEnd + 1; } } // execute OnControllerCommand once for every session that has changed. OnControllerCommand(command, args, (bEnabling ? sessionChanged : -sessionChanged), etwSessionId); } } else if (controlCode == UnsafeNativeMethods.ManifestEtw.EVENT_CONTROL_CODE_DISABLE_PROVIDER) { m_enabled = false; m_level = 0; m_anyKeywordMask = 0; m_allKeywordMask = 0; m_liveSessions = null; } else if (controlCode == UnsafeNativeMethods.ManifestEtw.EVENT_CONTROL_CODE_CAPTURE_STATE) { command = ControllerCommand.SendManifest; } else return; // per spec you ignore commands you don't recognize. if (!skipFinalOnControllerCommand) OnControllerCommand(command, args, 0, 0); } catch (Exception) { // We want to ignore any failures that happen as a result of turning on this provider as to // not crash the app. } } // New in CLR4.0 protected virtual void OnControllerCommand(ControllerCommand command, IDictionary<string, string> arguments, int sessionId, int etwSessionId) { } protected EventLevel Level { get { return (EventLevel)m_level; } set { m_level = (byte)value; } } protected EventKeywords MatchAnyKeyword { get { return (EventKeywords)m_anyKeywordMask; } set { m_anyKeywordMask = unchecked((long)value); } } protected EventKeywords MatchAllKeyword { get { return (EventKeywords)m_allKeywordMask; } set { m_allKeywordMask = unchecked((long)value); } } static private int FindNull(byte[] buffer, int idx) { while (idx < buffer.Length && buffer[idx] != 0) idx++; return idx; } /// <summary> /// Determines the ETW sessions that have been added and/or removed to the set of /// sessions interested in the current provider. It does so by (1) enumerating over all /// ETW sessions that enabled 'this.m_Guid' for the current process ID, and (2) /// comparing the current list with a list it cached on the previous invocation. /// /// The return value is a list of tuples, where the SessionInfo specifies the /// ETW session that was added or remove, and the bool specifies whether the /// session was added or whether it was removed from the set. /// </summary> [System.Security.SecuritySafeCritical] private List<Tuple<SessionInfo, bool>> GetSessions() { List<SessionInfo> liveSessionList = null; GetSessionInfo((Action<int, long>) ((etwSessionId, matchAllKeywords) => GetSessionInfoCallback(etwSessionId, matchAllKeywords, ref liveSessionList))); List<Tuple<SessionInfo, bool>> changedSessionList = new List<Tuple<SessionInfo, bool>>(); // first look for sessions that have gone away (or have changed) // (present in the m_liveSessions but not in the new liveSessionList) if (m_liveSessions != null) { foreach (SessionInfo s in m_liveSessions) { int idx; if ((idx = IndexOfSessionInList(liveSessionList, s.etwSessionId)) < 0 || (liveSessionList[idx].sessionIdBit != s.sessionIdBit)) changedSessionList.Add(Tuple.Create(s, false)); } } // next look for sessions that were created since the last callback (or have changed) // (present in the new liveSessionList but not in m_liveSessions) if (liveSessionList != null) { foreach (SessionInfo s in liveSessionList) { int idx; if ((idx = IndexOfSessionInList(m_liveSessions, s.etwSessionId)) < 0 || (m_liveSessions[idx].sessionIdBit != s.sessionIdBit)) changedSessionList.Add(Tuple.Create(s, true)); } } m_liveSessions = liveSessionList; return changedSessionList; } /// <summary> /// This method is the callback used by GetSessions() when it calls into GetSessionInfo(). /// It updates a List{SessionInfo} based on the etwSessionId and matchAllKeywords that /// GetSessionInfo() passes in. /// </summary> private static void GetSessionInfoCallback(int etwSessionId, long matchAllKeywords, ref List<SessionInfo> sessionList) { uint sessionIdBitMask = (uint)SessionMask.FromEventKeywords(unchecked((ulong)matchAllKeywords)); // an ETW controller that specifies more than the mandated bit for our EventSource // will be ignored... if (bitcount(sessionIdBitMask) > 1) return; if (sessionList == null) sessionList = new List<SessionInfo>(8); if (bitcount(sessionIdBitMask) == 1) { // activity-tracing-aware etw session sessionList.Add(new SessionInfo(bitindex(sessionIdBitMask) + 1, etwSessionId)); } else { // legacy etw session sessionList.Add(new SessionInfo(bitcount((uint)SessionMask.All) + 1, etwSessionId)); } } /// <summary> /// This method enumerates over all active ETW sessions that have enabled 'this.m_Guid' /// for the current process ID, calling 'action' for each session, and passing it the /// ETW session and the 'AllKeywords' the session enabled for the current provider. /// </summary> [System.Security.SecurityCritical] private unsafe void GetSessionInfo(Action<int, long> action) { // We wish the EventSource package to be legal for Windows Store applications. // Currently EnumerateTraceGuidsEx is not an allowed API, so we avoid its use here // and use the information in the registry instead. This means that ETW controllers // that do not publish their intent to the registry (basically all controllers EXCEPT // TraceEventSesion) will not work properly // However the framework version of EventSource DOES have ES_SESSION_INFO defined and thus // does not have this issue. #if ES_SESSION_INFO || !ES_BUILD_STANDALONE int buffSize = 256; // An initial guess that probably works most of the time. byte* buffer; for (; ; ) { var space = stackalloc byte[buffSize]; buffer = space; var hr = 0; fixed (Guid* provider = &m_providerId) { hr = UnsafeNativeMethods.ManifestEtw.EnumerateTraceGuidsEx(UnsafeNativeMethods.ManifestEtw.TRACE_QUERY_INFO_CLASS.TraceGuidQueryInfo, provider, sizeof(Guid), buffer, buffSize, ref buffSize); } if (hr == 0) break; if (hr != 122 /* ERROR_INSUFFICIENT_BUFFER */) return; } var providerInfos = (UnsafeNativeMethods.ManifestEtw.TRACE_GUID_INFO*)buffer; var providerInstance = (UnsafeNativeMethods.ManifestEtw.TRACE_PROVIDER_INSTANCE_INFO*)&providerInfos[1]; int processId = unchecked((int)Win32Native.GetCurrentProcessId()); // iterate over the instances of the EventProvider in all processes for (int i = 0; i < providerInfos->InstanceCount; i++) { if (providerInstance->Pid == processId) { var enabledInfos = (UnsafeNativeMethods.ManifestEtw.TRACE_ENABLE_INFO*)&providerInstance[1]; // iterate over the list of active ETW sessions "listening" to the current provider for (int j = 0; j < providerInstance->EnableCount; j++) action(enabledInfos[j].LoggerId, enabledInfos[j].MatchAllKeyword); } if (providerInstance->NextOffset == 0) break; Contract.Assert(0 <= providerInstance->NextOffset && providerInstance->NextOffset < buffSize); var structBase = (byte*)providerInstance; providerInstance = (UnsafeNativeMethods.ManifestEtw.TRACE_PROVIDER_INSTANCE_INFO*)&structBase[providerInstance->NextOffset]; } #else #if !ES_BUILD_PCL && !FEATURE_PAL // TODO command arguments don't work on PCL builds... // This code is only used in the Nuget Package Version of EventSource. because // the code above is using APIs baned from UWP apps. // // TODO: In addition to only working when TraceEventSession enables the provider, this code // also has a problem because TraceEvent does not clean up if the registry is stale // It is unclear if it is worth keeping, but for now we leave it as it does work // at least some of the time. // Determine our session from what is in the registry. string regKey = @"\Microsoft\Windows\CurrentVersion\Winevt\Publishers\{" + m_providerId + "}"; if (System.Runtime.InteropServices.Marshal.SizeOf(typeof(IntPtr)) == 8) regKey = @"Software" + @"\Wow6432Node" + regKey; else regKey = @"Software" + regKey; var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(regKey); if (key != null) { foreach (string valueName in key.GetValueNames()) { if (valueName.StartsWith("ControllerData_Session_")) { string strId = valueName.Substring(23); // strip of the ControllerData_Session_ int etwSessionId; if (int.TryParse(strId, out etwSessionId)) { // we need to assert this permission for partial trust scenarios (new RegistryPermission(RegistryPermissionAccess.Read, regKey)).Assert(); var data = key.GetValue(valueName) as byte[]; if (data != null) { var dataAsString = System.Text.Encoding.UTF8.GetString(data); int keywordIdx = dataAsString.IndexOf("EtwSessionKeyword"); if (0 <= keywordIdx) { int startIdx = keywordIdx + 18; int endIdx = dataAsString.IndexOf('\0', startIdx); string keywordBitString = dataAsString.Substring(startIdx, endIdx-startIdx); int keywordBit; if (0 < endIdx && int.TryParse(keywordBitString, out keywordBit)) action(etwSessionId, 1L << keywordBit); } } } } } } #endif #endif } /// <summary> /// Returns the index of the SesisonInfo from 'sessions' that has the specified 'etwSessionId' /// or -1 if the value is not present. /// </summary> private static int IndexOfSessionInList(List<SessionInfo> sessions, int etwSessionId) { if (sessions == null) return -1; // for non-coreclr code we could use List<T>.FindIndex(Predicate<T>), but we need this to compile // on coreclr as well for (int i = 0; i < sessions.Count; ++i) if (sessions[i].etwSessionId == etwSessionId) return i; return -1; } /// <summary> /// Gets any data to be passed from the controller to the provider. It starts with what is passed /// into the callback, but unfortunately this data is only present for when the provider is active /// at the time the controller issues the command. To allow for providers to activate after the /// controller issued a command, we also check the registry and use that to get the data. The function /// returns an array of bytes representing the data, the index into that byte array where the data /// starts, and the command being issued associated with that data. /// </summary> [System.Security.SecurityCritical] private unsafe bool GetDataFromController(int etwSessionId, UnsafeNativeMethods.ManifestEtw.EVENT_FILTER_DESCRIPTOR* filterData, out ControllerCommand command, out byte[] data, out int dataStart) { data = null; dataStart = 0; if (filterData == null) { #if !ES_BUILD_PCL && !FEATURE_PAL string regKey = @"\Microsoft\Windows\CurrentVersion\Winevt\Publishers\{" + m_providerId + "}"; if (System.Runtime.InteropServices.Marshal.SizeOf(typeof(IntPtr)) == 8) regKey = @"HKEY_LOCAL_MACHINE\Software" + @"\Wow6432Node" + regKey; else regKey = @"HKEY_LOCAL_MACHINE\Software" + regKey; string valueName = "ControllerData_Session_" + etwSessionId.ToString(CultureInfo.InvariantCulture); // we need to assert this permission for partial trust scenarios (new RegistryPermission(RegistryPermissionAccess.Read, regKey)).Assert(); data = Microsoft.Win32.Registry.GetValue(regKey, valueName, null) as byte[]; if (data != null) { // We only used the persisted data from the registry for updates. command = ControllerCommand.Update; return true; } #endif } else { if (filterData->Ptr != 0 && 0 < filterData->Size && filterData->Size <= 1024) { data = new byte[filterData->Size]; Marshal.Copy((IntPtr)filterData->Ptr, data, 0, data.Length); } command = (ControllerCommand)filterData->Type; return true; } command = ControllerCommand.Update; return false; } /// <summary> /// IsEnabled, method used to test if provider is enabled /// </summary> public bool IsEnabled() { return m_enabled; } /// <summary> /// IsEnabled, method used to test if event is enabled /// </summary> /// <param name="level"> /// Level to test /// </param> /// <param name="keywords"> /// Keyword to test /// </param> public bool IsEnabled(byte level, long keywords) { // // If not enabled at all, return false. // if (!m_enabled) { return false; } // This also covers the case of Level == 0. if ((level <= m_level) || (m_level == 0)) { // // Check if Keyword is enabled // if ((keywords == 0) || (((keywords & m_anyKeywordMask) != 0) && ((keywords & m_allKeywordMask) == m_allKeywordMask))) { return true; } } return false; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public static WriteEventErrorCode GetLastWriteEventError() { return s_returnCode; } // // Helper function to set the last error on the thread // private static void SetLastError(int error) { switch (error) { case UnsafeNativeMethods.ManifestEtw.ERROR_ARITHMETIC_OVERFLOW: case UnsafeNativeMethods.ManifestEtw.ERROR_MORE_DATA: s_returnCode = WriteEventErrorCode.EventTooBig; break; case UnsafeNativeMethods.ManifestEtw.ERROR_NOT_ENOUGH_MEMORY: s_returnCode = WriteEventErrorCode.NoFreeBuffers; break; } } // <SecurityKernel Critical="True" Ring="0"> // <UsesUnsafeCode Name="Local intptrPtr of type: IntPtr*" /> // <UsesUnsafeCode Name="Local intptrPtr of type: Int32*" /> // <UsesUnsafeCode Name="Local longptr of type: Int64*" /> // <UsesUnsafeCode Name="Local uintptr of type: UInt32*" /> // <UsesUnsafeCode Name="Local ulongptr of type: UInt64*" /> // <UsesUnsafeCode Name="Local charptr of type: Char*" /> // <UsesUnsafeCode Name="Local byteptr of type: Byte*" /> // <UsesUnsafeCode Name="Local shortptr of type: Int16*" /> // <UsesUnsafeCode Name="Local sbyteptr of type: SByte*" /> // <UsesUnsafeCode Name="Local ushortptr of type: UInt16*" /> // <UsesUnsafeCode Name="Local floatptr of type: Single*" /> // <UsesUnsafeCode Name="Local doubleptr of type: Double*" /> // <UsesUnsafeCode Name="Local boolptr of type: Boolean*" /> // <UsesUnsafeCode Name="Local guidptr of type: Guid*" /> // <UsesUnsafeCode Name="Local decimalptr of type: Decimal*" /> // <UsesUnsafeCode Name="Local booleanptr of type: Boolean*" /> // <UsesUnsafeCode Name="Parameter dataDescriptor of type: EventData*" /> // <UsesUnsafeCode Name="Parameter dataBuffer of type: Byte*" /> // </SecurityKernel> [System.Security.SecurityCritical] private static unsafe object EncodeObject(ref object data, ref EventData* dataDescriptor, ref byte* dataBuffer, ref uint totalEventSize) /*++ Routine Description: This routine is used by WriteEvent to unbox the object type and to fill the passed in ETW data descriptor. Arguments: data - argument to be decoded dataDescriptor - pointer to the descriptor to be filled (updated to point to the next empty entry) dataBuffer - storage buffer for storing user data, needed because cant get the address of the object (updated to point to the next empty entry) Return Value: null if the object is a basic type other than string or byte[]. String otherwise --*/ { Again: dataDescriptor->Reserved = 0; string sRet = data as string; byte[] blobRet = null; if (sRet != null) { dataDescriptor->Size = ((uint)sRet.Length + 1) * 2; } else if ((blobRet = data as byte[]) != null) { // first store array length *(int*)dataBuffer = blobRet.Length; dataDescriptor->Ptr = (ulong)dataBuffer; dataDescriptor->Size = 4; totalEventSize += dataDescriptor->Size; // then the array parameters dataDescriptor++; dataBuffer += s_basicTypeAllocationBufferSize; dataDescriptor->Size = (uint)blobRet.Length; } else if (data is IntPtr) { dataDescriptor->Size = (uint)sizeof(IntPtr); IntPtr* intptrPtr = (IntPtr*)dataBuffer; *intptrPtr = (IntPtr)data; dataDescriptor->Ptr = (ulong)intptrPtr; } else if (data is int) { dataDescriptor->Size = (uint)sizeof(int); int* intptr = (int*)dataBuffer; *intptr = (int)data; dataDescriptor->Ptr = (ulong)intptr; } else if (data is long) { dataDescriptor->Size = (uint)sizeof(long); long* longptr = (long*)dataBuffer; *longptr = (long)data; dataDescriptor->Ptr = (ulong)longptr; } else if (data is uint) { dataDescriptor->Size = (uint)sizeof(uint); uint* uintptr = (uint*)dataBuffer; *uintptr = (uint)data; dataDescriptor->Ptr = (ulong)uintptr; } else if (data is UInt64) { dataDescriptor->Size = (uint)sizeof(ulong); UInt64* ulongptr = (ulong*)dataBuffer; *ulongptr = (ulong)data; dataDescriptor->Ptr = (ulong)ulongptr; } else if (data is char) { dataDescriptor->Size = (uint)sizeof(char); char* charptr = (char*)dataBuffer; *charptr = (char)data; dataDescriptor->Ptr = (ulong)charptr; } else if (data is byte) { dataDescriptor->Size = (uint)sizeof(byte); byte* byteptr = (byte*)dataBuffer; *byteptr = (byte)data; dataDescriptor->Ptr = (ulong)byteptr; } else if (data is short) { dataDescriptor->Size = (uint)sizeof(short); short* shortptr = (short*)dataBuffer; *shortptr = (short)data; dataDescriptor->Ptr = (ulong)shortptr; } else if (data is sbyte) { dataDescriptor->Size = (uint)sizeof(sbyte); sbyte* sbyteptr = (sbyte*)dataBuffer; *sbyteptr = (sbyte)data; dataDescriptor->Ptr = (ulong)sbyteptr; } else if (data is ushort) { dataDescriptor->Size = (uint)sizeof(ushort); ushort* ushortptr = (ushort*)dataBuffer; *ushortptr = (ushort)data; dataDescriptor->Ptr = (ulong)ushortptr; } else if (data is float) { dataDescriptor->Size = (uint)sizeof(float); float* floatptr = (float*)dataBuffer; *floatptr = (float)data; dataDescriptor->Ptr = (ulong)floatptr; } else if (data is double) { dataDescriptor->Size = (uint)sizeof(double); double* doubleptr = (double*)dataBuffer; *doubleptr = (double)data; dataDescriptor->Ptr = (ulong)doubleptr; } else if (data is bool) { // WIN32 Bool is 4 bytes dataDescriptor->Size = 4; int* intptr = (int*)dataBuffer; if (((bool)data)) { *intptr = 1; } else { *intptr = 0; } dataDescriptor->Ptr = (ulong)intptr; } else if (data is Guid) { dataDescriptor->Size = (uint)sizeof(Guid); Guid* guidptr = (Guid*)dataBuffer; *guidptr = (Guid)data; dataDescriptor->Ptr = (ulong)guidptr; } else if (data is decimal) { dataDescriptor->Size = (uint)sizeof(decimal); decimal* decimalptr = (decimal*)dataBuffer; *decimalptr = (decimal)data; dataDescriptor->Ptr = (ulong)decimalptr; } else if (data is DateTime) { const long UTCMinTicks = 504911232000000000; long dateTimeTicks = 0; // We cannot translate dates sooner than 1/1/1601 in UTC. // To avoid getting an ArgumentOutOfRangeException we compare with 1/1/1601 DateTime ticks if (((DateTime)data).Ticks > UTCMinTicks) dateTimeTicks = ((DateTime)data).ToFileTimeUtc(); dataDescriptor->Size = (uint)sizeof(long); long* longptr = (long*)dataBuffer; *longptr = dateTimeTicks; dataDescriptor->Ptr = (ulong)longptr; } else { if (data is System.Enum) { Type underlyingType = Enum.GetUnderlyingType(data.GetType()); if (underlyingType == typeof(int)) { #if !ES_BUILD_PCL data = ((IConvertible)data).ToInt32(null); #else data = (int)data; #endif goto Again; } else if (underlyingType == typeof(long)) { #if !ES_BUILD_PCL data = ((IConvertible)data).ToInt64(null); #else data = (long)data; #endif goto Again; } } // To our eyes, everything else is a just a string if (data == null) sRet = ""; else sRet = data.ToString(); dataDescriptor->Size = ((uint)sRet.Length + 1) * 2; } totalEventSize += dataDescriptor->Size; // advance buffers dataDescriptor++; dataBuffer += s_basicTypeAllocationBufferSize; return (object)sRet ?? (object)blobRet; } /// <summary> /// WriteEvent, method to write a parameters with event schema properties /// </summary> /// <param name="eventDescriptor"> /// Event Descriptor for this event. /// </param> /// <param name="activityID"> /// A pointer to the activity ID GUID to log /// </param> /// <param name="childActivityID"> /// childActivityID is marked as 'related' to the current activity ID. /// </param> /// <param name="eventPayload"> /// Payload for the ETW event. /// </param> // <SecurityKernel Critical="True" Ring="0"> // <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventWrite(System.Int64,EventDescriptor&,System.UInt32,System.Void*):System.UInt32" /> // <UsesUnsafeCode Name="Local dataBuffer of type: Byte*" /> // <UsesUnsafeCode Name="Local pdata of type: Char*" /> // <UsesUnsafeCode Name="Local userData of type: EventData*" /> // <UsesUnsafeCode Name="Local userDataPtr of type: EventData*" /> // <UsesUnsafeCode Name="Local currentBuffer of type: Byte*" /> // <UsesUnsafeCode Name="Local v0 of type: Char*" /> // <UsesUnsafeCode Name="Local v1 of type: Char*" /> // <UsesUnsafeCode Name="Local v2 of type: Char*" /> // <UsesUnsafeCode Name="Local v3 of type: Char*" /> // <UsesUnsafeCode Name="Local v4 of type: Char*" /> // <UsesUnsafeCode Name="Local v5 of type: Char*" /> // <UsesUnsafeCode Name="Local v6 of type: Char*" /> // <UsesUnsafeCode Name="Local v7 of type: Char*" /> // <ReferencesCritical Name="Method: EncodeObject(Object&, EventData*, Byte*):String" Ring="1" /> // </SecurityKernel> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Performance-critical code")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] [System.Security.SecurityCritical] internal unsafe bool WriteEvent(ref EventDescriptor eventDescriptor, Guid* activityID, Guid* childActivityID, params object[] eventPayload) { int status = 0; if (IsEnabled(eventDescriptor.Level, eventDescriptor.Keywords)) { int argCount = 0; unsafe { argCount = eventPayload.Length; if (argCount > s_etwMaxNumberArguments) { s_returnCode = WriteEventErrorCode.TooManyArgs; return false; } uint totalEventSize = 0; int index; int refObjIndex = 0; List<int> refObjPosition = new List<int>(s_etwAPIMaxRefObjCount); List<object> dataRefObj = new List<object>(s_etwAPIMaxRefObjCount); EventData* userData = stackalloc EventData[2 * argCount]; EventData* userDataPtr = (EventData*)userData; byte* dataBuffer = stackalloc byte[s_basicTypeAllocationBufferSize * 2 * argCount]; // Assume 16 chars for non-string argument byte* currentBuffer = dataBuffer; // // The loop below goes through all the arguments and fills in the data // descriptors. For strings save the location in the dataString array. // Calculates the total size of the event by adding the data descriptor // size value set in EncodeObject method. // bool hasNonStringRefArgs = false; for (index = 0; index < eventPayload.Length; index++) { if (eventPayload[index] != null) { object supportedRefObj; supportedRefObj = EncodeObject(ref eventPayload[index], ref userDataPtr, ref currentBuffer, ref totalEventSize); if (supportedRefObj != null) { // EncodeObject advanced userDataPtr to the next empty slot int idx = (int)(userDataPtr - userData - 1); if (!(supportedRefObj is string)) { if (eventPayload.Length + idx + 1 - index > s_etwMaxNumberArguments) { s_returnCode = WriteEventErrorCode.TooManyArgs; return false; } hasNonStringRefArgs = true; } dataRefObj.Add(supportedRefObj); refObjPosition.Add(idx); refObjIndex++; } } else { s_returnCode = WriteEventErrorCode.NullInput; return false; } } // update argCount based on actual number of arguments written to 'userData' argCount = (int)(userDataPtr - userData); if (totalEventSize > s_traceEventMaximumSize) { s_returnCode = WriteEventErrorCode.EventTooBig; return false; } // the optimized path (using "fixed" instead of allocating pinned GCHandles if (!hasNonStringRefArgs && (refObjIndex < s_etwAPIMaxRefObjCount)) { // Fast path: at most 8 string arguments // ensure we have at least s_etwAPIMaxStringCount in dataString, so that // the "fixed" statement below works while (refObjIndex < s_etwAPIMaxRefObjCount) { dataRefObj.Add(null); ++refObjIndex; } // // now fix any string arguments and set the pointer on the data descriptor // fixed (char* v0 = (string)dataRefObj[0], v1 = (string)dataRefObj[1], v2 = (string)dataRefObj[2], v3 = (string)dataRefObj[3], v4 = (string)dataRefObj[4], v5 = (string)dataRefObj[5], v6 = (string)dataRefObj[6], v7 = (string)dataRefObj[7]) { userDataPtr = (EventData*)userData; if (dataRefObj[0] != null) { userDataPtr[refObjPosition[0]].Ptr = (ulong)v0; } if (dataRefObj[1] != null) { userDataPtr[refObjPosition[1]].Ptr = (ulong)v1; } if (dataRefObj[2] != null) { userDataPtr[refObjPosition[2]].Ptr = (ulong)v2; } if (dataRefObj[3] != null) { userDataPtr[refObjPosition[3]].Ptr = (ulong)v3; } if (dataRefObj[4] != null) { userDataPtr[refObjPosition[4]].Ptr = (ulong)v4; } if (dataRefObj[5] != null) { userDataPtr[refObjPosition[5]].Ptr = (ulong)v5; } if (dataRefObj[6] != null) { userDataPtr[refObjPosition[6]].Ptr = (ulong)v6; } if (dataRefObj[7] != null) { userDataPtr[refObjPosition[7]].Ptr = (ulong)v7; } status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper(m_regHandle, ref eventDescriptor, activityID, childActivityID, argCount, userData); } } else { // Slow path: use pinned handles userDataPtr = (EventData*)userData; GCHandle[] rgGCHandle = new GCHandle[refObjIndex]; for (int i = 0; i < refObjIndex; ++i) { // below we still use "fixed" to avoid taking dependency on the offset of the first field // in the object (the way we would need to if we used GCHandle.AddrOfPinnedObject) rgGCHandle[i] = GCHandle.Alloc(dataRefObj[i], GCHandleType.Pinned); if (dataRefObj[i] is string) { fixed (char* p = (string)dataRefObj[i]) userDataPtr[refObjPosition[i]].Ptr = (ulong)p; } else { fixed (byte* p = (byte[])dataRefObj[i]) userDataPtr[refObjPosition[i]].Ptr = (ulong)p; } } status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper(m_regHandle, ref eventDescriptor, activityID, childActivityID, argCount, userData); for (int i = 0; i < refObjIndex; ++i) { rgGCHandle[i].Free(); } } } } if (status != 0) { SetLastError((int)status); return false; } return true; } /// <summary> /// WriteEvent, method to be used by generated code on a derived class /// </summary> /// <param name="eventDescriptor"> /// Event Descriptor for this event. /// </param> /// <param name="activityID"> /// A pointer to the activity ID to log /// </param> /// <param name="childActivityID"> /// If this event is generating a child activity (WriteEventTransfer related activity) this is child activity /// This can be null for events that do not generate a child activity. /// </param> /// <param name="dataCount"> /// number of event descriptors /// </param> /// <param name="data"> /// pointer do the event data /// </param> // <SecurityKernel Critical="True" Ring="0"> // <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventWrite(System.Int64,EventDescriptor&,System.UInt32,System.Void*):System.UInt32" /> // </SecurityKernel> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] [System.Security.SecurityCritical] internal unsafe protected bool WriteEvent(ref EventDescriptor eventDescriptor, Guid* activityID, Guid* childActivityID, int dataCount, IntPtr data) { if (childActivityID != null) { // activity transfers are supported only for events that specify the Send or Receive opcode Contract.Assert((EventOpcode)eventDescriptor.Opcode == EventOpcode.Send || (EventOpcode)eventDescriptor.Opcode == EventOpcode.Receive || (EventOpcode)eventDescriptor.Opcode == EventOpcode.Start || (EventOpcode)eventDescriptor.Opcode == EventOpcode.Stop); } int status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper(m_regHandle, ref eventDescriptor, activityID, childActivityID, dataCount, (EventData*)data); if (status != 0) { SetLastError(status); return false; } return true; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] [System.Security.SecurityCritical] internal unsafe bool WriteEventRaw( ref EventDescriptor eventDescriptor, Guid* activityID, Guid* relatedActivityID, int dataCount, IntPtr data) { int status; status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper( m_regHandle, ref eventDescriptor, activityID, relatedActivityID, dataCount, (EventData*)data); if (status != 0) { SetLastError(status); return false; } return true; } // These are look-alikes to the Manifest based ETW OS APIs that have been shimmed to work // either with Manifest ETW or Classic ETW (if Manifest based ETW is not available). [SecurityCritical] private unsafe uint EventRegister(ref Guid providerId, UnsafeNativeMethods.ManifestEtw.EtwEnableCallback enableCallback) { m_providerId = providerId; m_etwCallback = enableCallback; return UnsafeNativeMethods.ManifestEtw.EventRegister(ref providerId, enableCallback, null, ref m_regHandle); } [SecurityCritical] private uint EventUnregister() { uint status = UnsafeNativeMethods.ManifestEtw.EventUnregister(m_regHandle); m_regHandle = 0; return status; } static int[] nibblebits = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; private static int bitcount(uint n) { int count = 0; for (; n != 0; n = n >> 4) count += nibblebits[n & 0x0f]; return count; } private static int bitindex(uint n) { Contract.Assert(bitcount(n) == 1); int idx = 0; while ((n & (1 << idx)) == 0) idx++; return idx; } } }
//! \file ImageTGA.cs //! \date Fri Jul 04 07:24:38 2014 //! \brief Targa image implementation. // // Copyright (C) 2014-2015 by morkt // // 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.IO; using System.Text; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; using System.ComponentModel.Composition; namespace GameRes { public class TgaMetaData : ImageMetaData { public short ImageType; public short ColormapType; public uint ColormapOffset; public ushort ColormapFirst; public ushort ColormapLength; public short ColormapDepth; public short Descriptor; } [Export(typeof(ImageFormat))] public class TgaFormat : ImageFormat { public override string Tag { get { return "TGA"; } } public override string Description { get { return "Truevision TGA image"; } } public override uint Signature { get { return 0; } } public override bool CanWrite { get { return true; } } public override ImageData Read (IBinaryStream stream, ImageMetaData metadata) { var reader = new Reader (stream, (TgaMetaData)metadata); var pixels = reader.Unpack(); return ImageData.Create (metadata, reader.Format, reader.Palette, pixels, reader.Stride); } public override void Write (Stream stream, ImageData image) { using (var file = new BinaryWriter (stream, System.Text.Encoding.ASCII, true)) { file.Write ((byte)0); // idlength file.Write ((byte)0); // colourmaptype file.Write ((byte)2); // datatypecode file.Write ((short)0); // colourmaporigin file.Write ((short)0); // colourmaplength file.Write ((byte)0); // colourmapdepth file.Write ((short)image.OffsetX); file.Write ((short)image.OffsetY); file.Write ((ushort)image.Width); file.Write ((ushort)image.Height); var bitmap = image.Bitmap; int bpp = 0; int stride = 0; byte descriptor = 0; if (PixelFormats.Bgr24 == bitmap.Format) { bpp = 24; stride = (int)image.Width*3; } else if (PixelFormats.Bgr32 == bitmap.Format) { bpp = 32; stride = (int)image.Width*4; } else { bpp = 32; stride = (int)image.Width*4; if (PixelFormats.Bgra32 != bitmap.Format) { var converted_bitmap = new FormatConvertedBitmap(); converted_bitmap.BeginInit(); converted_bitmap.Source = image.Bitmap; converted_bitmap.DestinationFormat = PixelFormats.Bgra32; converted_bitmap.EndInit(); bitmap = converted_bitmap; } } file.Write ((byte)bpp); file.Write (descriptor); byte[] row_data = new byte[stride]; Int32Rect rect = new Int32Rect (0, (int)image.Height, (int)image.Width, 1); for (uint row = 0; row < image.Height; ++row) { --rect.Y; bitmap.CopyPixels (rect, row_data, stride, 0); file.Write (row_data); } } } public override ImageMetaData ReadMetaData (IBinaryStream file) { short id_length = (short)file.ReadByte(); short colormap_type = (short)file.ReadByte(); if (colormap_type > 1) return null; short image_type = (short)file.ReadByte(); ushort colormap_first = file.ReadUInt16(); ushort colormap_length = file.ReadUInt16(); short colormap_depth = (short)file.ReadByte(); int pos_x = file.ReadInt16(); int pos_y = file.ReadInt16(); uint width = file.ReadUInt16(); uint height = file.ReadUInt16(); int bpp = file.ReadByte(); if (bpp != 32 && bpp != 24 && bpp != 16 && bpp != 15 && bpp != 8) return null; short descriptor = (short)file.ReadByte(); uint colormap_offset = (uint)(18 + id_length); switch (image_type) { default: return null; case 1: // Uncompressed, color-mapped images. case 9: // Runlength encoded color-mapped images. case 32: // Compressed color-mapped data, using Huffman, Delta, and // runlength encoding. case 33: // Compressed color-mapped data, using Huffman, Delta, and // runlength encoding. 4-pass quadtree-type process. if (colormap_depth != 24 && colormap_depth != 32) return null; break; case 2: // Uncompressed, RGB images. case 3: // Uncompressed, black and white images. case 10: // Runlength encoded RGB images. case 11: // Compressed, black and white images. break; } return new TgaMetaData { OffsetX = pos_x, OffsetY = pos_y, Width = width, Height = height, BPP = bpp, ImageType = image_type, ColormapType = colormap_type, ColormapOffset = colormap_offset, ColormapFirst = colormap_first, ColormapLength = colormap_length, ColormapDepth = colormap_depth, Descriptor = descriptor, }; } internal class Reader { IBinaryStream m_input; TgaMetaData m_meta; int m_width; int m_height; int m_stride; byte[] m_data; long m_image_offset; public PixelFormat Format { get; private set; } public BitmapPalette Palette { get; private set; } public int Stride { get { return m_stride; } } public byte[] Data { get { return m_data; } } public Reader (IBinaryStream stream, TgaMetaData meta) { m_input = stream; m_meta = meta; switch (meta.BPP) { default: throw new InvalidFormatException(); case 8: if (1 == meta.ColormapType) Format = PixelFormats.Indexed8; else Format = PixelFormats.Gray8; break; case 15: Format = PixelFormats.Bgr555; break; case 16: Format = PixelFormats.Bgr555; break; case 32: Format = PixelFormats.Bgra32; break; case 24: if (8 == (meta.Descriptor & 0xf)) Format = PixelFormats.Bgr32; else Format = PixelFormats.Bgr24; break; } int colormap_size = meta.ColormapLength * meta.ColormapDepth / 8; m_width = (int)meta.Width; m_height = (int)meta.Height; m_stride = m_width * ((Format.BitsPerPixel+7) / 8); m_image_offset = meta.ColormapOffset; if (1 == meta.ColormapType) { m_image_offset += colormap_size; m_input.Position = meta.ColormapOffset; ReadColormap (meta.ColormapLength, meta.ColormapDepth); } m_data = new byte[m_stride*m_height]; } private void ReadColormap (int length, int depth) { if (24 != depth && 32 != depth) throw new NotImplementedException(); int pixel_size = depth / 8; var palette_data = new byte[length * pixel_size]; if (palette_data.Length != m_input.Read (palette_data, 0, palette_data.Length)) throw new InvalidFormatException(); var palette = new Color[length]; for (int i = 0; i < palette.Length; ++i) { byte b = palette_data[i*pixel_size]; byte g = palette_data[i*pixel_size+1]; byte r = palette_data[i*pixel_size+2]; palette[i] = Color.FromRgb (r, g, b); } Palette = new BitmapPalette (palette); } public byte[] Unpack () { switch (m_meta.ImageType) { case 9: // Runlength encoded color-mapped images. case 32: // Compressed color-mapped data, using Huffman, Delta, and // runlength encoding. case 33: // Compressed color-mapped data, using Huffman, Delta, and // runlength encoding. 4-pass quadtree-type process. throw new NotImplementedException(); default: throw new InvalidFormatException(); case 1: // Uncompressed, color-mapped images. case 2: // Uncompressed, RGB images. case 3: // Uncompressed, black and white images. ReadRaw(); break; case 10: // Runlength encoded RGB images. case 11: // Compressed, black and white images. ReadRLE ((m_meta.BPP+7)/8); break; } return Data; } void ReadRaw () { m_input.Position = m_image_offset; if (0 != (m_meta.Descriptor & 0x20)) { if (m_data.Length != m_input.Read (m_data, 0, m_data.Length)) throw new InvalidFormatException(); } else { for (int row = m_height-1; row >= 0; --row) { if (m_stride != m_input.Read (m_data, row*m_stride, m_stride)) throw new InvalidFormatException(); } } } void ReadRLE (int pixel_size) { m_input.Position = m_image_offset; for (int dst = 0; dst < m_data.Length;) { int packet = m_input.ReadByte(); if (-1 == packet) break; int count = (packet & 0x7f) + 1; if (0 != (packet & 0x80)) { if (pixel_size != m_input.Read (m_data, dst, pixel_size)) break; int src = dst; dst += pixel_size; for (int i = 1; i < count && dst < m_data.Length; ++i) { Buffer.BlockCopy (m_data, src, m_data, dst, pixel_size); dst += pixel_size; } } else { count *= pixel_size; if (count != m_input.Read (m_data, dst, count)) break; dst += count; } } if (0 == (m_meta.Descriptor & 0x20)) { byte[] flipped = new byte[m_stride*m_height]; int dst = 0; for (int src = m_stride*(m_height-1); src >= 0; src -= m_stride) { Buffer.BlockCopy (m_data, src, flipped, dst, m_stride); dst += m_stride; } m_data = flipped; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: This is the value class representing a Unicode character ** Char methods until we create this functionality. ** ** ===========================================================*/ namespace System { using System; using System.Globalization; using System.Runtime; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Diagnostics; using System.Diagnostics.Contracts; [System.Runtime.InteropServices.ComVisible(true)] [Serializable] [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] public struct Char : IComparable, IConvertible , IComparable<Char>, IEquatable<Char> { // // Member Variables // internal char m_value; // // Public Constants // // The maximum character value. public const char MaxValue = (char) 0xFFFF; // The minimum character value. public const char MinValue = (char) 0x00; // Unicode category values from Unicode U+0000 ~ U+00FF. Store them in byte[] array to save space. private readonly static byte[] categoryForLatin1 = { (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0000 - 0007 (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0008 - 000F (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0010 - 0017 (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0018 - 001F (byte)UnicodeCategory.SpaceSeparator, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, // 0020 - 0027 (byte)UnicodeCategory.OpenPunctuation, (byte)UnicodeCategory.ClosePunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.DashPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, // 0028 - 002F (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, // 0030 - 0037 (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.OtherPunctuation, // 0038 - 003F (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 0040 - 0047 (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 0048 - 004F (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 0050 - 0057 (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.OpenPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.ClosePunctuation, (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.ConnectorPunctuation, // 0058 - 005F (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 0060 - 0067 (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 0068 - 006F (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 0070 - 0077 (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.OpenPunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.ClosePunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.Control, // 0078 - 007F (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0080 - 0087 (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0088 - 008F (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0090 - 0097 (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0098 - 009F (byte)UnicodeCategory.SpaceSeparator, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.OtherSymbol, // 00A0 - 00A7 (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.InitialQuotePunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.DashPunctuation, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.ModifierSymbol, // 00A8 - 00AF (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.OtherPunctuation, // 00B0 - 00B7 (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.FinalQuotePunctuation, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherPunctuation, // 00B8 - 00BF (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 00C0 - 00C7 (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 00C8 - 00CF (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.MathSymbol, // 00D0 - 00D7 (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00D8 - 00DF (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00E0 - 00E7 (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00E8 - 00EF (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.MathSymbol, // 00F0 - 00F7 (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00F8 - 00FF }; // Return true for all characters below or equal U+00ff, which is ASCII + Latin-1 Supplement. private static bool IsLatin1(char ch) { return (ch <= '\x00ff'); } // Return true for all characters below or equal U+007f, which is ASCII. private static bool IsAscii(char ch) { return (ch <= '\x007f'); } // Return the Unicode category for Unicode character <= 0x00ff. private static UnicodeCategory GetLatin1UnicodeCategory(char ch) { Debug.Assert(IsLatin1(ch), "Char.GetLatin1UnicodeCategory(): ch should be <= 007f"); return (UnicodeCategory)(categoryForLatin1[(int)ch]); } // // Private Constants // // // Overriden Instance Methods // // Calculate a hashcode for a 2 byte Unicode character. public override int GetHashCode() { return (int)m_value | ((int)m_value << 16); } // Used for comparing two boxed Char objects. // public override bool Equals(Object obj) { if (!(obj is Char)) { return false; } return (m_value==((Char)obj).m_value); } [System.Runtime.Versioning.NonVersionable] public bool Equals(Char obj) { return m_value == obj; } // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type Char, this method throws an ArgumentException. // [Pure] public int CompareTo(Object value) { if (value==null) { return 1; } if (!(value is Char)) { throw new ArgumentException (Environment.GetResourceString("Arg_MustBeChar")); } return (m_value-((Char)value).m_value); } [Pure] public int CompareTo(Char value) { return (m_value-value); } // Overrides System.Object.ToString. [Pure] public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); return Char.ToString(m_value); } [Pure] public String ToString(IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Char.ToString(m_value); } // // Formatting Methods // /*===================================ToString=================================== **This static methods takes a character and returns the String representation of it. ==============================================================================*/ // Provides a string representation of a character. [Pure] public static string ToString(char c) => string.CreateFromChar(c); public static char Parse(String s) { if (s==null) { throw new ArgumentNullException(nameof(s)); } Contract.EndContractBlock(); if (s.Length!=1) { throw new FormatException(Environment.GetResourceString("Format_NeedSingleChar")); } return s[0]; } public static bool TryParse(String s, out Char result) { result = '\0'; if (s == null) { return false; } if (s.Length != 1) { return false; } result = s[0]; return true; } // // Static Methods // /*=================================ISDIGIT====================================== **A wrapper for Char. Returns a boolean indicating whether ** **character c is considered to be a digit. ** ==============================================================================*/ // Determines whether a character is a digit. [Pure] public static bool IsDigit(char c) { if (IsLatin1(c)) { return (c >= '0' && c <= '9'); } return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.DecimalDigitNumber); } /*=================================CheckLetter===================================== ** Check if the specified UnicodeCategory belongs to the letter categories. ==============================================================================*/ internal static bool CheckLetter(UnicodeCategory uc) { switch(uc) { case (UnicodeCategory.UppercaseLetter): case (UnicodeCategory.LowercaseLetter): case (UnicodeCategory.TitlecaseLetter): case (UnicodeCategory.ModifierLetter): case (UnicodeCategory.OtherLetter): return (true); } return (false); } /*=================================ISLETTER===================================== **A wrapper for Char. Returns a boolean indicating whether ** **character c is considered to be a letter. ** ==============================================================================*/ // Determines whether a character is a letter. [Pure] public static bool IsLetter(char c) { if (IsLatin1(c)) { if (IsAscii(c)) { c |=(char)0x20; return ((c >= 'a' && c <= 'z')); } return (CheckLetter(GetLatin1UnicodeCategory(c))); } return (CheckLetter(CharUnicodeInfo.GetUnicodeCategory(c))); } private static bool IsWhiteSpaceLatin1(char c) { // There are characters which belong to UnicodeCategory.Control but are considered as white spaces. // We use code point comparisons for these characters here as a temporary fix. // U+0009 = <control> HORIZONTAL TAB // U+000a = <control> LINE FEED // U+000b = <control> VERTICAL TAB // U+000c = <contorl> FORM FEED // U+000d = <control> CARRIAGE RETURN // U+0085 = <control> NEXT LINE // U+00a0 = NO-BREAK SPACE if ((c == ' ') || (c >= '\x0009' && c <= '\x000d') || c == '\x00a0' || c == '\x0085') { return (true); } return (false); } /*===============================ISWHITESPACE=================================== **A wrapper for Char. Returns a boolean indicating whether ** **character c is considered to be a whitespace character. ** ==============================================================================*/ // Determines whether a character is whitespace. [Pure] public static bool IsWhiteSpace(char c) { if (IsLatin1(c)) { return (IsWhiteSpaceLatin1(c)); } return CharUnicodeInfo.IsWhiteSpace(c); } /*===================================IsUpper==================================== **Arguments: c -- the characater to be checked. **Returns: True if c is an uppercase character. ==============================================================================*/ // Determines whether a character is upper-case. [Pure] public static bool IsUpper(char c) { if (IsLatin1(c)) { if (IsAscii(c)) { return (c >= 'A' && c <= 'Z'); } return (GetLatin1UnicodeCategory(c)== UnicodeCategory.UppercaseLetter); } return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.UppercaseLetter); } /*===================================IsLower==================================== **Arguments: c -- the characater to be checked. **Returns: True if c is an lowercase character. ==============================================================================*/ // Determines whether a character is lower-case. [Pure] public static bool IsLower(char c) { if (IsLatin1(c)) { if (IsAscii(c)) { return (c >= 'a' && c <= 'z'); } return (GetLatin1UnicodeCategory(c)== UnicodeCategory.LowercaseLetter); } return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.LowercaseLetter); } internal static bool CheckPunctuation(UnicodeCategory uc) { switch (uc) { case UnicodeCategory.ConnectorPunctuation: case UnicodeCategory.DashPunctuation: case UnicodeCategory.OpenPunctuation: case UnicodeCategory.ClosePunctuation: case UnicodeCategory.InitialQuotePunctuation: case UnicodeCategory.FinalQuotePunctuation: case UnicodeCategory.OtherPunctuation: return (true); } return (false); } /*================================IsPunctuation================================= **Arguments: c -- the characater to be checked. **Returns: True if c is an punctuation mark ==============================================================================*/ // Determines whether a character is a punctuation mark. [Pure] public static bool IsPunctuation(char c){ if (IsLatin1(c)) { return (CheckPunctuation(GetLatin1UnicodeCategory(c))); } return (CheckPunctuation(CharUnicodeInfo.GetUnicodeCategory(c))); } /*=================================CheckLetterOrDigit===================================== ** Check if the specified UnicodeCategory belongs to the letter or digit categories. ==============================================================================*/ internal static bool CheckLetterOrDigit(UnicodeCategory uc) { switch (uc) { case UnicodeCategory.UppercaseLetter: case UnicodeCategory.LowercaseLetter: case UnicodeCategory.TitlecaseLetter: case UnicodeCategory.ModifierLetter: case UnicodeCategory.OtherLetter: case UnicodeCategory.DecimalDigitNumber: return (true); } return (false); } // Determines whether a character is a letter or a digit. [Pure] public static bool IsLetterOrDigit(char c) { if (IsLatin1(c)) { return (CheckLetterOrDigit(GetLatin1UnicodeCategory(c))); } return (CheckLetterOrDigit(CharUnicodeInfo.GetUnicodeCategory(c))); } /*===================================ToUpper==================================== ** ==============================================================================*/ // Converts a character to upper-case for the specified culture. // <;<;Not fully implemented>;>; public static char ToUpper(char c, CultureInfo culture) { if (culture==null) throw new ArgumentNullException(nameof(culture)); Contract.EndContractBlock(); return culture.TextInfo.ToUpper(c); } /*=================================TOUPPER====================================== **A wrapper for Char.toUpperCase. Converts character c to its ** **uppercase equivalent. If c is already an uppercase character or is not an ** **alphabetic, nothing happens. ** ==============================================================================*/ // Converts a character to upper-case for the default culture. // public static char ToUpper(char c) { return ToUpper(c, CultureInfo.CurrentCulture); } // Converts a character to upper-case for invariant culture. public static char ToUpperInvariant(char c) { return ToUpper(c, CultureInfo.InvariantCulture); } /*===================================ToLower==================================== ** ==============================================================================*/ // Converts a character to lower-case for the specified culture. // <;<;Not fully implemented>;>; public static char ToLower(char c, CultureInfo culture) { if (culture==null) throw new ArgumentNullException(nameof(culture)); Contract.EndContractBlock(); return culture.TextInfo.ToLower(c); } /*=================================TOLOWER====================================== **A wrapper for Char.toLowerCase. Converts character c to its ** **lowercase equivalent. If c is already a lowercase character or is not an ** **alphabetic, nothing happens. ** ==============================================================================*/ // Converts a character to lower-case for the default culture. public static char ToLower(char c) { return ToLower(c, CultureInfo.CurrentCulture); } // Converts a character to lower-case for invariant culture. public static char ToLowerInvariant(char c) { return ToLower(c, CultureInfo.InvariantCulture); } // // IConvertible implementation // [Pure] public TypeCode GetTypeCode() { return TypeCode.Char; } /// <internalonly/> bool IConvertible.ToBoolean(IFormatProvider provider) { throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Char", "Boolean")); } /// <internalonly/> char IConvertible.ToChar(IFormatProvider provider) { return m_value; } /// <internalonly/> sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } /// <internalonly/> byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } /// <internalonly/> short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } /// <internalonly/> ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } /// <internalonly/> int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } /// <internalonly/> uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } /// <internalonly/> long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } /// <internalonly/> ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } /// <internalonly/> float IConvertible.ToSingle(IFormatProvider provider) { throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Char", "Single")); } /// <internalonly/> double IConvertible.ToDouble(IFormatProvider provider) { throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Char", "Double")); } /// <internalonly/> Decimal IConvertible.ToDecimal(IFormatProvider provider) { throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Char", "Decimal")); } /// <internalonly/> DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Char", "DateTime")); } /// <internalonly/> Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } public static bool IsControl(char c) { if (IsLatin1(c)) { return (GetLatin1UnicodeCategory(c) == UnicodeCategory.Control); } return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.Control); } public static bool IsControl(String s, int index) { if (s==null) throw new ArgumentNullException(nameof(s)); if (((uint)index)>=((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { return (GetLatin1UnicodeCategory(c) == UnicodeCategory.Control); } return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.Control); } public static bool IsDigit(String s, int index) { if (s==null) throw new ArgumentNullException(nameof(s)); if (((uint)index)>=((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { return (c >= '0' && c <= '9'); } return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.DecimalDigitNumber); } public static bool IsLetter(String s, int index) { if (s==null) throw new ArgumentNullException(nameof(s)); if (((uint)index)>=((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { if (IsAscii(c)) { c |=(char)0x20; return ((c >= 'a' && c <= 'z')); } return (CheckLetter(GetLatin1UnicodeCategory(c))); } return (CheckLetter(CharUnicodeInfo.GetUnicodeCategory(s, index))); } public static bool IsLetterOrDigit(String s, int index) { if (s==null) throw new ArgumentNullException(nameof(s)); if (((uint)index)>=((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { return CheckLetterOrDigit(GetLatin1UnicodeCategory(c)); } return CheckLetterOrDigit(CharUnicodeInfo.GetUnicodeCategory(s, index)); } public static bool IsLower(String s, int index) { if (s==null) throw new ArgumentNullException(nameof(s)); if (((uint)index)>=((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { if (IsAscii(c)) { return (c >= 'a' && c <= 'z'); } return (GetLatin1UnicodeCategory(c)== UnicodeCategory.LowercaseLetter); } return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.LowercaseLetter); } /*=================================CheckNumber===================================== ** Check if the specified UnicodeCategory belongs to the number categories. ==============================================================================*/ internal static bool CheckNumber(UnicodeCategory uc) { switch (uc) { case (UnicodeCategory.DecimalDigitNumber): case (UnicodeCategory.LetterNumber): case (UnicodeCategory.OtherNumber): return (true); } return (false); } public static bool IsNumber(char c) { if (IsLatin1(c)) { if (IsAscii(c)) { return (c >= '0' && c <= '9'); } return (CheckNumber(GetLatin1UnicodeCategory(c))); } return (CheckNumber(CharUnicodeInfo.GetUnicodeCategory(c))); } public static bool IsNumber(String s, int index) { if (s==null) throw new ArgumentNullException(nameof(s)); if (((uint)index)>=((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { if (IsAscii(c)) { return (c >= '0' && c <= '9'); } return (CheckNumber(GetLatin1UnicodeCategory(c))); } return (CheckNumber(CharUnicodeInfo.GetUnicodeCategory(s, index))); } //////////////////////////////////////////////////////////////////////// // // IsPunctuation // // Determines if the given character is a punctuation character. // //////////////////////////////////////////////////////////////////////// public static bool IsPunctuation (String s, int index) { if (s==null) throw new ArgumentNullException(nameof(s)); if (((uint)index)>=((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { return (CheckPunctuation(GetLatin1UnicodeCategory(c))); } return (CheckPunctuation(CharUnicodeInfo.GetUnicodeCategory(s, index))); } /*================================= CheckSeparator ============================ ** Check if the specified UnicodeCategory belongs to the seprator categories. ==============================================================================*/ internal static bool CheckSeparator(UnicodeCategory uc) { switch (uc) { case UnicodeCategory.SpaceSeparator: case UnicodeCategory.LineSeparator: case UnicodeCategory.ParagraphSeparator: return (true); } return (false); } private static bool IsSeparatorLatin1(char c) { // U+00a0 = NO-BREAK SPACE // There is no LineSeparator or ParagraphSeparator in Latin 1 range. return (c == '\x0020' || c == '\x00a0'); } public static bool IsSeparator(char c) { if (IsLatin1(c)) { return (IsSeparatorLatin1(c)); } return (CheckSeparator(CharUnicodeInfo.GetUnicodeCategory(c))); } public static bool IsSeparator(String s, int index) { if (s==null) throw new ArgumentNullException(nameof(s)); if (((uint)index)>=((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { return (IsSeparatorLatin1(c)); } return (CheckSeparator(CharUnicodeInfo.GetUnicodeCategory(s, index))); } [Pure] public static bool IsSurrogate(char c) { return (c >= HIGH_SURROGATE_START && c <= LOW_SURROGATE_END); } [Pure] public static bool IsSurrogate(String s, int index) { if (s==null) { throw new ArgumentNullException(nameof(s)); } if (((uint)index)>=((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); return (IsSurrogate(s[index])); } /*================================= CheckSymbol ============================ ** Check if the specified UnicodeCategory belongs to the symbol categories. ==============================================================================*/ internal static bool CheckSymbol(UnicodeCategory uc) { switch (uc) { case (UnicodeCategory.MathSymbol): case (UnicodeCategory.CurrencySymbol): case (UnicodeCategory.ModifierSymbol): case (UnicodeCategory.OtherSymbol): return (true); } return (false); } public static bool IsSymbol(char c) { if (IsLatin1(c)) { return (CheckSymbol(GetLatin1UnicodeCategory(c))); } return (CheckSymbol(CharUnicodeInfo.GetUnicodeCategory(c))); } public static bool IsSymbol(String s, int index) { if (s==null) throw new ArgumentNullException(nameof(s)); if (((uint)index)>=((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); if (IsLatin1(s[index])) { return (CheckSymbol(GetLatin1UnicodeCategory(s[index]))); } return (CheckSymbol(CharUnicodeInfo.GetUnicodeCategory(s, index))); } public static bool IsUpper(String s, int index) { if (s==null) throw new ArgumentNullException(nameof(s)); if (((uint)index)>=((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); char c = s[index]; if (IsLatin1(c)) { if (IsAscii(c)) { return (c >= 'A' && c <= 'Z'); } return (GetLatin1UnicodeCategory(c)== UnicodeCategory.UppercaseLetter); } return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.UppercaseLetter); } public static bool IsWhiteSpace(String s, int index) { if (s==null) throw new ArgumentNullException(nameof(s)); if (((uint)index)>=((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); if (IsLatin1(s[index])) { return IsWhiteSpaceLatin1(s[index]); } return CharUnicodeInfo.IsWhiteSpace(s, index); } public static UnicodeCategory GetUnicodeCategory(char c) { if (IsLatin1(c)) { return (GetLatin1UnicodeCategory(c)); } return CharUnicodeInfo.InternalGetUnicodeCategory(c); } public static UnicodeCategory GetUnicodeCategory(String s, int index) { if (s==null) throw new ArgumentNullException(nameof(s)); if (((uint)index)>=((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); if (IsLatin1(s[index])) { return (GetLatin1UnicodeCategory(s[index])); } return CharUnicodeInfo.InternalGetUnicodeCategory(s, index); } public static double GetNumericValue(char c) { return CharUnicodeInfo.GetNumericValue(c); } public static double GetNumericValue(String s, int index) { if (s==null) throw new ArgumentNullException(nameof(s)); if (((uint)index)>=((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); return CharUnicodeInfo.GetNumericValue(s, index); } /*================================= IsHighSurrogate ============================ ** Check if a char is a high surrogate. ==============================================================================*/ [Pure] public static bool IsHighSurrogate(char c) { return ((c >= CharUnicodeInfo.HIGH_SURROGATE_START) && (c <= CharUnicodeInfo.HIGH_SURROGATE_END)); } [Pure] public static bool IsHighSurrogate(String s, int index) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (index < 0 || index >= s.Length) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); return (IsHighSurrogate(s[index])); } /*================================= IsLowSurrogate ============================ ** Check if a char is a low surrogate. ==============================================================================*/ [Pure] public static bool IsLowSurrogate(char c) { return ((c >= CharUnicodeInfo.LOW_SURROGATE_START) && (c <= CharUnicodeInfo.LOW_SURROGATE_END)); } [Pure] public static bool IsLowSurrogate(String s, int index) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (index < 0 || index >= s.Length) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); return (IsLowSurrogate(s[index])); } /*================================= IsSurrogatePair ============================ ** Check if the string specified by the index starts with a surrogate pair. ==============================================================================*/ [Pure] public static bool IsSurrogatePair(String s, int index) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (index < 0 || index >= s.Length) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); if (index + 1 < s.Length) { return (IsSurrogatePair(s[index], s[index+1])); } return (false); } [Pure] public static bool IsSurrogatePair(char highSurrogate, char lowSurrogate) { return ((highSurrogate >= CharUnicodeInfo.HIGH_SURROGATE_START && highSurrogate <= CharUnicodeInfo.HIGH_SURROGATE_END) && (lowSurrogate >= CharUnicodeInfo.LOW_SURROGATE_START && lowSurrogate <= CharUnicodeInfo.LOW_SURROGATE_END)); } internal const int UNICODE_PLANE00_END = 0x00ffff; // The starting codepoint for Unicode plane 1. Plane 1 contains 0x010000 ~ 0x01ffff. internal const int UNICODE_PLANE01_START = 0x10000; // The end codepoint for Unicode plane 16. This is the maximum code point value allowed for Unicode. // Plane 16 contains 0x100000 ~ 0x10ffff. internal const int UNICODE_PLANE16_END = 0x10ffff; internal const int HIGH_SURROGATE_START = 0x00d800; internal const int LOW_SURROGATE_END = 0x00dfff; /*================================= ConvertFromUtf32 ============================ ** Convert an UTF32 value into a surrogate pair. ==============================================================================*/ public static String ConvertFromUtf32(int utf32) { // For UTF32 values from U+00D800 ~ U+00DFFF, we should throw. They // are considered as irregular code unit sequence, but they are not illegal. if ((utf32 < 0 || utf32 > UNICODE_PLANE16_END) || (utf32 >= HIGH_SURROGATE_START && utf32 <= LOW_SURROGATE_END)) { throw new ArgumentOutOfRangeException(nameof(utf32), Environment.GetResourceString("ArgumentOutOfRange_InvalidUTF32")); } Contract.EndContractBlock(); if (utf32 < UNICODE_PLANE01_START) { // This is a BMP character. return (Char.ToString((char)utf32)); } unsafe { // This is a supplementary character. Convert it to a surrogate pair in UTF-16. utf32 -= UNICODE_PLANE01_START; uint surrogate = 0; // allocate 2 chars worth of stack space char* address = (char*)&surrogate; address[0] = (char)((utf32 / 0x400) + (int)CharUnicodeInfo.HIGH_SURROGATE_START); address[1] = (char)((utf32 % 0x400) + (int)CharUnicodeInfo.LOW_SURROGATE_START); return new string(address, 0, 2); } } /*=============================ConvertToUtf32=================================== ** Convert a surrogate pair to UTF32 value ==============================================================================*/ public static int ConvertToUtf32(char highSurrogate, char lowSurrogate) { if (!IsHighSurrogate(highSurrogate)) { throw new ArgumentOutOfRangeException(nameof(highSurrogate), Environment.GetResourceString("ArgumentOutOfRange_InvalidHighSurrogate")); } if (!IsLowSurrogate(lowSurrogate)) { throw new ArgumentOutOfRangeException(nameof(lowSurrogate), Environment.GetResourceString("ArgumentOutOfRange_InvalidLowSurrogate")); } Contract.EndContractBlock(); return (((highSurrogate - CharUnicodeInfo.HIGH_SURROGATE_START) * 0x400) + (lowSurrogate - CharUnicodeInfo.LOW_SURROGATE_START) + UNICODE_PLANE01_START); } /*=============================ConvertToUtf32=================================== ** Convert a character or a surrogate pair starting at index of the specified string ** to UTF32 value. ** The char pointed by index should be a surrogate pair or a BMP character. ** This method throws if a high-surrogate is not followed by a low surrogate. ** This method throws if a low surrogate is seen without preceding a high-surrogate. ==============================================================================*/ public static int ConvertToUtf32(String s, int index) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (index < 0 || index >= s.Length) { throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index")); } Contract.EndContractBlock(); // Check if the character at index is a high surrogate. int temp1 = (int)s[index] - CharUnicodeInfo.HIGH_SURROGATE_START; if (temp1 >= 0 && temp1 <= 0x7ff) { // Found a surrogate char. if (temp1 <= 0x3ff) { // Found a high surrogate. if (index < s.Length - 1) { int temp2 = (int)s[index+1] - CharUnicodeInfo.LOW_SURROGATE_START; if (temp2 >= 0 && temp2 <= 0x3ff) { // Found a low surrogate. return ((temp1 * 0x400) + temp2 + UNICODE_PLANE01_START); } else { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHighSurrogate", index), nameof(s)); } } else { // Found a high surrogate at the end of the string. throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHighSurrogate", index), nameof(s)); } } else { // Find a low surrogate at the character pointed by index. throw new ArgumentException(Environment.GetResourceString("Argument_InvalidLowSurrogate", index), nameof(s)); } } // Not a high-surrogate or low-surrogate. Genereate the UTF32 value for the BMP characters. return ((int)s[index]); } } }
// $ANTLR 2.7.4: "langparser.g" -> "AspectLanguageParser.cs"$ using antlr; using System.Text; using AspectSharp.Lang.AST; // Generate the header common to all output files. using System; using TokenBuffer = antlr.TokenBuffer; using TokenStreamException = antlr.TokenStreamException; using TokenStreamIOException = antlr.TokenStreamIOException; using ANTLRException = antlr.ANTLRException; using LLkParser = antlr.LLkParser; using Token = antlr.Token; using TokenStream = antlr.TokenStream; using RecognitionException = antlr.RecognitionException; using NoViableAltException = antlr.NoViableAltException; using MismatchedTokenException = antlr.MismatchedTokenException; using SemanticException = antlr.SemanticException; using ParserSharedInputState = antlr.ParserSharedInputState; using BitSet = antlr.collections.impl.BitSet; public class AspectLanguageParser : antlr.LLkParser { public const int EOF = 1; public const int NULL_TREE_LOOKAHEAD = 3; public const int ASPECT = 4; public const int FOR = 5; public const int IN = 6; public const int END = 7; public const int IMPORT = 8; public const int MIXINS = 9; public const int INCLUDE = 10; public const int INTERCEPTORS = 11; public const int ADVICEINTERCEPTOR = 12; public const int POINTCUT = 13; public const int METHOD = 14; public const int PROPERTY = 15; public const int PROPERTY_READ = 16; public const int PROPERTY_WRITE = 17; public const int ASSIGNFROM = 18; public const int CUSTOMMATCHER = 19; public const int EXCLUDES = 20; public const int INCLUDES = 21; public const int EOS = 22; public const int LBRACK = 23; public const int SEMI = 24; public const int RBRACK = 25; public const int STRING_LITERAL = 26; public const int COLON = 27; public const int ID = 28; public const int LCURLY = 29; public const int RCURLY = 30; public const int OR = 31; public const int ALL = 32; public const int COMMA = 33; public const int DOT = 34; public const int WS = 35; protected StringBuilder sbuilder = new StringBuilder(); protected LexicalInfo ToLexicalInfo(antlr.IToken token) { int line = token.getLine(); int startColumn = token.getColumn(); int endColumn = token.getColumn() + token.getText().Length; String filename = token.getFilename(); return new LexicalInfo(filename, line, startColumn, endColumn); } protected String methodAll(String s) { if (s == "*") return ".*"; return s; } protected void initialize() { tokenNames = tokenNames_; } protected AspectLanguageParser(TokenBuffer tokenBuf, int k) : base(tokenBuf, k) { initialize(); } public AspectLanguageParser(TokenBuffer tokenBuf) : this(tokenBuf,1) { } protected AspectLanguageParser(TokenStream lexer, int k) : base(lexer,k) { initialize(); } public AspectLanguageParser(TokenStream lexer) : this(lexer,1) { } public AspectLanguageParser(ParserSharedInputState state) : base(state,1) { initialize(); } public EngineConfiguration start() //throws RecognitionException, TokenStreamException { EngineConfiguration conf; conf = new EngineConfiguration(); try { // for error handling { // ( ... )* for (;;) { if ((LA(1)==EOS)) { match(EOS); } else { goto _loop3_breakloop; } } _loop3_breakloop: ; } // ( ... )* { // ( ... )* for (;;) { if ((LA(1)==IMPORT)) { import_directive(conf); } else { goto _loop5_breakloop; } } _loop5_breakloop: ; } // ( ... )* { // ( ... )* for (;;) { if ((LA(1)==INTERCEPTORS)) { interceptors_global(conf); } else { goto _loop7_breakloop; } } _loop7_breakloop: ; } // ( ... )* { // ( ... )* for (;;) { if ((LA(1)==MIXINS)) { mixins_global(conf); } else { goto _loop9_breakloop; } } _loop9_breakloop: ; } // ( ... )* { // ( ... )* for (;;) { if ((LA(1)==ASPECT)) { aspects(conf); } else { goto _loop11_breakloop; } } _loop11_breakloop: ; } // ( ... )* match(Token.EOF_TYPE); } catch (RecognitionException ex) { reportError(ex); consume(); consumeUntil(tokenSet_0_); } return conf; } protected void import_directive( EngineConfiguration conf ) //throws RecognitionException, TokenStreamException { IToken i = null; String ns; String assemblyName; ImportDirective import = null; try { // for error handling i = LT(1); match(IMPORT); ns=identifier(); import = new ImportDirective( ToLexicalInfo(i), ns ); conf.Imports.Add(import); { switch ( LA(1) ) { case IN: { match(IN); assemblyName=identifier(); import.AssemblyReference = new AssemblyReference( ToLexicalInfo(i), assemblyName); break; } case EOF: case ASPECT: case IMPORT: case MIXINS: case INTERCEPTORS: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } catch (RecognitionException ex) { reportError(ex); consume(); consumeUntil(tokenSet_1_); } } protected void interceptors_global( EngineConfiguration conf ) //throws RecognitionException, TokenStreamException { try { // for error handling match(INTERCEPTORS); keytypepair(conf.Interceptors); } catch (RecognitionException ex) { reportError(ex); consume(); consumeUntil(tokenSet_2_); } } protected void mixins_global( EngineConfiguration conf ) //throws RecognitionException, TokenStreamException { try { // for error handling match(MIXINS); keytypepair(conf.Mixins); } catch (RecognitionException ex) { reportError(ex); consume(); consumeUntil(tokenSet_3_); } } protected void aspects( EngineConfiguration conf ) //throws RecognitionException, TokenStreamException { IToken a = null; IToken aspectId = null; AspectDefinition aspect = null; TargetTypeDefinition target = null; TypeReference tr = null; try { // for error handling a = LT(1); match(ASPECT); aspectId = LT(1); match(ID); match(FOR); aspect = new AspectDefinition( ToLexicalInfo(a), aspectId.getText() ); conf.Aspects.Add(aspect); { switch ( LA(1) ) { case ID: { tr=type_name_def(); target = new TargetTypeDefinition( tr ); target.TargetStrategy = TargetStrategyEnum.SingleType; aspect.TargetType = target; break; } case LBRACK: { match(LBRACK); target = new TargetTypeDefinition( ); aspect.TargetType = target; String namespaceRegEx = null; { switch ( LA(1) ) { case ASSIGNFROM: { match(ASSIGNFROM); match(LCURLY); tr=type_name_def(); match(RCURLY); target.TargetStrategy = TargetStrategyEnum.Assignable; target.AssignType = tr; break; } case CUSTOMMATCHER: { match(CUSTOMMATCHER); match(LCURLY); tr=type_name_def(); match(RCURLY); target.TargetStrategy = TargetStrategyEnum.Custom; target.CustomMatcherType = tr; break; } case ID: { { namespaceRegEx=identifier(); target.TargetStrategy = TargetStrategyEnum.Namespace; target.NamespaceRoot = namespaceRegEx; { switch ( LA(1) ) { case EXCLUDES: { match(EXCLUDES); match(LCURLY); type_list(target.Excludes); match(RCURLY); break; } case RBRACK: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } match(RBRACK); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } { { // ( ... )* for (;;) { if ((LA(1)==INCLUDE)) { include(aspect); } else { goto _loop33_breakloop; } } _loop33_breakloop: ; } // ( ... )* { // ( ... )* for (;;) { if ((LA(1)==POINTCUT)) { pointcut(aspect); } else { goto _loop35_breakloop; } } _loop35_breakloop: ; } // ( ... )* } match(END); } catch (RecognitionException ex) { reportError(ex); consume(); consumeUntil(tokenSet_4_); } } protected String identifier() //throws RecognitionException, TokenStreamException { String value; IToken id = null; IToken id2 = null; value = null; sbuilder.Length = 0; try { // for error handling id = LT(1); match(ID); sbuilder.Append(id.getText()); value = sbuilder.ToString(); { // ( ... )* for (;;) { if ((LA(1)==DOT)) { match(DOT); id2 = LT(1); match(ID); sbuilder.Append('.'); sbuilder.Append(id2.getText()); } else { goto _loop65_breakloop; } } _loop65_breakloop: ; } // ( ... )* value = sbuilder.ToString(); } catch (RecognitionException ex) { reportError(ex); consume(); consumeUntil(tokenSet_5_); } return value; } protected void keytypepair( IDeclarationCollection collection ) //throws RecognitionException, TokenStreamException { try { // for error handling match(LBRACK); { { pairvalue(collection); { // ( ... )* for (;;) { if ((LA(1)==SEMI)) { match(SEMI); pairvalue(collection); } else { goto _loop20_breakloop; } } _loop20_breakloop: ; } // ( ... )* } } match(RBRACK); } catch (RecognitionException ex) { reportError(ex); consume(); consumeUntil(tokenSet_2_); } } protected void pairvalue( IDeclarationCollection collection ) //throws RecognitionException, TokenStreamException { IToken keyToken = null; DefinitionBase definition = null; try { // for error handling keyToken = LT(1); match(STRING_LITERAL); match(COLON); String key = keyToken.getText(); definition = collection.Add( key, ToLexicalInfo(keyToken) ); type_name(definition); } catch (RecognitionException ex) { reportError(ex); consume(); consumeUntil(tokenSet_6_); } } protected void type_name( DefinitionBase definition ) //throws RecognitionException, TokenStreamException { TypeReference tr = null; try { // for error handling tr=type_name_def(); definition.TypeReference = tr; } catch (RecognitionException ex) { reportError(ex); consume(); consumeUntil(tokenSet_6_); } } protected TypeReference type_name_or_ref() //throws RecognitionException, TokenStreamException { TypeReference type; IToken refTypeToken = null; type = null; try { // for error handling switch ( LA(1) ) { case STRING_LITERAL: { refTypeToken = LT(1); match(STRING_LITERAL); type = new TypeReference(); type.LinkRef = refTypeToken.getText(); break; } case ID: { type=type_name_def(); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } catch (RecognitionException ex) { reportError(ex); consume(); consumeUntil(tokenSet_7_); } return type; } protected TypeReference type_name_def() //throws RecognitionException, TokenStreamException { TypeReference type; IToken i = null; type = new TypeReference(); String typeToken = null; String assemblyToken = null; try { // for error handling typeToken=identifier(); type.TypeName = typeToken; { switch ( LA(1) ) { case IN: { i = LT(1); match(IN); assemblyToken=identifier(); type.AssemblyReference = new AssemblyReference( ToLexicalInfo(i), assemblyToken ); break; } case END: case INCLUDE: case POINTCUT: case SEMI: case RBRACK: case RCURLY: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } catch (RecognitionException ex) { reportError(ex); consume(); consumeUntil(tokenSet_8_); } return type; } protected void type_list( TypeReferenceCollection types ) //throws RecognitionException, TokenStreamException { TypeReference tr = null; try { // for error handling tr=type_name_def(); types.Add(tr); { // ( ... )* for (;;) { if ((LA(1)==SEMI)) { match(SEMI); tr=type_name_def(); types.Add(tr); } else { goto _loop38_breakloop; } } _loop38_breakloop: ; } // ( ... )* } catch (RecognitionException ex) { reportError(ex); consume(); consumeUntil(tokenSet_9_); } } protected void include( AspectDefinition aspect ) //throws RecognitionException, TokenStreamException { IToken i = null; TypeReference tr = null; MixinDefinition md; try { // for error handling i = LT(1); match(INCLUDE); md = new MixinDefinition( ToLexicalInfo(i) ); tr=type_name_or_ref(); md.TypeReference = tr; aspect.Mixins.Add( md ); } catch (RecognitionException ex) { reportError(ex); consume(); consumeUntil(tokenSet_10_); } } protected void pointcut( AspectDefinition aspect ) //throws RecognitionException, TokenStreamException { IToken p = null; PointCutDefinition pointcut = null; PointCutFlags flags = PointCutFlags.Unspecified; try { // for error handling p = LT(1); match(POINTCUT); flags=pointcutflags(); pointcut = new PointCutDefinition( ToLexicalInfo(p), flags ); aspect.PointCuts.Add( pointcut ); pointcuttarget(pointcut); advices(pointcut); match(END); } catch (RecognitionException ex) { reportError(ex); consume(); consumeUntil(tokenSet_11_); } } protected PointCutFlags pointcutflags() //throws RecognitionException, TokenStreamException { PointCutFlags flags; flags = PointCutFlags.Unspecified; try { // for error handling flags=pointcutflag(flags); { switch ( LA(1) ) { case OR: { match(OR); flags=pointcutflag(flags); break; } case LCURLY: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } catch (RecognitionException ex) { reportError(ex); consume(); consumeUntil(tokenSet_12_); } return flags; } protected void pointcuttarget( PointCutDefinition pointcut ) //throws RecognitionException, TokenStreamException { try { // for error handling match(LCURLY); pointcutsignature(pointcut); } catch (RecognitionException ex) { reportError(ex); consume(); consumeUntil(tokenSet_13_); } } protected void advices( PointCutDefinition pointcut ) //throws RecognitionException, TokenStreamException { try { // for error handling { // ( ... )* for (;;) { if ((LA(1)==ADVICEINTERCEPTOR)) { advice(pointcut); } else { goto _loop43_breakloop; } } _loop43_breakloop: ; } // ( ... )* } catch (RecognitionException ex) { reportError(ex); consume(); consumeUntil(tokenSet_14_); } } protected void advice( PointCutDefinition pointcut ) //throws RecognitionException, TokenStreamException { IToken i = null; TypeReference tr = null; InterceptorDefinition interDef = null; try { // for error handling i = LT(1); match(ADVICEINTERCEPTOR); interDef = new InterceptorDefinition( ToLexicalInfo(i) ); match(LCURLY); tr=type_name_or_ref(); interDef.TypeReference = tr; pointcut.Advices.Add( interDef ); match(RCURLY); } catch (RecognitionException ex) { reportError(ex); consume(); consumeUntil(tokenSet_13_); } } protected PointCutFlags pointcutflag( PointCutFlags flags ) //throws RecognitionException, TokenStreamException { PointCutFlags retValue; retValue = flags; try { // for error handling switch ( LA(1) ) { case METHOD: { match(METHOD); retValue |= PointCutFlags.Method; break; } case PROPERTY: { match(PROPERTY); retValue |= PointCutFlags.Property; break; } case PROPERTY_READ: { match(PROPERTY_READ); retValue |= PointCutFlags.PropertyRead; break; } case PROPERTY_WRITE: { match(PROPERTY_WRITE); retValue |= PointCutFlags.PropertyWrite; break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } catch (RecognitionException ex) { reportError(ex); consume(); consumeUntil(tokenSet_15_); } return retValue; } protected void pointcutsignature( PointCutDefinition pointcut ) //throws RecognitionException, TokenStreamException { try { // for error handling pointcutsig1(pointcut); } catch (RecognitionException ex) { reportError(ex); consume(); consumeUntil(tokenSet_13_); } } protected void pointcutsig1( PointCutDefinition pointcut ) //throws RecognitionException, TokenStreamException { String part1; MethodSignature ms = null; try { // for error handling { switch ( LA(1) ) { case ALL: { match(ALL); part1 = "*"; ms = AllMethodSignature.Instance; break; } case ID: { part1=reg_ex(true); ms = new MethodSignature(part1, methodAll("*")); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } pointcut.Method = pointcutsig2(part1, ms); } catch (RecognitionException ex) { reportError(ex); consume(); consumeUntil(tokenSet_13_); } } protected String reg_ex( Boolean allowALL ) //throws RecognitionException, TokenStreamException { String value; IToken id = null; value = null; sbuilder.Length = 0; try { // for error handling { id = LT(1); match(ID); sbuilder.Append(id.getText()); value = sbuilder.ToString(); { switch ( LA(1) ) { case WS: { match(WS); break; } case DOT: { match(DOT); sbuilder.Append('.'); match(ALL); sbuilder.Append('*'); break; } default: if ((tokenSet_16_.member(LA(1)))) { if (LA(1) == ALL) { if (allowALL) break; throw new NoViableAltException(LT(1), getFilename()); } } else if ((tokenSet_16_.member(LA(1)))) { } else { throw new NoViableAltException(LT(1), getFilename()); } break; } } } value = sbuilder.ToString(); } catch (RecognitionException ex) { reportError(ex); consume(); consumeUntil(tokenSet_16_); } return value; } protected MethodSignature pointcutsig2( String part1, MethodSignature ms ) //throws RecognitionException, TokenStreamException { MethodSignature ret; String part2; ret = null; try { // for error handling { switch ( LA(1) ) { case ALL: { match(ALL); part2 = "*"; ret=pointcutsig3(part1, part2, ms); break; } case LCURLY: { match(LCURLY); pointcutarguments(ms); match(RCURLY); match(RCURLY); ret = ms; break; } case RCURLY: { match(RCURLY); ret = ms; break; } case ID: { part2=reg_ex(true); ret=pointcutsig3(part1, part2, ms); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } catch (RecognitionException ex) { reportError(ex); consume(); consumeUntil(tokenSet_0_); } return ret; } protected MethodSignature pointcutsig3( String part1, String part2, MethodSignature ms ) //throws RecognitionException, TokenStreamException { MethodSignature ret; String part3; ret = null; try { // for error handling { switch ( LA(1) ) { case ALL: { match(ALL); part3 = "*"; ms = new MethodSignature(part1, part2, methodAll(part3)); pointcutsig4(ms); break; } case LCURLY: { match(LCURLY); ms = new MethodSignature(part1, methodAll(part2)); pointcutarguments(ms); match(RCURLY); match(RCURLY); break; } case RCURLY: { match(RCURLY); ms = new MethodSignature(part1, methodAll(part2)); break; } case ID: { part3=reg_ex(false); ms = new MethodSignature(part1, part2, methodAll(part3)); pointcutsig4(ms); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } ret = ms; } catch (RecognitionException ex) { reportError(ex); consume(); consumeUntil(tokenSet_0_); } return ret; } protected void pointcutarguments( MethodSignature ms ) //throws RecognitionException, TokenStreamException { try { // for error handling { switch ( LA(1) ) { case ID: case ALL: { pointcutargument(ms); { // ( ... )* for (;;) { if ((LA(1)==COMMA)) { match(COMMA); pointcutargument(ms); } else { goto _loop61_breakloop; } } _loop61_breakloop: ; } // ( ... )* break; } case RCURLY: { break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } catch (RecognitionException ex) { reportError(ex); consume(); consumeUntil(tokenSet_9_); } } protected void pointcutsig4( MethodSignature ms ) //throws RecognitionException, TokenStreamException { try { // for error handling { switch ( LA(1) ) { case LCURLY: { match(LCURLY); pointcutarguments(ms); match(RCURLY); match(RCURLY); break; } case RCURLY: { match(RCURLY); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } } catch (RecognitionException ex) { reportError(ex); consume(); consumeUntil(tokenSet_0_); } } protected void pointcutargument( MethodSignature ms ) //throws RecognitionException, TokenStreamException { String argType = String.Empty; try { // for error handling switch ( LA(1) ) { case ALL: { match(ALL); ms.AddArgumentType( "*" ); break; } case ID: { argType=reg_ex(false); ms.AddArgumentType( argType ); break; } default: { throw new NoViableAltException(LT(1), getFilename()); } } } catch (RecognitionException ex) { reportError(ex); consume(); consumeUntil(tokenSet_17_); } } private void initializeFactory() { } public static readonly string[] tokenNames_ = new string[] { @"""<0>""", @"""EOF""", @"""<2>""", @"""NULL_TREE_LOOKAHEAD""", @"""aspect""", @"""for""", @"""in""", @"""end""", @"""import""", @"""mixins""", @"""include""", @"""interceptors""", @"""advice""", @"""pointcut""", @"""method""", @"""property""", @"""propertyread""", @"""propertywrite""", @"""assignableFrom""", @"""customMatcher""", @"""excludes""", @"""includes""", @"""EOS""", @"""LBRACK""", @"""SEMI""", @"""RBRACK""", @"""STRING_LITERAL""", @"""COLON""", @"""ID""", @"""LCURLY""", @"""RCURLY""", @"""OR""", @"""ALL""", @"""COMMA""", @"""DOT""", @"""WS""" }; private static long[] mk_tokenSet_0_() { long[] data = { 2L, 0L}; return data; } public static readonly BitSet tokenSet_0_ = new BitSet(mk_tokenSet_0_()); private static long[] mk_tokenSet_1_() { long[] data = { 2834L, 0L}; return data; } public static readonly BitSet tokenSet_1_ = new BitSet(mk_tokenSet_1_()); private static long[] mk_tokenSet_2_() { long[] data = { 2578L, 0L}; return data; } public static readonly BitSet tokenSet_2_ = new BitSet(mk_tokenSet_2_()); private static long[] mk_tokenSet_3_() { long[] data = { 530L, 0L}; return data; } public static readonly BitSet tokenSet_3_ = new BitSet(mk_tokenSet_3_()); private static long[] mk_tokenSet_4_() { long[] data = { 18L, 0L}; return data; } public static readonly BitSet tokenSet_4_ = new BitSet(mk_tokenSet_4_()); private static long[] mk_tokenSet_5_() { long[] data = { 1125134290L, 0L}; return data; } public static readonly BitSet tokenSet_5_ = new BitSet(mk_tokenSet_5_()); private static long[] mk_tokenSet_6_() { long[] data = { 50331648L, 0L}; return data; } public static readonly BitSet tokenSet_6_ = new BitSet(mk_tokenSet_6_()); private static long[] mk_tokenSet_7_() { long[] data = { 1073751168L, 0L}; return data; } public static readonly BitSet tokenSet_7_ = new BitSet(mk_tokenSet_7_()); private static long[] mk_tokenSet_8_() { long[] data = { 1124082816L, 0L}; return data; } public static readonly BitSet tokenSet_8_ = new BitSet(mk_tokenSet_8_()); private static long[] mk_tokenSet_9_() { long[] data = { 1073741824L, 0L}; return data; } public static readonly BitSet tokenSet_9_ = new BitSet(mk_tokenSet_9_()); private static long[] mk_tokenSet_10_() { long[] data = { 9344L, 0L}; return data; } public static readonly BitSet tokenSet_10_ = new BitSet(mk_tokenSet_10_()); private static long[] mk_tokenSet_11_() { long[] data = { 8320L, 0L}; return data; } public static readonly BitSet tokenSet_11_ = new BitSet(mk_tokenSet_11_()); private static long[] mk_tokenSet_12_() { long[] data = { 536870912L, 0L}; return data; } public static readonly BitSet tokenSet_12_ = new BitSet(mk_tokenSet_12_()); private static long[] mk_tokenSet_13_() { long[] data = { 4224L, 0L}; return data; } public static readonly BitSet tokenSet_13_ = new BitSet(mk_tokenSet_13_()); private static long[] mk_tokenSet_14_() { long[] data = { 128L, 0L}; return data; } public static readonly BitSet tokenSet_14_ = new BitSet(mk_tokenSet_14_()); private static long[] mk_tokenSet_15_() { long[] data = { 2684354560L, 0L}; return data; } public static readonly BitSet tokenSet_15_ = new BitSet(mk_tokenSet_15_()); private static long[] mk_tokenSet_16_() { long[] data = { 14763954304L, 0L}; return data; } public static readonly BitSet tokenSet_16_ = new BitSet(mk_tokenSet_16_()); private static long[] mk_tokenSet_17_() { long[] data = { 9663676416L, 0L}; return data; } public static readonly BitSet tokenSet_17_ = new BitSet(mk_tokenSet_17_()); }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using Orleans.CodeGeneration; using Orleans.GrainDirectory; using Orleans.Runtime.Reactive; using System.Collections.Concurrent; using Orleans.Reactive; using Orleans.Runtime.Configuration; using Orleans.Storage; namespace Orleans.Runtime { /// <summary> /// Maintains additional per-activation state that is required for Orleans internal operations. /// MUST lock this object for any concurrent access /// Consider: compartmentalize by usage, e.g., using separate interfaces for data for catalog, etc. /// </summary> internal class ActivationData : IActivationData, IInvokable { // This class is used for activations that have extension invokers. It keeps a dictionary of // invoker objects to use with the activation, and extend the default invoker // defined for the grain class. // Note that in all cases we never have more than one copy of an actual invoker; // we may have a ExtensionInvoker per activation, in the worst case. private class ExtensionInvoker : IGrainMethodInvoker, IGrainExtensionMap { // Because calls to ExtensionInvoker are allways made within the activation context, // we rely on the single-threading guarantee of the runtime and do not protect the map with a lock. private Dictionary<int, Tuple<IGrainExtension, IGrainExtensionMethodInvoker>> extensionMap; // key is the extension interface ID /// <summary> /// Try to add an extension for the specific interface ID. /// Fail and return false if there is already an extension for that interface ID. /// Note that if an extension invoker handles multiple interface IDs, it can only be associated /// with one of those IDs when added, and so only conflicts on that one ID will be detected and prevented. /// </summary> /// <param name="invoker"></param> /// <param name="handler"></param> /// <returns></returns> internal bool TryAddExtension(IGrainExtensionMethodInvoker invoker, IGrainExtension handler) { if (extensionMap == null) { extensionMap = new Dictionary<int, Tuple<IGrainExtension, IGrainExtensionMethodInvoker>>(1); } if (extensionMap.ContainsKey(invoker.InterfaceId)) return false; extensionMap.Add(invoker.InterfaceId, new Tuple<IGrainExtension, IGrainExtensionMethodInvoker>(handler, invoker)); return true; } /// <summary> /// Removes all extensions for the specified interface id. /// Returns true if the chained invoker no longer has any extensions and may be safely retired. /// </summary> /// <param name="extension"></param> /// <returns>true if the chained invoker is now empty, false otherwise</returns> public bool Remove(IGrainExtension extension) { int interfaceId = 0; foreach(int iface in extensionMap.Keys) if (extensionMap[iface].Item1 == extension) { interfaceId = iface; break; } if (interfaceId == 0) // not found throw new InvalidOperationException(String.Format("Extension {0} is not installed", extension.GetType().FullName)); extensionMap.Remove(interfaceId); return extensionMap.Count == 0; } public bool TryGetExtensionHandler(Type extensionType, out IGrainExtension result) { result = null; if (extensionMap == null) return false; foreach (var ext in extensionMap.Values) if (extensionType == ext.Item1.GetType()) { result = ext.Item1; return true; } return false; } /// <summary> /// Invokes the appropriate grain or extension method for the request interface ID and method ID. /// First each extension invoker is tried; if no extension handles the request, then the base /// invoker is used to handle the request. /// The base invoker will throw an appropriate exception if the request is not recognized. /// </summary> /// <param name="grain"></param> /// <param name="request"></param> /// <returns></returns> public Task<object> Invoke(IAddressable grain, InvokeMethodRequest request) { if (extensionMap == null || !extensionMap.ContainsKey(request.InterfaceId)) throw new InvalidOperationException( String.Format("Extension invoker invoked with an unknown inteface ID:{0}.", request.InterfaceId)); var invoker = extensionMap[request.InterfaceId].Item2; var extension = extensionMap[request.InterfaceId].Item1; return invoker.Invoke(extension, request); } public bool IsExtensionInstalled(int interfaceId) { return extensionMap != null && extensionMap.ContainsKey(interfaceId); } public int InterfaceId { get { return 0; } // 0 indicates an extension invoker that may have multiple intefaces inplemented by extensions. } /// <summary> /// Gets the extension from this instance if it is available. /// </summary> /// <param name="interfaceId">The interface id.</param> /// <param name="extension">The extension.</param> /// <returns> /// <see langword="true"/> if the extension is found, <see langword="false"/> otherwise. /// </returns> public bool TryGetExtension(int interfaceId, out IGrainExtension extension) { Tuple<IGrainExtension, IGrainExtensionMethodInvoker> value; if (extensionMap != null && extensionMap.TryGetValue(interfaceId, out value)) { extension = value.Item1; } else { extension = null; } return extension != null; } } // This is the maximum amount of time we expect a request to continue processing private static TimeSpan maxRequestProcessingTime; private static NodeConfiguration nodeConfiguration; public readonly TimeSpan CollectionAgeLimit; private IGrainMethodInvoker lastInvoker; // This is the maximum number of enqueued request messages for a single activation before we write a warning log or reject new requests. private LimitValue maxEnqueuedRequestsLimit; private HashSet<GrainTimer> timers; private readonly Logger logger; public static void Init(ClusterConfiguration config, NodeConfiguration nodeConfig) { // Consider adding a config parameter for this maxRequestProcessingTime = config.Globals.ResponseTimeout.Multiply(5); nodeConfiguration = nodeConfig; } public ActivationData(ActivationAddress addr, string genericArguments, PlacementStrategy placedUsing, MultiClusterRegistrationStrategy registrationStrategy, IActivationCollector collector, TimeSpan ageLimit) { if (null == addr) throw new ArgumentNullException("addr"); if (null == placedUsing) throw new ArgumentNullException("placedUsing"); if (null == collector) throw new ArgumentNullException("collector"); logger = LogManager.GetLogger("ActivationData", LoggerType.Runtime); ResetKeepAliveRequest(); Address = addr; State = ActivationState.Create; PlacedUsing = placedUsing; RegistrationStrategy = registrationStrategy; if (!Grain.IsSystemTarget && !Constants.IsSystemGrain(Grain)) { this.collector = collector; } CollectionAgeLimit = ageLimit; GrainReference = GrainReference.FromGrainId(addr.Grain, genericArguments, Grain.IsSystemTarget ? addr.Silo : null); } #region Method invocation private ExtensionInvoker extensionInvoker; public IGrainMethodInvoker GetInvoker(int interfaceId, string genericGrainType=null) { // Return previous cached invoker, if applicable if (lastInvoker != null && interfaceId == lastInvoker.InterfaceId) // extension invoker returns InterfaceId==0, so this condition will never be true if an extension is installed return lastInvoker; if (extensionInvoker != null && extensionInvoker.IsExtensionInstalled(interfaceId)) // HasExtensionInstalled(interfaceId) // Shared invoker for all extensions installed on this grain lastInvoker = extensionInvoker; else // Find the specific invoker for this interface / grain type lastInvoker = RuntimeClient.Current.GetInvoker(interfaceId, genericGrainType); return lastInvoker; } internal bool TryAddExtension(IGrainExtensionMethodInvoker invoker, IGrainExtension extension) { if(extensionInvoker == null) extensionInvoker = new ExtensionInvoker(); return extensionInvoker.TryAddExtension(invoker, extension); } internal void RemoveExtension(IGrainExtension extension) { if (extensionInvoker != null) { if (extensionInvoker.Remove(extension)) extensionInvoker = null; } else throw new InvalidOperationException("Grain extensions not installed."); } internal bool TryGetExtensionHandler(Type extensionType, out IGrainExtension result) { result = null; return extensionInvoker != null && extensionInvoker.TryGetExtensionHandler(extensionType, out result); } #endregion public string GrainTypeName { get { if (GrainInstanceType == null) { throw new ArgumentNullException("GrainInstanceType", "GrainInstanceType has not been set."); } return GrainInstanceType.FullName; } } internal Type GrainInstanceType { get; private set; } internal void SetGrainInstance(Grain grainInstance) { GrainInstance = grainInstance; if (grainInstance != null) { GrainInstanceType = grainInstance.GetType(); // Don't ever collect system grains or reminder table grain or memory store grains. bool doNotCollect = typeof(IReminderTableGrain).IsAssignableFrom(GrainInstanceType) || typeof(IMemoryStorageGrain).IsAssignableFrom(GrainInstanceType); if (doNotCollect) { this.collector = null; } } } public IStorageProvider StorageProvider { get; set; } private Streams.StreamDirectory streamDirectory; internal Streams.StreamDirectory GetStreamDirectory() { return streamDirectory ?? (streamDirectory = new Streams.StreamDirectory()); } internal bool IsUsingStreams { get { return streamDirectory != null; } } internal async Task DeactivateStreamResources() { if (streamDirectory == null) return; // No streams - Nothing to do. if (extensionInvoker == null) return; // No installed extensions - Nothing to do. if (StreamResourceTestControl.TestOnlySuppressStreamCleanupOnDeactivate) { logger.Warn(0, "Suppressing cleanup of stream resources during tests for {0}", this); return; } await streamDirectory.Cleanup(true, false); } #region IActivationData GrainReference IActivationData.GrainReference { get { return GrainReference; } } public GrainId Identity { get { return Grain; } } public Grain GrainInstance { get; private set; } public ActivationId ActivationId { get { return Address.Activation; } } public ActivationAddress Address { get; private set; } public IDisposable RegisterTimer(Func<object, Task> asyncCallback, object state, TimeSpan dueTime, TimeSpan period) { var timer = GrainTimer.FromTaskCallback(asyncCallback, state, dueTime, period); AddTimer(timer); timer.Start(); return timer; } #endregion #region Catalog internal readonly GrainReference GrainReference; public SiloAddress Silo { get { return Address.Silo; } } public GrainId Grain { get { return Address.Grain; } } public ActivationState State { get; private set; } public void SetState(ActivationState state) { State = state; } // Don't accept any new messages and stop all timers. public void PrepareForDeactivation() { SetState(ActivationState.Deactivating); StopAllTimers(); } /// <summary> /// If State == Invalid, this may contain a forwarding address for incoming messages /// </summary> public ActivationAddress ForwardingAddress { get; set; } private IActivationCollector collector; internal bool IsExemptFromCollection { get { return collector == null; } } public DateTime CollectionTicket { get; private set; } private bool collectionCancelledFlag; public bool TrySetCollectionCancelledFlag() { lock (this) { if (default(DateTime) == CollectionTicket || collectionCancelledFlag) return false; collectionCancelledFlag = true; return true; } } public void ResetCollectionCancelledFlag() { lock (this) { collectionCancelledFlag = false; } } public void ResetCollectionTicket() { CollectionTicket = default(DateTime); } public void SetCollectionTicket(DateTime ticket) { if (ticket == default(DateTime)) throw new ArgumentException("default(DateTime) is disallowed", "ticket"); if (CollectionTicket != default(DateTime)) { throw new InvalidOperationException("call ResetCollectionTicket before calling SetCollectionTicket."); } CollectionTicket = ticket; } #endregion #region Dispatcher public PlacementStrategy PlacedUsing { get; private set; } public MultiClusterRegistrationStrategy RegistrationStrategy { get; private set; } // Currently, the only supported multi-activation grain is one using the StatelessWorkerPlacement strategy. internal bool IsStatelessWorker { get { return PlacedUsing is StatelessWorkerPlacement; } } // Currently, the only grain type that is not registered in the Grain Directory is StatelessWorker. internal bool IsUsingGrainDirectory { get { return !IsStatelessWorker; } } public Message Running { get; private set; } // the number of requests that are currently executing on this activation. // includes reentrant and non-reentrant requests. private int numRunning; private DateTime currentRequestStartTime; private DateTime becameIdle; public void RecordRunning(Message message) { // Note: This method is always called while holding lock on this activation, so no need for additional locks here numRunning++; if (Running != null) return; // This logic only works for non-reentrant activations // Consider: Handle long request detection for reentrant activations. Running = message; currentRequestStartTime = DateTime.UtcNow; } public void ResetRunning(Message message) { // Note: This method is always called while holding lock on this activation, so no need for additional locks here numRunning--; if (numRunning == 0) { becameIdle = DateTime.UtcNow; if (!IsExemptFromCollection) { collector.TryRescheduleCollection(this); } } // The below logic only works for non-reentrant activations. if (Running != null && !message.Equals(Running)) return; Running = null; currentRequestStartTime = DateTime.MinValue; } private long inFlightCount; private long enqueuedOnDispatcherCount; /// <summary> /// Number of messages that are actively being processed [as opposed to being in the Waiting queue]. /// In most cases this will be 0 or 1, but for Reentrant grains can be >1. /// </summary> public long InFlightCount { get { return Interlocked.Read(ref inFlightCount); } } /// <summary> /// Number of messages that are being received [as opposed to being in the scheduler queue or actively processed]. /// </summary> public long EnqueuedOnDispatcherCount { get { return Interlocked.Read(ref enqueuedOnDispatcherCount); } } /// <summary>Increment the number of in-flight messages currently being processed.</summary> public void IncrementInFlightCount() { Interlocked.Increment(ref inFlightCount); } /// <summary>Decrement the number of in-flight messages currently being processed.</summary> public void DecrementInFlightCount() { Interlocked.Decrement(ref inFlightCount); } /// <summary>Increment the number of messages currently in the prcess of being received.</summary> public void IncrementEnqueuedOnDispatcherCount() { Interlocked.Increment(ref enqueuedOnDispatcherCount); } /// <summary>Decrement the number of messages currently in the prcess of being received.</summary> public void DecrementEnqueuedOnDispatcherCount() { Interlocked.Decrement(ref enqueuedOnDispatcherCount); } /// <summary> /// grouped by sending activation: responses first, then sorted by id /// </summary> private List<Message> waiting; public int WaitingCount { get { return waiting == null ? 0 : waiting.Count; } } /// <summary> /// Insert in a FIFO order /// </summary> /// <param name="message"></param> public bool EnqueueMessage(Message message) { lock (this) { if (State == ActivationState.Invalid) { logger.Warn(ErrorCode.Dispatcher_InvalidActivation, "Cannot enqueue message to invalid activation {0} : {1}", this.ToDetailedString(), message); return false; } // If maxRequestProcessingTime is never set, then we will skip this check if (maxRequestProcessingTime.TotalMilliseconds > 0 && Running != null) { // Consider: Handle long request detection for reentrant activations -- this logic only works for non-reentrant activations var currentRequestActiveTime = DateTime.UtcNow - currentRequestStartTime; if (currentRequestActiveTime > maxRequestProcessingTime) { logger.Warn(ErrorCode.Dispatcher_ExtendedMessageProcessing, "Current request has been active for {0} for activation {1}. Currently executing {2}. Trying to enqueue {3}.", currentRequestActiveTime, this.ToDetailedString(), Running, message); } } waiting = waiting ?? new List<Message>(); waiting.Add(message); return true; } } /// <summary> /// Check whether this activation is overloaded. /// Returns LimitExceededException if overloaded, otherwise <c>null</c>c> /// </summary> /// <param name="log">Logger to use for reporting any overflow condition</param> /// <returns>Returns LimitExceededException if overloaded, otherwise <c>null</c>c></returns> public LimitExceededException CheckOverloaded(Logger log) { LimitValue limitValue = GetMaxEnqueuedRequestLimit(); int maxRequestsHardLimit = limitValue.HardLimitThreshold; int maxRequestsSoftLimit = limitValue.SoftLimitThreshold; if (maxRequestsHardLimit <= 0 && maxRequestsSoftLimit <= 0) return null; // No limits are set int count = GetRequestCount(); if (maxRequestsHardLimit > 0 && count > maxRequestsHardLimit) // Hard limit { log.Warn(ErrorCode.Catalog_Reject_ActivationTooManyRequests, String.Format("Overload - {0} enqueued requests for activation {1}, exceeding hard limit rejection threshold of {2}", count, this, maxRequestsHardLimit)); return new LimitExceededException(limitValue.Name, count, maxRequestsHardLimit, this.ToString()); } if (maxRequestsSoftLimit > 0 && count > maxRequestsSoftLimit) // Soft limit { log.Warn(ErrorCode.Catalog_Warn_ActivationTooManyRequests, String.Format("Hot - {0} enqueued requests for activation {1}, exceeding soft limit warning threshold of {2}", count, this, maxRequestsSoftLimit)); return null; } return null; } internal int GetRequestCount() { lock (this) { long numInDispatcher = EnqueuedOnDispatcherCount; long numActive = InFlightCount; long numWaiting = WaitingCount; return (int)(numInDispatcher + numActive + numWaiting); } } private LimitValue GetMaxEnqueuedRequestLimit() { if (maxEnqueuedRequestsLimit != null) return maxEnqueuedRequestsLimit; if (GrainInstanceType != null) { string limitName = CodeGeneration.GrainInterfaceUtils.IsStatelessWorker(GrainInstanceType.GetTypeInfo()) ? LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS_STATELESS_WORKER : LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS; maxEnqueuedRequestsLimit = nodeConfiguration.LimitManager.GetLimit(limitName); // Cache for next time return maxEnqueuedRequestsLimit; } return nodeConfiguration.LimitManager.GetLimit(LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS); } public Message PeekNextWaitingMessage() { if (waiting != null && waiting.Count > 0) return waiting[0]; return null; } public void DequeueNextWaitingMessage() { if (waiting != null && waiting.Count > 0) waiting.RemoveAt(0); } internal List<Message> DequeueAllWaitingMessages() { lock (this) { if (waiting == null) return null; List<Message> tmp = waiting; waiting = null; return tmp; } } #endregion #region Activation collection public bool IsInactive { get { return !IsCurrentlyExecuting && (waiting == null || waiting.Count == 0); } } public bool IsCurrentlyExecuting { get { return numRunning > 0 ; } } /// <summary> /// Returns how long this activation has been idle. /// </summary> public TimeSpan GetIdleness(DateTime now) { if (now == default(DateTime)) throw new ArgumentException("default(DateTime) is not allowed; Use DateTime.UtcNow instead.", "now"); return now - becameIdle; } /// <summary> /// Returns whether this activation has been idle long enough to be collected. /// </summary> public bool IsStale(DateTime now) { return GetIdleness(now) >= CollectionAgeLimit; } private DateTime keepAliveUntil; public bool ShouldBeKeptAlive { get { return keepAliveUntil >= DateTime.UtcNow; } } public void DelayDeactivation(TimeSpan timespan) { if (timespan <= TimeSpan.Zero) { // reset any current keepAliveUntill ResetKeepAliveRequest(); } else if (timespan == TimeSpan.MaxValue) { // otherwise creates negative time. keepAliveUntil = DateTime.MaxValue; } else { keepAliveUntil = DateTime.UtcNow + timespan; } } public void ResetKeepAliveRequest() { keepAliveUntil = DateTime.MinValue; } public List<Action> OnInactive { get; set; } // ActivationData public void AddOnInactive(Action action) // ActivationData { lock (this) { if (OnInactive == null) { OnInactive = new List<Action>(); } OnInactive.Add(action); } } public void RunOnInactive() { lock (this) { if (OnInactive == null) return; var actions = OnInactive; OnInactive = null; foreach (var action in actions) { action(); } } } #endregion #region In-grain Timers internal void AddTimer(GrainTimer timer) { lock(this) { if (timers == null) { timers = new HashSet<GrainTimer>(); } timers.Add(timer); } } private void StopAllTimers() { lock (this) { if (timers == null) return; foreach (var timer in timers) { timer.Stop(); } } } internal void OnTimerDisposed(GrainTimer orleansTimerInsideGrain) { lock (this) // need to lock since dispose can be called on finalizer thread, outside garin context (not single threaded). { timers.Remove(orleansTimerInsideGrain); } } internal Task WaitForAllTimersToFinish() { lock(this) { if (timers == null) { return TaskDone.Done; } var tasks = new List<Task>(); var timerCopy = timers.ToList(); // need to copy since OnTimerDisposed will change the timers set. foreach (var timer in timerCopy) { // first call dispose, then wait to finish. Utils.SafeExecute(timer.Dispose, logger, "timer.Dispose has thrown"); tasks.Add(timer.GetCurrentlyExecutingTickTask()); } return Task.WhenAll(tasks); } } #endregion #region Reactive Computations private ConcurrentDictionary<string, RcSummaryBase> _RcSummaryMap; public ConcurrentDictionary<string, RcSummaryBase> RcSummaryMap { get { lock (this) { if (_RcSummaryMap == null) { _RcSummaryMap = new ConcurrentDictionary<string, RcSummaryBase>(); //AddOnInactive(() => //{ // foreach (var Kvp in RcSummaryMap) // { // Kvp.Value.Dispose(); // } //}); } } return _RcSummaryMap; } } private RcSummaryWorker _RcSummaryWorker; public RcSummaryWorker RcSummaryWorker { get { lock (this) { if (_RcSummaryWorker == null) { _RcSummaryWorker = new RcSummaryWorker(Identity, ((InsideRuntimeClient)RuntimeClient.Current).InsideRcManager, RuntimeContext.CurrentActivationContext); } } return _RcSummaryWorker; } } #endregion #region Printing functions public string DumpStatus() { var sb = new StringBuilder(); lock (this) { sb.AppendFormat(" {0}", ToDetailedString()); if (Running != null) { sb.AppendFormat(" Processing message: {0}", Running); } if (waiting!=null && waiting.Count > 0) { sb.AppendFormat(" Messages queued within ActivationData: {0}", PrintWaitingQueue()); } } return sb.ToString(); } public override string ToString() { return String.Format("[Activation: {0}{1}{2}{3} State={4}]", Silo, Grain, ActivationId, GetActivationInfoString(), State); } internal string ToDetailedString(bool includeExtraDetails = false) { return String.Format( "[Activation: {0}{1}{2}{3} State={4} NonReentrancyQueueSize={5} EnqueuedOnDispatcher={6} InFlightCount={7} NumRunning={8} IdlenessTimeSpan={9} CollectionAgeLimit={10}{11}]", Silo.ToLongString(), Grain.ToDetailedString(), ActivationId, GetActivationInfoString(), State, // 4 WaitingCount, // 5 NonReentrancyQueueSize EnqueuedOnDispatcherCount, // 6 EnqueuedOnDispatcher InFlightCount, // 7 InFlightCount numRunning, // 8 NumRunning GetIdleness(DateTime.UtcNow), // 9 IdlenessTimeSpan CollectionAgeLimit, // 10 CollectionAgeLimit (includeExtraDetails && Running != null) ? " CurrentlyExecuting=" + Running : ""); // 11: Running } public string Name { get { return String.Format("[Activation: {0}{1}{2}{3}]", Silo, Grain, ActivationId, GetActivationInfoString()); } } /// <summary> /// Return string containing dump of the queue of waiting work items /// </summary> /// <returns></returns> /// <remarks>Note: Caller must be holding lock on this activation while calling this method.</remarks> internal string PrintWaitingQueue() { return Utils.EnumerableToString(waiting); } private string GetActivationInfoString() { var placement = PlacedUsing != null ? PlacedUsing.GetType().Name : String.Empty; return GrainInstanceType == null ? placement : String.Format(" #GrainType={0} Placement={1}", GrainInstanceType.FullName, placement); } #endregion } internal static class StreamResourceTestControl { internal static bool TestOnlySuppressStreamCleanupOnDeactivate; } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using QuantConnect.Securities.Option; using QuantConnect.Util; namespace QuantConnect.Data.Market { /// <summary> /// Represents an entire chain of option contracts for a single underying security. /// This type is <see cref="IEnumerable{OptionContract}"/> /// </summary> public class OptionChain : BaseData, IEnumerable<OptionContract> { private readonly Dictionary<Type, Dictionary<Symbol, List<BaseData>>> _auxiliaryData = new Dictionary<Type, Dictionary<Symbol, List<BaseData>>>(); /// <summary> /// Gets the most recent trade information for the underlying. This may /// be a <see cref="Tick"/> or a <see cref="TradeBar"/> /// </summary> public BaseData Underlying { get; internal set; } /// <summary> /// Gets all ticks for every option contract in this chain, keyed by option symbol /// </summary> public Ticks Ticks { get; private set; } /// <summary> /// Gets all trade bars for every option contract in this chain, keyed by option symbol /// </summary> public TradeBars TradeBars { get; private set; } /// <summary> /// Gets all quote bars for every option contract in this chain, keyed by option symbol /// </summary> public QuoteBars QuoteBars { get; private set; } /// <summary> /// Gets all contracts in the chain, keyed by option symbol /// </summary> public OptionContracts Contracts { get; private set; } /// <summary> /// Gets the set of symbols that passed the <see cref="Option.ContractFilter"/> /// </summary> public HashSet<Symbol> FilteredContracts { get; private set; } /// <summary> /// Initializes a new default instance of the <see cref="OptionChain"/> class /// </summary> private OptionChain() { DataType = MarketDataType.OptionChain; } /// <summary> /// Initializes a new instance of the <see cref="OptionChain"/> class /// </summary> /// <param name="canonicalOptionSymbol">The symbol for this chain.</param> /// <param name="time">The time of this chain</param> public OptionChain(Symbol canonicalOptionSymbol, DateTime time) { Time = time; Symbol = canonicalOptionSymbol; DataType = MarketDataType.OptionChain; Ticks = new Ticks(time); TradeBars = new TradeBars(time); QuoteBars = new QuoteBars(time); Contracts = new OptionContracts(time); FilteredContracts = new HashSet<Symbol>(); Underlying = new QuoteBar(); } /// <summary> /// Initializes a new instance of the <see cref="OptionChain"/> class /// </summary> /// <param name="canonicalOptionSymbol">The symbol for this chain.</param> /// <param name="time">The time of this chain</param> /// <param name="underlying">The most recent underlying trade data</param> /// <param name="trades">All trade data for the entire option chain</param> /// <param name="quotes">All quote data for the entire option chain</param> /// <param name="contracts">All contracts for this option chain</param> /// <param name="filteredContracts">The filtered list of contracts for this option chain</param> public OptionChain(Symbol canonicalOptionSymbol, DateTime time, BaseData underlying, IEnumerable<BaseData> trades, IEnumerable<BaseData> quotes, IEnumerable<OptionContract> contracts, IEnumerable<Symbol> filteredContracts) { Time = time; Underlying = underlying; Symbol = canonicalOptionSymbol; DataType = MarketDataType.OptionChain; FilteredContracts = filteredContracts.ToHashSet(); Ticks = new Ticks(time); TradeBars = new TradeBars(time); QuoteBars = new QuoteBars(time); Contracts = new OptionContracts(time); foreach (var trade in trades) { var tick = trade as Tick; if (tick != null) { List<Tick> ticks; if (!Ticks.TryGetValue(tick.Symbol, out ticks)) { ticks = new List<Tick>(); Ticks[tick.Symbol] = ticks; } ticks.Add(tick); continue; } var bar = trade as TradeBar; if (bar != null) { TradeBars[trade.Symbol] = bar; } } foreach (var quote in quotes) { var tick = quote as Tick; if (tick != null) { List<Tick> ticks; if (!Ticks.TryGetValue(tick.Symbol, out ticks)) { ticks = new List<Tick>(); Ticks[tick.Symbol] = ticks; } ticks.Add(tick); continue; } var bar = quote as QuoteBar; if (bar != null) { QuoteBars[quote.Symbol] = bar; } } foreach (var contract in contracts) { Contracts[contract.Symbol] = contract; } } /// <summary> /// Gets the auxiliary data with the specified type and symbol /// </summary> /// <typeparam name="T">The type of auxiliary data</typeparam> /// <param name="symbol">The symbol of the auxiliary data</param> /// <returns>The last auxiliary data with the specified type and symbol</returns> public T GetAux<T>(Symbol symbol) { List<BaseData> list; Dictionary<Symbol, List<BaseData>> dictionary; if (!_auxiliaryData.TryGetValue(typeof(T), out dictionary) || !dictionary.TryGetValue(symbol, out list)) { return default(T); } return list.OfType<T>().LastOrDefault(); } /// <summary> /// Gets all auxiliary data of the specified type as a dictionary keyed by symbol /// </summary> /// <typeparam name="T">The type of auxiliary data</typeparam> /// <returns>A dictionary containing all auxiliary data of the specified type</returns> public DataDictionary<T> GetAux<T>() { Dictionary<Symbol, List<BaseData>> d; if (!_auxiliaryData.TryGetValue(typeof(T), out d)) { return new DataDictionary<T>(); } var dictionary = new DataDictionary<T>(); foreach (var kvp in d) { var item = kvp.Value.OfType<T>().LastOrDefault(); if (item != null) { dictionary.Add(kvp.Key, item); } } return dictionary; } /// <summary> /// Gets all auxiliary data of the specified type as a dictionary keyed by symbol /// </summary> /// <typeparam name="T">The type of auxiliary data</typeparam> /// <returns>A dictionary containing all auxiliary data of the specified type</returns> public Dictionary<Symbol, List<BaseData>> GetAuxList<T>() { Dictionary<Symbol, List<BaseData>> dictionary; if (!_auxiliaryData.TryGetValue(typeof(T), out dictionary)) { return new Dictionary<Symbol, List<BaseData>>(); } return dictionary; } /// <summary> /// Gets a list of auxiliary data with the specified type and symbol /// </summary> /// <typeparam name="T">The type of auxiliary data</typeparam> /// <param name="symbol">The symbol of the auxiliary data</param> /// <returns>The list of auxiliary data with the specified type and symbol</returns> public List<T> GetAuxList<T>(Symbol symbol) { List<BaseData> list; Dictionary<Symbol, List<BaseData>> dictionary; if (!_auxiliaryData.TryGetValue(typeof(T), out dictionary) || !dictionary.TryGetValue(symbol, out list)) { return new List<T>(); } return list.OfType<T>().ToList(); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// An enumerator that can be used to iterate through the collection. /// </returns> public IEnumerator<OptionContract> GetEnumerator() { return Contracts.Values.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Return a new instance clone of this object, used in fill forward /// </summary> /// <returns>A clone of the current object</returns> public override BaseData Clone() { return new OptionChain { Underlying = Underlying, Ticks = Ticks, Contracts = Contracts, QuoteBars = QuoteBars, TradeBars = TradeBars, FilteredContracts = FilteredContracts, Symbol = Symbol, Time = Time, DataType = DataType, Value = Value }; } /// <summary> /// Adds the specified auxiliary data to this option chain /// </summary> /// <param name="baseData">The auxiliary data to be added</param> internal void AddAuxData(BaseData baseData) { var type = baseData.GetType(); Dictionary<Symbol, List<BaseData>> dictionary; if (!_auxiliaryData.TryGetValue(type, out dictionary)) { dictionary = new Dictionary<Symbol, List<BaseData>>(); _auxiliaryData[type] = dictionary; } List<BaseData> list; if (!dictionary.TryGetValue(baseData.Symbol, out list)) { list = new List<BaseData>(); dictionary[baseData.Symbol] = list; } list.Add(baseData); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; using System.Reflection; using System.Diagnostics; using System; using System.Text; using System.Collections; using System.ComponentModel.Design; using Microsoft.Win32; using System.Security.Permissions; namespace System.ComponentModel { /// <summary> /// <para>Provides properties and methods to add a license /// to a component and to manage a <see cref='System.ComponentModel.LicenseProvider'/>. This class cannot be inherited.</para> /// </summary> public sealed class LicenseManager { private static readonly object s_selfLock = new object(); private static volatile LicenseContext s_context; private static object s_contextLockHolder; private static volatile Hashtable s_providers; private static volatile Hashtable s_providerInstances; private static readonly object s_internalSyncObject = new object(); // not creatable... // private LicenseManager() { } /// <summary> /// <para> /// Gets or sets the current <see cref='System.ComponentModel.LicenseContext'/> which specifies when the licensed object can be /// used. /// </para> /// </summary> public static LicenseContext CurrentContext { get { if (s_context == null) { lock (s_internalSyncObject) { if (s_context == null) { s_context = new System.ComponentModel.Design.RuntimeLicenseContext(); } } } return s_context; } set { lock (s_internalSyncObject) { if (s_contextLockHolder != null) { throw new InvalidOperationException(SR.LicMgrContextCannotBeChanged); } s_context = value; } } } /// <summary> /// <para>Gets the <see cref='System.ComponentModel.LicenseUsageMode'/> that /// specifies when the licensed object can be used, for the <see cref='System.ComponentModel.LicenseManager.CurrentContext'/>.</para> /// </summary> public static LicenseUsageMode UsageMode { get { if (s_context != null) { return s_context.UsageMode; } return LicenseUsageMode.Runtime; } } /// <summary> /// Caches the provider, both in the instance cache, and the type /// cache. /// </summary> private static void CacheProvider(Type type, LicenseProvider provider) { if (s_providers == null) { s_providers = new Hashtable(); } s_providers[type] = provider; if (provider != null) { if (s_providerInstances == null) { s_providerInstances = new Hashtable(); } s_providerInstances[provider.GetType()] = provider; } } /// <summary> /// <para>Creates an instance of the specified type, using /// creationContext /// as the context in which the licensed instance can be used.</para> /// </summary> public static object CreateWithContext(Type type, LicenseContext creationContext) { return CreateWithContext(type, creationContext, Array.Empty<object>()); } /// <summary> /// <para>Creates an instance of the specified type with the /// specified arguments, using creationContext as the context in which the licensed /// instance can be used.</para> /// </summary> public static object CreateWithContext(Type type, LicenseContext creationContext, object[] args) { object created = null; lock (s_internalSyncObject) { LicenseContext normal = CurrentContext; try { CurrentContext = creationContext; LockContext(s_selfLock); try { created = SecurityUtils.SecureCreateInstance(type, args); } catch (TargetInvocationException e) { throw e.InnerException; } } finally { UnlockContext(s_selfLock); CurrentContext = normal; } } return created; } /// <summary> /// Determines if type was actually cached to have _no_ provider, /// as opposed to not being cached. /// </summary> private static bool GetCachedNoLicenseProvider(Type type) { if (s_providers != null) { return s_providers.ContainsKey(type); } return false; } /// <summary> /// Retrieves a cached instance of the provider associated with the /// specified type. /// </summary> private static LicenseProvider GetCachedProvider(Type type) { return (LicenseProvider) s_providers?[type]; } /// <summary> /// Retrieves a cached instance of the provider of the specified /// type. /// </summary> private static LicenseProvider GetCachedProviderInstance(Type providerType) { Debug.Assert(providerType != null, "Type cannot ever be null"); return (LicenseProvider) s_providerInstances?[providerType]; } /// <summary> /// <para>Determines if the given type has a valid license or not.</para> /// </summary> public static bool IsLicensed(Type type) { Debug.Assert(type != null, "IsValid Type cannot ever be null"); License license; bool value = ValidateInternal(type, null, false, out license); if (license != null) { license.Dispose(); license = null; } return value; } /// <summary> /// <para>Determines if a valid license can be granted for the specified type.</para> /// </summary> public static bool IsValid(Type type) { Debug.Assert(type != null, "IsValid Type cannot ever be null"); License license; bool value = ValidateInternal(type, null, false, out license); if (license != null) { license.Dispose(); license = null; } return value; } /// <summary> /// <para>Determines if a valid license can be granted for the /// specified instance of the type. This method creates a valid <see cref='System.ComponentModel.License'/>. </para> /// </summary> public static bool IsValid(Type type, object instance, out License license) { return ValidateInternal(type, instance, false, out license); } /// <summary> /// </summary> public static void LockContext(object contextUser) { lock (s_internalSyncObject) { if (s_contextLockHolder != null) { throw new InvalidOperationException(SR.LicMgrAlreadyLocked); } s_contextLockHolder = contextUser; } } /// <summary> /// </summary> public static void UnlockContext(object contextUser) { lock (s_internalSyncObject) { if (s_contextLockHolder != contextUser) { throw new ArgumentException(SR.LicMgrDifferentUser); } s_contextLockHolder = null; } } /// <summary> /// Internal validation helper. /// </summary> private static bool ValidateInternal(Type type, object instance, bool allowExceptions, out License license) { string licenseKey; return ValidateInternalRecursive(CurrentContext, type, instance, allowExceptions, out license, out licenseKey); } /// <summary> /// Since we want to walk up the entire inheritance change, when not /// give an instance, we need another helper method to walk up /// the chain... /// </summary> private static bool ValidateInternalRecursive(LicenseContext context, Type type, object instance, bool allowExceptions, out License license, out string licenseKey) { LicenseProvider provider = GetCachedProvider(type); if (provider == null && !GetCachedNoLicenseProvider(type)) { // NOTE : Must look directly at the class, we want no inheritance. // LicenseProviderAttribute attr = (LicenseProviderAttribute)Attribute.GetCustomAttribute(type, typeof(LicenseProviderAttribute), false); if (attr != null) { Type providerType = attr.LicenseProvider; provider = GetCachedProviderInstance(providerType) ?? (LicenseProvider)SecurityUtils.SecureCreateInstance(providerType); } CacheProvider(type, provider); } license = null; bool isValid = true; licenseKey = null; if (provider != null) { license = provider.GetLicense(context, type, instance, allowExceptions); if (license == null) { isValid = false; } else { // For the case where a COM client is calling "RequestLicKey", // we try to squirrel away the first found license key // licenseKey = license.LicenseKey; } } // When looking only at a type, we need to recurse up the inheritence // chain, however, we can't give out the license, since this may be // from more than one provider. // if (isValid && instance == null) { Type baseType = type.BaseType; if (baseType != typeof(object) && baseType != null) { if (license != null) { license.Dispose(); license = null; } string temp; isValid = ValidateInternalRecursive(context, baseType, null, allowExceptions, out license, out temp); if (license != null) { license.Dispose(); license = null; } } } return isValid; } /// <summary> /// <para>Determines if a license can be granted for the specified type.</para> /// </summary> public static void Validate(Type type) { License lic; if (!ValidateInternal(type, null, true, out lic)) { throw new LicenseException(type); } if (lic != null) { lic.Dispose(); lic = null; } } /// <summary> /// <para>Determines if a license can be granted for the instance of the specified type.</para> /// </summary> public static License Validate(Type type, object instance) { License lic; if (!ValidateInternal(type, instance, true, out lic)) { throw new LicenseException(type, instance); } return lic; } } }
using System; using NUnit.Framework; using nDumbster.smtp; using System.Web.Mail; namespace tests { /// <summary> /// Summary description for SimpleSmtpServerTests /// </summary> [TestFixture] public class SimpleSmtpServerTests { SimpleSmtpServer server; SimpleSmtpServer server2; public SimpleSmtpServerTests() { server = null; server2 = null; } [SetUp] protected void setUp() { server = new SimpleSmtpServer(); server.Start(); server2 = null; } [TearDown] protected void tearDown() { if (server != null) server.Stop(); if (server2 != null) server2.Stop(); } [Test] public void SendMessage() { System.Web.Mail.SmtpMail.SmtpServer = "localhost"; System.Web.Mail.SmtpMail.Send("[email protected]", "[email protected]", "This is the subject", "This is the body."); Assert.AreEqual(1, server.ReceivedEmail.Length, "server.ReceivedEmail.Length"); Assert.AreEqual(1, server.ReceivedEmailCount, "server.ReceivedEmailSize"); SmtpMessage email = server.ReceivedEmail[0]; Assert.AreEqual("<[email protected]>", email.Headers["To"]); Assert.AreEqual("<[email protected]>", email.Headers["From"]); Assert.AreEqual("text/plain;", email.Headers["Content-Type"]); Assert.AreEqual("This is the subject", email.Headers["Subject"]); Assert.AreEqual("This is the body.", email.Body); } [Test] public void SendMessagesWithCarriageReturn() { String bodyWithCR = "\n\nKeep these pesky carriage returns\n\nPlease,\nPlease\n\n"; System.Web.Mail.SmtpMail.SmtpServer = "localhost"; SmtpMessage.CR = "\n"; System.Web.Mail.SmtpMail.Send("[email protected]", "[email protected]", "CRTest", bodyWithCR); Assert.AreEqual(1, server.ReceivedEmail.Length, "server.ReceivedEmail.Length"); Assert.AreEqual(1, server.ReceivedEmailCount, "server.ReceivedEmailSize"); SmtpMessage email = server.ReceivedEmail[0]; Assert.AreEqual("<[email protected]>", email.Headers["To"]); Assert.AreEqual("<[email protected]>", email.Headers["From"]); Assert.AreEqual("CRTest", email.Headers["Subject"]); Assert.AreEqual("text/plain;", email.Headers["Content-Type"]); Assert.AreEqual(bodyWithCR, email.Body, "Body with CR"); server.ClearReceivedEmail(); String bodyWithCRLF = "\r\n\r\nKeep these pesky carriage returns\r\n\r\nPlease,\r\nPlease\r\n\r\n"; SmtpMessage.CR = "\r\n"; System.Web.Mail.SmtpMail.Send("[email protected]", "[email protected]", "CRTest", bodyWithCRLF); Assert.AreEqual(1, server.ReceivedEmail.Length, "server.ReceivedEmail.Length"); Assert.AreEqual(1, server.ReceivedEmailCount, "server.ReceivedEmailSize"); email = server.ReceivedEmail[0]; Assert.AreEqual("<[email protected]>", email.Headers["To"]); Assert.AreEqual("<[email protected]>", email.Headers["From"]); Assert.AreEqual("CRTest", email.Headers["Subject"]); Assert.AreEqual("text/plain;", email.Headers["Content-Type"]); Assert.AreEqual(bodyWithCRLF, email.Body, "Body with CRLF"); } [Test] public void SendTwoMessages() { System.Web.Mail.SmtpMail.SmtpServer = "localhost"; System.Web.Mail.SmtpMail.Send("[email protected]", "[email protected]", "This is the subject", "This is the body."); System.Web.Mail.SmtpMail.Send("[email protected]", "[email protected]", "This is the second subject", "This is the second body."); Assert.AreEqual(2, server.ReceivedEmail.Length, "server.ReceivedEmail.Length"); Assert.AreEqual(2, server.ReceivedEmailCount, "server.ReceivedEmailSize"); SmtpMessage email1 = server.ReceivedEmail[0]; Assert.AreEqual("<[email protected]>", email1.Headers["To"]); Assert.AreEqual("<[email protected]>", email1.Headers["From"]); Assert.AreEqual("text/plain;", email1.Headers["Content-Type"]); Assert.AreEqual("This is the subject", email1.Headers["Subject"]); Assert.AreEqual("This is the body.", email1.Body); SmtpMessage email2 = server.ReceivedEmail[1]; Assert.AreEqual("<[email protected]>", email2.Headers["To"]); Assert.AreEqual("<[email protected]>", email2.Headers["From"]); Assert.AreEqual("text/plain;", email2.Headers["Content-Type"]); Assert.AreEqual("This is the second subject", email2.Headers["Subject"]); Assert.AreEqual("This is the second body.", email2.Body); } [Test] public void StopStartServer() { System.Web.Mail.SmtpMail.SmtpServer = "localhost"; System.Web.Mail.SmtpMail.Send("[email protected]", "[email protected]", "This is the subject", "This is the body."); Assert.AreEqual(1, server.ReceivedEmail.Length, "server.ReceivedEmail.Length"); Assert.AreEqual(1, server.ReceivedEmailCount, "server.ReceivedEmailSize"); SmtpMessage email1 = server.ReceivedEmail[0]; Assert.AreEqual("<[email protected]>", email1.Headers["To"]); Assert.AreEqual("<[email protected]>", email1.Headers["From"]); Assert.AreEqual("text/plain;", email1.Headers["Content-Type"]); Assert.AreEqual("This is the subject", email1.Headers["Subject"]); Assert.AreEqual("This is the body.", email1.Body); server.Stop(); server.ClearReceivedEmail(); server.Start(); System.Web.Mail.SmtpMail.Send("[email protected]", "[email protected]", "This is the second subject", "This is the second body."); Assert.AreEqual(1, server.ReceivedEmail.Length, "server.ReceivedEmail.Length"); Assert.AreEqual(1, server.ReceivedEmailCount, "server.ReceivedEmailSize"); SmtpMessage email2 = server.ReceivedEmail[0]; Assert.AreEqual("<[email protected]>", email2.Headers["To"]); Assert.AreEqual("<[email protected]>", email2.Headers["From"]); Assert.AreEqual("text/plain;", email2.Headers["Content-Type"]); Assert.AreEqual("This is the second subject", email2.Headers["Subject"]); Assert.AreEqual("This is the second body.", email2.Body); } [Test] [ExpectedException(typeof( System.Net.Sockets.SocketException))] public void ServerBindingError() { // Server is already running. We check that this cause an SocketException to be thrown SimpleSmtpServer server2 = new SimpleSmtpServer(); server2.Start(); Assert.Fail("BindingError"); } #if NET_1_0 // In .Net 1.0 we can't send mail to alternate port because MailMessage.Fields doesn't exists [Test] public void MultipleServerPortSimple() { int ALT_PORT = 2525; // Start second server server2 = SimpleSmtpServer.Start(ALT_PORT); // Send to first server System.Web.Mail.SmtpMail.SmtpServer = "localhost"; System.Web.Mail.SmtpMail.Send("[email protected]", "[email protected]", "This is the subject", "This is the body."); // Check first server Assert.AreEqual(1, server.ReceivedEmail.Length, "server.ReceivedEmail.Length"); Assert.AreEqual(1, server.ReceivedEmailCount, "server.ReceivedEmailSize"); SmtpMessage email = server.ReceivedEmail[0]; Assert.AreEqual("<[email protected]>", email.Headers["To"]); Assert.AreEqual("<[email protected]>", email.Headers["From"]); Assert.AreEqual("text/plain;", email.Headers["Content-Type"]); Assert.AreEqual("This is the subject", email.Headers["Subject"]); Assert.AreEqual("This is the body.", email.Body); // Check second server Assert.AreEqual(0, server2.ReceivedEmail.Length, "server.ReceivedEmail.Length"); Assert.AreEqual(0, server2.ReceivedEmailCount, "server.ReceivedEmailSize"); } #else [Test] public void MultipleServerPort() { int ALT_PORT = 2525; // Start second server server2 = new SimpleSmtpServer(ALT_PORT); server2.Start(); // Send to first server System.Web.Mail.SmtpMail.SmtpServer = "localhost"; System.Web.Mail.SmtpMail.Send("[email protected]", "[email protected]", "This is the subject", "This is the body."); // Send to second server MailMessage mail = new MailMessage(); mail.To = "[email protected]"; mail.From = "[email protected]"; mail.Subject = "This is the second subject"; mail.Body = "This is the second body."; mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", ALT_PORT.ToString()); SmtpMail.Send(mail); // Check first server Assert.AreEqual(1, server.ReceivedEmail.Length, "server.ReceivedEmail.Length"); Assert.AreEqual(1, server.ReceivedEmailCount, "server.ReceivedEmailSize"); SmtpMessage email = server.ReceivedEmail[0]; Assert.AreEqual("<[email protected]>", email.Headers["To"]); Assert.AreEqual("<[email protected]>", email.Headers["From"]); Assert.AreEqual("text/plain;", email.Headers["Content-Type"]); Assert.AreEqual("This is the subject", email.Headers["Subject"]); Assert.AreEqual("This is the body.", email.Body); // Check second server Assert.AreEqual(1, server2.ReceivedEmail.Length, "server.ReceivedEmail.Length"); Assert.AreEqual(1, server2.ReceivedEmailCount, "server.ReceivedEmailSize"); SmtpMessage email1 = server2.ReceivedEmail[0]; Assert.AreEqual("<[email protected]>", email1.Headers["To"]); Assert.AreEqual("<[email protected]>", email1.Headers["From"]); Assert.AreEqual("text/plain;", email1.Headers["Content-Type"]); Assert.AreEqual("This is the second subject", email1.Headers["Subject"]); Assert.AreEqual("This is the second body.", email1.Body); } #endif } }
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; using Signum.Utilities.Reflection; using System.Collections.Concurrent; namespace Signum.Utilities.ExpressionTrees { /// <summary> /// Evaluates & replaces sub-trees when first candidate is reached (top-down) /// </summary> public class ExpressionEvaluator : ExpressionVisitor { readonly HashSet<Expression> candidates; public ExpressionEvaluator(HashSet<Expression> candidates) { this.candidates = candidates; } /// <summary> /// Performs evaluation & replacement of independent sub-trees /// </summary> /// <param name="expression">The root of the expression tree.</param> /// <param name="fnCanBeEvaluated">A function that decides whether a given expression node can be part of the local function.</param> /// <returns>A new tree with sub-trees evaluated and replaced.</returns> public static Expression PartialEval(Expression exp) { if (exp.NodeType == ExpressionType.Constant) return exp; HashSet<Expression> candidates = ExpressionNominator.Nominate(exp); return new ExpressionEvaluator(candidates).Visit(exp)!; } public static object? Eval(Expression expression) { switch (expression.NodeType) { case ExpressionType.Constant: return ((ConstantExpression)expression).Value; case ExpressionType.MemberAccess: { var me = (MemberExpression)expression; if (me.Expression == null) return GetStaticGetter(me.Member)(); else return GetInstanceGetter(me.Member)(Eval(me.Expression)); } case ExpressionType.Convert: { var conv = (UnaryExpression)expression; var operand = Eval(conv.Operand); if(conv.Method != null) return GetExtensionMethodCaller(conv.Method)(operand); if (operand is IConvertible) return ReflectionTools.ChangeType(operand, conv.Type); return operand; } case ExpressionType.Call: { var call = (MethodCallExpression)expression; if (call.Method.IsStatic) { if (call.Arguments.Count == 0) return GetStaticMethodCaller(call.Method)(); if (call.Arguments.Count == 1) return GetExtensionMethodCaller(call.Method)(Eval(call.Arguments[0])); } else { if (call.Arguments.Count == 0) return GetInstanceMethodCaller(call.Method)(Eval(call.Object)); } break; } case ExpressionType.Equal: { var be = (BinaryExpression)expression; return object.Equals(Eval(be.Left), Eval(be.Right)); } case ExpressionType.NotEqual: { var be = (BinaryExpression)expression; return !object.Equals(Eval(be.Left), Eval(be.Right)); } } Delegate fn; using (HeavyProfiler.LogNoStackTrace("Comp")) { fn = Expression.Lambda(expression).Compile(); } try { return fn.DynamicInvoke(null); } catch (TargetInvocationException ex) { ex.InnerException!.PreserveStackTrace(); throw ex.InnerException!; } } public struct MethodKey : IEquatable<MethodKey> { readonly MethodInfo mi; readonly Type[]? arguments; public MethodKey(MethodInfo mi) { this.mi = mi; this.arguments = mi.IsGenericMethod ? mi.GetGenericArguments() : null; } public override bool Equals(object? obj) { return obj is MethodKey mk && Equals(mk); } public bool Equals(MethodKey other) { if (mi.MetadataToken != other.mi.MetadataToken) return false; if (mi.DeclaringType != other.mi.DeclaringType) return false; if (arguments == null) return other.arguments == null; if (other.arguments == null) return false; if (arguments.Length != other.arguments.Length) return false; for (int i = 0; i < arguments.Length; i++) if (arguments[i] != other.arguments[i]) return false; return true; } public override int GetHashCode() { var result = mi.MetadataToken ^ mi.DeclaringType!.GetHashCode(); if (!mi.IsGenericMethod) return result; Type[] types = arguments!; for (int i = 0; i < types.Length; i++) result ^= i ^ types[i].GetHashCode(); return result; } } static readonly ConcurrentDictionary<MethodKey, Func<object?>> cachedStaticMethods = new ConcurrentDictionary<MethodKey, Func<object?>>(); private static Func<object?> GetStaticMethodCaller(MethodInfo mi) { return cachedStaticMethods.GetOrAdd(new MethodKey(mi), (MethodKey _) => { return Expression.Lambda<Func<object?>>(Expression.Convert(Expression.Call(mi), typeof(object))).Compile(); }); } static readonly ConcurrentDictionary<MethodKey, Func<object?, object?>> cachedExtensionMethods = new ConcurrentDictionary<MethodKey, Func<object?, object?>>(); private static Func<object?, object?> GetExtensionMethodCaller(MethodInfo mi) { return cachedExtensionMethods.GetOrAdd(new MethodKey(mi), (MethodKey _) => { ParameterExpression p = Expression.Parameter(typeof(object), "p"); return Expression.Lambda<Func<object?, object?>>(Expression.Convert(Expression.Call(mi, Expression.Convert(p, mi.GetParameters()[0].ParameterType)), typeof(object)), p).Compile(); }); } static readonly ConcurrentDictionary<MethodKey, Func<object?, object?>> cachedInstanceMethods = new ConcurrentDictionary<MethodKey, Func<object?, object?>>(); private static Func<object?, object?> GetInstanceMethodCaller(MethodInfo mi) { return cachedInstanceMethods.GetOrAdd(new MethodKey(mi), (MethodKey _) => { ParameterExpression p = Expression.Parameter(typeof(object), "p"); return Expression.Lambda<Func<object?, object?>>(Expression.Convert(Expression.Call(Expression.Convert(p, mi.DeclaringType), mi), typeof(object)), p).Compile(); }); } static readonly ConcurrentDictionary<(Type type, string name), Func<object?>> cachedStaticGetters = new ConcurrentDictionary<(Type type, string name), Func<object?>>(); private static Func<object?> GetStaticGetter(MemberInfo mi) { return cachedStaticGetters.GetOrAdd((type: mi.DeclaringType!, name: mi.Name), _ => { return Expression.Lambda<Func<object?>>(Expression.Convert(Expression.MakeMemberAccess(null, mi), typeof(object))).Compile(); }); } static readonly ConcurrentDictionary<(Type type, string name), Func<object?, object?>> cachedInstanceGetters = new ConcurrentDictionary<(Type type, string name), Func<object?, object?>>(); private static Func<object?, object?> GetInstanceGetter(MemberInfo mi) { return cachedInstanceGetters.GetOrAdd((type: mi.DeclaringType!, name: mi.Name), _ => { ParameterExpression p = Expression.Parameter(typeof(object), "p"); return Expression.Lambda<Func<object?, object?>>(Expression.Convert(Expression.MakeMemberAccess(Expression.Convert(p, mi.DeclaringType), mi), typeof(object)), p).Compile(); }); } public override Expression? Visit(Expression? exp) { if (exp == null) return null; if (this.candidates.Contains(exp)) { if (exp.NodeType == ExpressionType.Constant) { return exp; } var constant = Expression.Constant(Eval(exp), exp.Type); if (typeof(LambdaExpression).IsAssignableFrom(constant.Type)) return PartialEval((Expression)constant.Value); return constant; } return base.Visit(exp); } } }
// QyotoProjectServiceExtension.cs // // Copyright (c) 2008 Eric Butler <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.IO; using System.CodeDom; using System.CodeDom.Compiler; using System.Reflection; using System.Xml; namespace QyotoDevelop { public class QyotoCodeGenerator { public static void GenerateFormCodeFile(QyotoForm form) { new QyotoCodeGenerator(form); } CodeMemberMethod m_SetupUiMethod; List<CodeExpression> m_SetBuddyExpressions = new List<CodeExpression>(); QyotoCodeGenerator (QyotoForm form) { CodeCompileUnit unit = new CodeCompileUnit(); CodeNamespace nspace = new CodeNamespace(form.Namespace); nspace.Imports.Add(new CodeNamespaceImport("System")); nspace.Imports.Add(new CodeNamespaceImport("Qyoto")); unit.Namespaces.Add(nspace); CodeTypeDeclaration type = new CodeTypeDeclaration(form.ClassName); type.IsClass = true; type.IsPartial = true; type.TypeAttributes = TypeAttributes.Public; type.BaseTypes.Add(new CodeTypeReference(form.BaseTypeName)); nspace.Types.Add(type); m_SetupUiMethod = new CodeMemberMethod(); m_SetupUiMethod.Name = "SetupUi"; m_SetupUiMethod.Attributes = MemberAttributes.Family | MemberAttributes.Final; type.Members.Add(m_SetupUiMethod); m_SetupUiMethod.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeBaseReferenceExpression(), "ObjectName"), new CodePrimitiveExpression(form.ClassName))); XmlDocument doc = new XmlDocument(); doc.Load(form.UiFile); XmlElement widgetNode = (XmlElement)doc.SelectSingleNode("/ui/widget"); ParseWidget(widgetNode, type, null, null); foreach (XmlElement node in doc.SelectNodes("/ui/connections/connection")) { string sender = node.SelectSingleNode("sender").InnerText; string signal = node.SelectSingleNode("signal").InnerText; string receiver = node.SelectSingleNode("receiver").InnerText; string slot = node.SelectSingleNode("slot").InnerText; CodeExpression senderExpression = null; if (sender == type.Name) senderExpression = new CodeThisReferenceExpression(); else senderExpression = new CodeVariableReferenceExpression(sender); CodeExpression receiverExpression = null; if (receiver == type.Name) receiverExpression = new CodeThisReferenceExpression(); else receiverExpression = new CodeVariableReferenceExpression(receiver); m_SetupUiMethod.Statements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("QObject"), "Connect", senderExpression, new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("Qt"), "SIGNAL", new CodePrimitiveExpression(signal)), receiverExpression, new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("Qt"), "SLOT", new CodePrimitiveExpression(slot)))); } m_SetupUiMethod.Statements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("QMetaObject"), "ConnectSlotsByName", new CodeThisReferenceExpression())); foreach (var expr in m_SetBuddyExpressions) { m_SetupUiMethod.Statements.Add(expr); } using (TextWriter writer = new StreamWriter(form.GeneratedSourceCodeFile)) { CodeDomProvider provider = form.Project.LanguageBinding.GetCodeDomProvider(); provider.GenerateCodeFromCompileUnit(unit, writer, new CodeGeneratorOptions()); } } void ParseWidget(XmlElement widgetNode, CodeTypeDeclaration formClass, CodeExpression parentWidgetReference, CodeExpression parentLayoutReference) { ParseWidget(widgetNode, formClass, parentWidgetReference, parentLayoutReference, null); } void ParseWidget(XmlElement widgetNode, CodeTypeDeclaration formClass, CodeExpression parentWidgetReference, CodeExpression parentLayoutReference, XmlElement parentItemNode) { string widgetClass = widgetNode.GetAttribute("class"); string widgetName = widgetNode.GetAttribute("name"); CodeExpression widgetReference; if (parentWidgetReference == null) { widgetReference = new CodeThisReferenceExpression(); } else { if (widgetClass == "Line") widgetClass = "QFrame"; CodeMemberField widgetField = new CodeMemberField(widgetClass, widgetName); widgetField.Attributes = MemberAttributes.Family; formClass.Members.Add(widgetField); widgetReference = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), widgetName); m_SetupUiMethod.Statements.Add(new CodeAssignStatement(widgetReference, new CodeObjectCreateExpression(widgetClass, parentWidgetReference))); m_SetupUiMethod.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(widgetReference, "ObjectName"), new CodePrimitiveExpression(widgetName))); } ParseProperties(widgetNode, widgetReference, widgetReference); XmlElement layoutNode = (XmlElement)widgetNode.SelectSingleNode("layout"); if (layoutNode != null) { ParseLayout(layoutNode, formClass, widgetReference, null); } if (parentWidgetReference != null) { if (parentItemNode == null || parentItemNode.Attributes["row"] == null || parentItemNode.Attributes["column"] == null) { if (parentLayoutReference != null) { m_SetupUiMethod.Statements.Add(new CodeMethodInvokeExpression(parentLayoutReference, "AddWidget", widgetReference)); } else { var parentWidgetNode = (XmlElement)widgetNode.ParentNode; if (GetClassName(parentWidgetNode) == "QTabWidget") { string tabLabel = widgetNode.SelectSingleNode("attribute[@name='title']/string").InnerText; m_SetupUiMethod.Statements.Add(new CodeMethodInvokeExpression(parentWidgetReference, "AddTab", widgetReference, new CodePrimitiveExpression(tabLabel))); } else if (GetClassName(parentWidgetNode) == "QScrollArea") { m_SetupUiMethod.Statements.Add(new CodeMethodInvokeExpression(parentWidgetReference, "SetWidget", widgetReference)); } else { m_SetupUiMethod.Statements.Add(new CodeMethodInvokeExpression(parentWidgetReference, "AddWidget", widgetReference)); } } } else { int row = Convert.ToInt32(parentItemNode.GetAttribute("row")); int column = Convert.ToInt32(parentItemNode.GetAttribute("column")); var parentLayoutNode = (XmlElement)parentItemNode.ParentNode; if (GetClassName(parentLayoutNode) == "QFormLayout") { var roleName = (column == 0) ? "LabelRole" : "FieldRole"; var roleExpression = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("QFormLayout.ItemRole"), roleName); m_SetupUiMethod.Statements.Add(new CodeMethodInvokeExpression(parentLayoutReference, "SetWidget", new CodePrimitiveExpression(row), roleExpression, widgetReference)); } else { var colSpan = parentItemNode.Attributes["colspan"] != null ? Convert.ToInt32(parentItemNode.GetAttribute("colspan")) : 1; var rowSpan = parentItemNode.Attributes["rowspan"] != null ? Convert.ToInt32(parentItemNode.GetAttribute("rowspan")) : 1; m_SetupUiMethod.Statements.Add(new CodeMethodInvokeExpression(parentLayoutReference, "AddWidget", widgetReference, new CodePrimitiveExpression(row), new CodePrimitiveExpression(column), new CodePrimitiveExpression(rowSpan), new CodePrimitiveExpression(colSpan))); } } } if (widgetClass == "QComboBox") { List<CodeExpression> itemTextExpressions = new List<CodeExpression>(); foreach (XmlElement itemElement in widgetNode.GetElementsByTagName("item")) { string text = itemElement.SelectSingleNode("property[@name='text']").InnerText; itemTextExpressions.Add(new CodePrimitiveExpression(text)); } if (itemTextExpressions.Count > 0) { m_SetupUiMethod.Statements.Add(new CodeMethodInvokeExpression(widgetReference, "InsertItems", new CodePrimitiveExpression(0), new CodeObjectCreateExpression(typeof (List<string>), new CodeArrayCreateExpression(typeof(string[]), itemTextExpressions.ToArray())))); } } foreach (XmlElement childWidgetNode in widgetNode.SelectNodes("widget")) { ParseWidget(childWidgetNode, formClass, widgetReference, null); } } void ParseLayout(XmlElement layoutNode, CodeTypeDeclaration formClass, CodeExpression widgetReference, CodeExpression parentLayout) { string layoutName = layoutNode.GetAttribute("name"); string layoutClass = layoutNode.GetAttribute("class"); CodeVariableReferenceExpression layoutReference = new CodeVariableReferenceExpression(layoutName); m_SetupUiMethod.Statements.Add(new CodeVariableDeclarationStatement(layoutClass, layoutName)); if (parentLayout != null) { m_SetupUiMethod.Statements.Add(new CodeAssignStatement(layoutReference, new CodeObjectCreateExpression(layoutClass))); var parentItemNode = (XmlElement)layoutNode.ParentNode; var parentLayoutNode = (XmlElement)parentItemNode.ParentNode; if (parentLayoutNode.GetAttribute("class") == "QGridLayout") { int row = Convert.ToInt32(parentItemNode.GetAttribute("row")); int column = Convert.ToInt32(parentItemNode.GetAttribute("column")); var colSpan = parentItemNode.Attributes["colspan"] != null ? Convert.ToInt32(parentItemNode.GetAttribute("colspan")) : 1; var rowSpan = parentItemNode.Attributes["rowspan"] != null ? Convert.ToInt32(parentItemNode.GetAttribute("rowspan")) : 1; m_SetupUiMethod.Statements.Add(new CodeMethodInvokeExpression(parentLayout, "AddLayout", layoutReference, new CodePrimitiveExpression(row), new CodePrimitiveExpression(column), new CodePrimitiveExpression(rowSpan), new CodePrimitiveExpression(colSpan))); } else { m_SetupUiMethod.Statements.Add(new CodeMethodInvokeExpression(parentLayout, "AddLayout", layoutReference)); } } else { m_SetupUiMethod.Statements.Add(new CodeAssignStatement(layoutReference, new CodeObjectCreateExpression(layoutClass, widgetReference))); } ParseProperties(layoutNode, layoutReference, layoutReference); foreach (XmlElement itemNode in layoutNode.SelectNodes("item")) { XmlElement itemChildNode = (XmlElement)itemNode.FirstChild; if (itemChildNode.Name == "widget") ParseWidget(itemChildNode, formClass, widgetReference, layoutReference, itemNode); else if (itemChildNode.Name == "layout") ParseLayout(itemChildNode, formClass, widgetReference, layoutReference); else if (itemChildNode.Name == "spacer") { string spacerName = itemChildNode.GetAttribute("name"); int width = Convert.ToInt32(itemChildNode.SelectSingleNode("property[@name='sizeHint']/size/width").InnerText); int height = Convert.ToInt32(itemChildNode.SelectSingleNode("property[@name='sizeHint']/size/height").InnerText); string orientation = itemChildNode.SelectSingleNode("property[@name='orientation']/enum").InnerText; string hpolicy, vpolicy = null; if (orientation == "Qt::Vertical") { hpolicy = "Minimum"; vpolicy = "Expanding"; } else if (orientation == "Qt::Horizontal") { hpolicy = "Expanding"; vpolicy = "Minimum"; } else { throw new Exception("Unknown orientation: " + orientation); } CodeVariableReferenceExpression spacerReference = new CodeVariableReferenceExpression(spacerName); m_SetupUiMethod.Statements.Add(new CodeVariableDeclarationStatement("QSpacerItem", spacerName)); m_SetupUiMethod.Statements.Add(new CodeAssignStatement(spacerReference, new CodeObjectCreateExpression("QSpacerItem", new CodePrimitiveExpression(width), new CodePrimitiveExpression(height), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("QSizePolicy.Policy"), hpolicy), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("QSizePolicy.Policy"), vpolicy)))); if (layoutNode.GetAttribute("class") == "QGridLayout") { int row = Convert.ToInt32(itemNode.GetAttribute("row")); int column = Convert.ToInt32(itemNode.GetAttribute("column")); var colSpan = itemNode.Attributes["colspan"] != null ? Convert.ToInt32(itemNode.GetAttribute("colspan")) : 1; var rowSpan = itemNode.Attributes["rowspan"] != null ? Convert.ToInt32(itemNode.GetAttribute("rowspan")) : 1; m_SetupUiMethod.Statements.Add(new CodeMethodInvokeExpression(layoutReference, "AddItem", spacerReference, new CodePrimitiveExpression(row), new CodePrimitiveExpression(column), new CodePrimitiveExpression(rowSpan), new CodePrimitiveExpression(colSpan))); } else { m_SetupUiMethod.Statements.Add(new CodeMethodInvokeExpression(layoutReference, "AddItem", spacerReference)); } } else throw new Exception(String.Format("Failed to generate {0}. Expected <widget> or <layout>. Got: {1}", formClass.Name, itemChildNode.Name)); } } void ParseProperties(XmlElement parentNode, CodeExpression parentObjectReference, CodeExpression itemReference) { int leftMargin = 0, rightMargin = 0, topMargin = 0, bottomMargin = 0; foreach (XmlElement propertyNode in parentNode.SelectNodes("property")) { string name = TranslatePropertyName(propertyNode.GetAttribute("name"), false); XmlElement propertyValueNode = (XmlElement)propertyNode.FirstChild; if (propertyValueNode.Name == "sizepolicy") { string hpolicy = propertyValueNode.GetAttribute("hsizetype"); string vpolicy = propertyValueNode.GetAttribute("vsizetype"); int hstretch = Convert.ToInt32(propertyValueNode.SelectSingleNode("horstretch").InnerText); int vstretch = Convert.ToInt32(propertyValueNode.SelectSingleNode("verstretch").InnerText); CodeExpression hpolicyExpr = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("QSizePolicy.Policy"), hpolicy); CodeExpression vpolicyExpr = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("QSizePolicy.Policy"), vpolicy); //CodeExpression sizePolicyReference = new CodePropertyReferenceExpression(itemReference, "SizePolicy"); //m_SetupUiMethod.Statements.Add(new CodeAssignStatement(sizePolicyReference, new CodeObjectCreateExpression("QSizePolicy", hpolicyExpr, vpolicyExpr))); string objectName = parentNode.GetAttribute("name"); m_SetupUiMethod.Statements.Add(new CodeVariableDeclarationStatement("QSizePolicy", objectName + "_sizePolicy")); CodeExpression sizePolicyReference = new CodeVariableReferenceExpression(objectName + "_sizePolicy"); m_SetupUiMethod.Statements.Add(new CodeAssignStatement(sizePolicyReference, new CodeObjectCreateExpression("QSizePolicy", hpolicyExpr, vpolicyExpr))); m_SetupUiMethod.Statements.Add(new CodeMethodInvokeExpression(sizePolicyReference, "SetVerticalStretch", new CodePrimitiveExpression(vstretch))); m_SetupUiMethod.Statements.Add(new CodeMethodInvokeExpression(sizePolicyReference, "SetHorizontalStretch", new CodePrimitiveExpression(hstretch))); m_SetupUiMethod.Statements.Add(new CodeMethodInvokeExpression(sizePolicyReference,"SetHeightForWidth", new CodeMethodInvokeExpression(new CodePropertyReferenceExpression(parentObjectReference, "SizePolicy"), "HasHeightForWidth"))); m_SetupUiMethod.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(parentObjectReference, "SizePolicy"), sizePolicyReference)); } else if (name == "LeftMargin") { leftMargin = Convert.ToInt32(propertyValueNode.InnerText); } else if (name == "RightMargin") { rightMargin = Convert.ToInt32(propertyValueNode.InnerText); } else if (name == "TopMargin") { topMargin = Convert.ToInt32(propertyValueNode.InnerText); } else if (name == "BottomMargin") { bottomMargin = Convert.ToInt32(propertyValueNode.InnerText); } else if (name == "Orientation" && parentNode.GetAttribute("class") == "Line") { CodeExpression valueExpr = null; if (propertyNode.InnerText == "Qt::Vertical") valueExpr = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("QFrame.Shape"), "VLine"); else valueExpr = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("QFrame.Shape"), "HLine"); m_SetupUiMethod.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(itemReference, "FrameShape"), valueExpr)); m_SetupUiMethod.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(itemReference, "FrameShadow"), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("QFrame.Shadow"), "Sunken"))); } else if (name == "Buddy") { m_SetBuddyExpressions.Add(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(itemReference, "SetBuddy"), TranslatePropertyValue(propertyNode))); } else { m_SetupUiMethod.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(itemReference, name), TranslatePropertyValue(propertyNode))); } } if (leftMargin != 0 || topMargin != 0 || bottomMargin != 0 || rightMargin != 0) { m_SetupUiMethod.Statements.Add(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(itemReference, "SetContentsMargins"), new CodePrimitiveExpression(leftMargin), new CodePrimitiveExpression(topMargin), new CodePrimitiveExpression(rightMargin), new CodePrimitiveExpression(bottomMargin))); } } string TranslatePropertyName (string cname, bool alwaysUppercaseFirstLetter) { List<string> lowerCasePropertyNames = new List<string>(); lowerCasePropertyNames.AddRange(new string[] { "acceptMode", "buttonSymbols", "cacheMode", "completionMode", "correctionMode", "curveShape", "direction", "dragDropMode", "dragMode", "echoMode", "fieldGrowthPolicy", "fileMode", "flow", "horizontalHeaderFormat", "icon", "insertPolicy", "itemIndexMethod", "layoutMode", "lineWrapMode", "menuRole", "mode", "modelSorting", "movement", "notation", "resizeMode", "segmentStyle", "selectionBehavior", "selectionMode", "shape", "sizeAdjustPolicy", "sizeConstraint", "submitPolicy", "tabPosition", "tabShape", "tickPosition", "verticalHeaderFormat", "viewMode", "viewportUpdateMode", "wizardStyle" }); if (!alwaysUppercaseFirstLetter && lowerCasePropertyNames.Contains(cname)) return cname; else return cname.Substring(0,1).ToUpper() + cname.Substring(1); } CodeExpression TranslatePropertyValue (XmlElement propertyNode) { XmlElement propertyValueNode = (XmlElement)propertyNode.FirstChild; switch (propertyValueNode.Name) { case "string": return new CodePrimitiveExpression(propertyValueNode.InnerText); case "bool": return new CodePrimitiveExpression(propertyValueNode.InnerText == "true"); case "number": return new CodePrimitiveExpression(Convert.ToInt32(propertyValueNode.InnerText)); case "url": return new CodeObjectCreateExpression("QUrl", new CodePrimitiveExpression(propertyValueNode.InnerText)); case "rect": int rectX = Convert.ToInt32(propertyValueNode.SelectSingleNode("x").InnerText); int rectY = Convert.ToInt32(propertyValueNode.SelectSingleNode("y").InnerText); int rectWidth = Convert.ToInt32(propertyValueNode.SelectSingleNode("width").InnerText); int rectHeight = Convert.ToInt32(propertyValueNode.SelectSingleNode("height").InnerText); return new CodeObjectCreateExpression("QRect", new CodePrimitiveExpression(rectX), new CodePrimitiveExpression(rectY), new CodePrimitiveExpression(rectWidth), new CodePrimitiveExpression(rectHeight)); case "size": int sizeWidth = Convert.ToInt32(propertyValueNode.SelectSingleNode("width").InnerText); int sizeHeight = Convert.ToInt32(propertyValueNode.SelectSingleNode("height").InnerText); return new CodeObjectCreateExpression("QSize", new CodePrimitiveExpression(sizeWidth), new CodePrimitiveExpression(sizeHeight)); case "iconset": return new CodeObjectCreateExpression("QIcon", new CodePrimitiveExpression(propertyValueNode.InnerText)); case "enum": string val = propertyValueNode.InnerText; if (val.Contains("::")) { string className = val.Substring(0, val.IndexOf("::")); string enumName = TranslatePropertyName(propertyNode.GetAttribute("name"), true); if (enumName == "FrameShadow") enumName = "Shadow"; else if (enumName == "FrameShape") enumName = "Shape"; else if (enumName == "HorizontalScrollBarPolicy") enumName = "ScrollBarPolicy"; else if (enumName == "VerticalScrollBarPolicy") enumName = "ScrollBarPolicy"; string enumValue = val.Substring(val.IndexOf("::") + 2); return new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(String.Format("{0}.{1}", className, enumName)), enumValue); } else { throw new NotSupportedException(); } case "set": CodeExpression result = null; foreach (string cenum in propertyValueNode.InnerText.Split('|')) { string enumName = cenum.Substring(0, cenum.IndexOf("::")); string enumValue = cenum.Substring(cenum.IndexOf("::") + 2); CodeExpression thisExpr = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("global::Qyoto.Qyoto"), "GetCPPEnumValue", new CodePrimitiveExpression(enumName), new CodePrimitiveExpression(enumValue)); if (result == null) result = thisExpr; else result = new CodeBinaryOperatorExpression(result, CodeBinaryOperatorType.BitwiseOr, thisExpr); } return result; case "cstring": return new CodeVariableReferenceExpression(propertyValueNode.InnerText); } throw new Exception("Unsupported property type: " + propertyValueNode.Name); } string GetClassName (XmlElement node) { var className = node.GetAttribute("class"); var custom = node.OwnerDocument.SelectSingleNode(String.Format("/ui/customwidgets/customwidget[class='{0}']", className)); if (custom != null) className = custom["extends"].InnerText; return className; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="MvcTestBase.cs" company="Sven Erik Matzen"> // (c) 2013 Sven Erik Matzen // </copyright> // <summary> // Defines the MvcTestBase type. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Sem.Authentication.MvcHelper.Test { using System; using System.Collections.Specialized; using System.Security.Principal; using System.Web; using System.Web.Mvc; using System.Web.Routing; using Moq; /// <summary> /// The test base class for MVC tests. This class does provide some basic helpers for /// testing MVC controllers / filters etc. /// </summary> public class MvcTestBase { /// <summary> /// Creates a new request context that returns a distinct, but always the same, session id. /// </summary> /// <returns> The <see cref="Mock"/> object for the request context. </returns> public static ActionExecutingContext CreateRequestContext() { return CreateRequestContext(new Uri("http://localhost/test", UriKind.Absolute), Guid.NewGuid().ToString("N"), Guid.NewGuid().ToString("N")); } /// <summary> /// Creates a new request context that returns a distinct, but always the same, session id. /// </summary> /// <param name="requestUrl">The URL that should be simulated to be requested.</param> /// <returns> The <see cref="Mock"/> object for the request context. </returns> public static ActionExecutingContext CreateRequestContext(Uri requestUrl) { return CreateRequestContext(requestUrl, Guid.NewGuid().ToString("N"), Guid.NewGuid().ToString("N")); } /// <summary> /// Creates a new request context that returns a distinct, but always the same, session id. /// </summary> /// <param name="requestUrl">The URL the request should fake.</param> /// <param name="sessionId"> The session Id for the request. </param> /// <param name="clientIP"> The client IP for the request. </param> /// <returns> The <see cref="Mock"/> object for the request context. </returns> public static ActionExecutingContext CreateRequestContext(Uri requestUrl, string sessionId, string clientIP) { return CreateRequestContext(requestUrl, sessionId, clientIP, new NameValueCollection()); } /// <summary> /// Creates a new request context that returns a distinct, but always the same, session id. /// </summary> /// <param name="requestUrl">The URL the request should fake.</param> /// <param name="sessionId"> The session Id for the request. </param> /// <param name="clientIP"> The client IP for the request. </param> /// <param name="formCollection">The collection of form data items.</param> /// <returns> The <see cref="Mock"/> object for the request context. </returns> public static ActionExecutingContext CreateRequestContext(Uri requestUrl, string sessionId, string clientIP, NameValueCollection formCollection) { return CreateRequestContext(requestUrl, sessionId, clientIP, formCollection, "UserName"); } /// <summary> /// Creates a new request context that returns a distinct, but always the same, session id. /// </summary> /// <param name="requestUrl">The URL the request should fake.</param> /// <param name="sessionId"> The session Id for the request. </param> /// <param name="clientIP"> The client IP for the request. </param> /// <param name="formCollection">The collection of form data items.</param> /// <param name="userName">The name of the user the identity should contain.</param> /// <returns> The <see cref="Mock"/> object for the request context. </returns> public static ActionExecutingContext CreateRequestContext(Uri requestUrl, string sessionId, string clientIP, NameValueCollection formCollection, string userName) { object values = new { controller = "Home", action = "Index", id = UrlParameter.Optional }; var requestContext = RequestContext(requestUrl, sessionId, clientIP, formCollection, values, userName); var routes = RouteCollection(values); var controller = Controller(requestContext, routes); return new ActionExecutingContext { RequestContext = requestContext, Controller = controller, }; } /// <summary> /// Creates an initialized <see cref="HtmlHelper"/> object. /// </summary> /// <returns> /// The <see cref="HtmlHelper"/>. /// </returns> public static HtmlHelper CreateHtmlHelper() { var container = new Mock<IViewDataContainer>(); return new HtmlHelper(ViewContext(new Uri("http://test/"), Guid.NewGuid().ToString("N"), Guid.NewGuid().ToString("N"), new NameValueCollection()), container.Object); } /// <summary> /// Generates a request context. /// </summary> /// <param name="requestUrl"> The request url. </param> /// <param name="sessionId"> The session id. </param> /// <param name="clientIP"> The client IP. </param> /// <param name="formCollection"> The http FORM collection. </param> /// <param name="values"> The values for the route data. </param> /// <param name="username"> The username. </param> /// <returns> The <see cref="RequestContext(System.Uri,string,string,System.Collections.Specialized.NameValueCollection,object,string)"/>. </returns> private static RequestContext RequestContext(Uri requestUrl, string sessionId, string clientIP, NameValueCollection formCollection, object values, string username) { var requestBase = RequestBase(requestUrl, clientIP, formCollection); var httpContext = HttpContext(sessionId, requestBase, username); return RequestContext(httpContext, values); } /// <summary> /// Creates an initialized controller. /// </summary> /// <param name="requestContext"> The request context for the controller. </param> /// <param name="routes"> The routes for the <see cref="UrlHelper"/>. </param> /// <returns> The <see cref="Mock"/>. </returns> private static Controller Controller(RequestContext requestContext, RouteCollection routes) { var urlHelper = new UrlHelper(requestContext, routes); var controller = new Mock<Controller>(); controller.Object.Url = urlHelper; RouteTable.Routes.Clear(); foreach (var route in routes) { RouteTable.Routes.Add(route); } return controller.Object; } /// <summary> /// Generates a default route collection. /// </summary> /// <param name="values"> The default values. </param> /// <returns> The <see cref="RouteCollection"/>. </returns> private static RouteCollection RouteCollection(object values) { return new RouteCollection { new Route("{controller}/{action}/{id}", new MvcRouteHandler()) { Defaults = new RouteValueDictionary(values), Constraints = new RouteValueDictionary((object)null), DataTokens = new RouteValueDictionary(), } }; } /// <summary> /// Generates an initialized <see cref="HttpContextBase"/>. /// </summary> /// <param name="sessionId"> The session id. </param> /// <param name="requestBase"> The request base. </param> /// <param name="username"> The username for the identity of the current user. </param> /// <returns> The <see cref="HttpContextBase"/>. </returns> private static HttpContextBase HttpContext(string sessionId, HttpRequestBase requestBase, string username) { var httpContext = new Moq.Mock<HttpContextBase>(); httpContext.Setup(x => x.Session).Returns(SessionState(sessionId)); httpContext.Setup(x => x.Request).Returns(requestBase); httpContext.Setup(x => x.Response).Returns(Response()); httpContext.Setup(x => x.User).Returns(User(username)); return httpContext.Object; } /// <summary> /// Creates an initialized <see cref="IPrincipal"/> for a given user name. /// </summary> /// <param name="username"> The username. </param> /// <returns> The <see cref="IPrincipal"/>. </returns> private static IPrincipal User(string username) { var user = new Mock<IPrincipal>(); var identity = new Mock<IIdentity>(); identity.Setup(x => x.Name).Returns(username); user.Setup(x => x.Identity).Returns(identity.Object); return user.Object; } /// <summary> /// Generates a ready to use <see cref="HttpResponseBase"/> object. /// </summary> /// <returns> The <see cref="Mock"/>. </returns> private static HttpResponseBase Response() { var response = new Mock<HttpResponseBase>(); response.Setup(r => r.ApplyAppPathModifier(It.IsAny<string>())).Returns((string s) => s); return response.Object; } /// <summary> /// Generates an initialized <see cref="HttpSessionStateBase"/>. /// </summary> /// <param name="sessionId"> The session id. </param> /// <returns> The <see cref="HttpSessionStateBase"/>. </returns> private static HttpSessionStateBase SessionState(string sessionId) { var sessionState = new Mock<HttpSessionStateBase>(); sessionState.Setup(x => x.SessionID).Returns(sessionId); return sessionState.Object; } /// <summary> /// Generates an initialized <see cref="HttpRequestBase"/>. /// </summary> /// <param name="requestUrl"> The request url. </param> /// <param name="clientIP"> The client IP this request should simulate. </param> /// <param name="formCollection"> The form value collection. </param> /// <returns> The <see cref="HttpRequestBase"/>. </returns> private static HttpRequestBase RequestBase(Uri requestUrl, string clientIP, NameValueCollection formCollection) { var path = requestUrl == null ? string.Empty : requestUrl.AbsolutePath; var requestBase = new Mock<HttpRequestBase>(); requestBase.Setup(x => x.ApplicationPath).Returns(path); requestBase.Setup(x => x.AppRelativeCurrentExecutionFilePath).Returns("~" + path); requestBase.Setup(x => x.CurrentExecutionFilePath).Returns("/"); requestBase.Setup(x => x.CurrentExecutionFilePathExtension).Returns(string.Empty); requestBase.Setup(x => x.Form).Returns(formCollection); requestBase.Setup(x => x.HttpMethod).Returns("GET"); requestBase.Setup(x => x.Path).Returns("/"); requestBase.Setup(x => x.RawUrl).Returns(path); requestBase.Setup(x => x.RequestType).Returns("GET"); requestBase.Setup(x => x.Url).Returns(requestUrl); requestBase.Setup(x => x.UserHostAddress).Returns(clientIP); requestBase.Setup(x => x.UserHostName).Returns(clientIP); return requestBase.Object; } /// <summary> /// Generates an initialized <see cref="RequestContext(System.Uri,string,string,System.Collections.Specialized.NameValueCollection,object,string)"/>. /// </summary> /// <param name="httpContext"> The http context. </param> /// <param name="values"> The route values. </param> /// <returns> The <see cref="RequestContext(System.Uri,string,string,System.Collections.Specialized.NameValueCollection,object,string)"/>. </returns> private static RequestContext RequestContext(HttpContextBase httpContext, object values) { var requestContext = new Moq.Mock<RequestContext>(); requestContext.Setup(x => x.HttpContext).Returns(httpContext); requestContext.Setup(x => x.RouteData).Returns(RouteData(values)); return requestContext.Object; } /// <summary> /// Generates an initialized <see cref="RouteData"/>. /// </summary> /// <param name="values"> The values. </param> /// <returns> The <see cref="RouteData"/>. </returns> private static RouteData RouteData(object values) { var routeData = new RouteData { Route = new Route("{controller}/{action}/{id}", new MvcRouteHandler()) { Defaults = new RouteValueDictionary(values), Constraints = new RouteValueDictionary((object)null), DataTokens = new RouteValueDictionary() }, }; routeData.Values.Add("controller", "Home"); routeData.Values.Add("action", "Index"); return routeData; } /// <summary> /// Generates an initialized <see cref="ViewContext"/>. /// </summary> /// <param name="requestUrl"> The request URL. </param> /// <param name="sessionId"> The session id. </param> /// <param name="clientIP"> The client IP. </param> /// <param name="formCollection"> The form value collection. </param> /// <returns> The <see cref="ViewContext"/>. </returns> private static ViewContext ViewContext(Uri requestUrl, string sessionId, string clientIP, NameValueCollection formCollection) { object values = new { controller = "Home", action = "Index", id = UrlParameter.Optional }; var viewContext = new Mock<ViewContext>(); var requestContext = RequestContext(requestUrl, sessionId, clientIP, formCollection, values, "userName"); var routes = RouteCollection(values); var controller = Controller(requestContext, routes); viewContext.Setup(x => x.Controller).Returns(controller); return viewContext.Object; } } }
// HtmlAgilityPack V1.0 - Simon Mourier <simon underscore mourier at hotmail dot com> using System; using System.Diagnostics; using System.IO; using System.Text; using System.Xml; using System.Xml.XPath; namespace Marius.Html.Hap { /// <summary> /// Represents an HTML navigator on an HTML document seen as a data store. /// </summary> public class HtmlNodeNavigator : XPathNavigator { #region Fields private int _attindex; private HtmlNode _currentnode; private HtmlDocument _doc = new HtmlDocument(); private HtmlNameTable _nametable = new HtmlNameTable(); internal bool Trace; #endregion #region Constructors internal HtmlNodeNavigator() { Reset(); } internal HtmlNodeNavigator(HtmlDocument doc, HtmlNode currentNode) { if (currentNode == null) { throw new ArgumentNullException("currentNode"); } if (currentNode.OwnerDocument != doc) { throw new ArgumentException(HtmlDocument.HtmlExceptionRefNotChild); } InternalTrace(null); _doc = doc; Reset(); _currentnode = currentNode; } private HtmlNodeNavigator(HtmlNodeNavigator nav) { if (nav == null) { throw new ArgumentNullException("nav"); } InternalTrace(null); _doc = nav._doc; _currentnode = nav._currentnode; _attindex = nav._attindex; _nametable = nav._nametable; // REVIEW: should we do this? } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream. /// </summary> /// <param name="stream">The input stream.</param> public HtmlNodeNavigator(Stream stream) { _doc.Load(stream); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param> public HtmlNodeNavigator(Stream stream, bool detectEncodingFromByteOrderMarks) { _doc.Load(stream, detectEncodingFromByteOrderMarks); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="encoding">The character encoding to use.</param> public HtmlNodeNavigator(Stream stream, Encoding encoding) { _doc.Load(stream, encoding); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param> public HtmlNodeNavigator(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks) { _doc.Load(stream, encoding, detectEncodingFromByteOrderMarks); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream. /// </summary> /// <param name="stream">The input stream.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param> /// <param name="buffersize">The minimum buffer size.</param> public HtmlNodeNavigator(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int buffersize) { _doc.Load(stream, encoding, detectEncodingFromByteOrderMarks, buffersize); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a TextReader. /// </summary> /// <param name="reader">The TextReader used to feed the HTML data into the document.</param> public HtmlNodeNavigator(TextReader reader) { _doc.Load(reader); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> public HtmlNodeNavigator(string path) { _doc.Load(path); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param> public HtmlNodeNavigator(string path, bool detectEncodingFromByteOrderMarks) { _doc.Load(path, detectEncodingFromByteOrderMarks); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> /// <param name="encoding">The character encoding to use.</param> public HtmlNodeNavigator(string path, Encoding encoding) { _doc.Load(path, encoding); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param> public HtmlNodeNavigator(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks) { _doc.Load(path, encoding, detectEncodingFromByteOrderMarks); Reset(); } /// <summary> /// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file. /// </summary> /// <param name="path">The complete file path to be read.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param> /// <param name="buffersize">The minimum buffer size.</param> public HtmlNodeNavigator(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int buffersize) { _doc.Load(path, encoding, detectEncodingFromByteOrderMarks, buffersize); Reset(); } #endregion #region Properties /// <summary> /// Gets the base URI for the current node. /// Always returns string.Empty in the case of HtmlNavigator implementation. /// </summary> public override string BaseURI { get { InternalTrace(">"); return _nametable.GetOrAdd(string.Empty); } } /// <summary> /// Gets the current HTML document. /// </summary> public HtmlDocument CurrentDocument { get { return _doc; } } /// <summary> /// Gets the current HTML node. /// </summary> public HtmlNode CurrentNode { get { return _currentnode; } } /// <summary> /// Gets a value indicating whether the current node has child nodes. /// </summary> public override bool HasAttributes { get { InternalTrace(">" + (_currentnode.Attributes.Count > 0)); return (_currentnode.Attributes.Count > 0); } } /// <summary> /// Gets a value indicating whether the current node has child nodes. /// </summary> public override bool HasChildren { get { InternalTrace(">" + (_currentnode.ChildNodes.Count > 0)); return (_currentnode.ChildNodes.Count > 0); } } /// <summary> /// Gets a value indicating whether the current node is an empty element. /// </summary> public override bool IsEmptyElement { get { InternalTrace(">" + !HasChildren); // REVIEW: is this ok? return !HasChildren; } } /// <summary> /// Gets the name of the current HTML node without the namespace prefix. /// </summary> public override string LocalName { get { if (_attindex != -1) { InternalTrace("att>" + _currentnode.Attributes[_attindex].Name); return _nametable.GetOrAdd(_currentnode.Attributes[_attindex].Name); } InternalTrace("node>" + _currentnode.Name); return _nametable.GetOrAdd(_currentnode.Name); } } /// <summary> /// Gets the qualified name of the current node. /// </summary> public override string Name { get { InternalTrace(">" + _currentnode.Name); return _nametable.GetOrAdd(_currentnode.Name); } } /// <summary> /// Gets the namespace URI (as defined in the W3C Namespace Specification) of the current node. /// Always returns string.Empty in the case of HtmlNavigator implementation. /// </summary> public override string NamespaceURI { get { InternalTrace(">"); return _nametable.GetOrAdd(string.Empty); } } /// <summary> /// Gets the <see cref="XmlNameTable"/> associated with this implementation. /// </summary> public override XmlNameTable NameTable { get { InternalTrace(null); return _nametable; } } /// <summary> /// Gets the type of the current node. /// </summary> public override XPathNodeType NodeType { get { switch (_currentnode.NodeType) { case HtmlNodeType.Comment: InternalTrace(">" + XPathNodeType.Comment); return XPathNodeType.Comment; case HtmlNodeType.Document: InternalTrace(">" + XPathNodeType.Root); return XPathNodeType.Root; case HtmlNodeType.Text: InternalTrace(">" + XPathNodeType.Text); return XPathNodeType.Text; case HtmlNodeType.Element: { if (_attindex != -1) { InternalTrace(">" + XPathNodeType.Attribute); return XPathNodeType.Attribute; } InternalTrace(">" + XPathNodeType.Element); return XPathNodeType.Element; } default: throw new NotImplementedException("Internal error: Unhandled HtmlNodeType: " + _currentnode.NodeType); } } } /// <summary> /// Gets the prefix associated with the current node. /// Always returns string.Empty in the case of HtmlNavigator implementation. /// </summary> public override string Prefix { get { InternalTrace(null); return _nametable.GetOrAdd(string.Empty); } } /// <summary> /// Gets the text value of the current node. /// </summary> public override string Value { get { InternalTrace("nt=" + _currentnode.NodeType); switch (_currentnode.NodeType) { case HtmlNodeType.Comment: InternalTrace(">" + ((HtmlCommentNode) _currentnode).Comment); return ((HtmlCommentNode) _currentnode).Comment; case HtmlNodeType.Document: InternalTrace(">"); return ""; case HtmlNodeType.Text: InternalTrace(">" + ((HtmlTextNode) _currentnode).Text); return ((HtmlTextNode) _currentnode).Text; case HtmlNodeType.Element: { if (_attindex != -1) { InternalTrace(">" + _currentnode.Attributes[_attindex].Value); return _currentnode.Attributes[_attindex].Value; } return _currentnode.InnerText; } default: throw new NotImplementedException("Internal error: Unhandled HtmlNodeType: " + _currentnode.NodeType); } } } /// <summary> /// Gets the xml:lang scope for the current node. /// Always returns string.Empty in the case of HtmlNavigator implementation. /// </summary> public override string XmlLang { get { InternalTrace(null); return _nametable.GetOrAdd(string.Empty); } } #endregion #region Public Methods /// <summary> /// Creates a new HtmlNavigator positioned at the same node as this HtmlNavigator. /// </summary> /// <returns>A new HtmlNavigator object positioned at the same node as the original HtmlNavigator.</returns> public override XPathNavigator Clone() { InternalTrace(null); return new HtmlNodeNavigator(this); } /// <summary> /// Gets the value of the HTML attribute with the specified LocalName and NamespaceURI. /// </summary> /// <param name="localName">The local name of the HTML attribute.</param> /// <param name="namespaceURI">The namespace URI of the attribute. Unsupported with the HtmlNavigator implementation.</param> /// <returns>The value of the specified HTML attribute. String.Empty or null if a matching attribute is not found or if the navigator is not positioned on an element node.</returns> public override string GetAttribute(string localName, string namespaceURI) { InternalTrace("localName=" + localName + ", namespaceURI=" + namespaceURI); HtmlAttribute att = _currentnode.Attributes[localName]; if (att == null) { InternalTrace(">null"); return null; } InternalTrace(">" + att.Value); return att.Value; } /// <summary> /// Returns the value of the namespace node corresponding to the specified local name. /// Always returns string.Empty for the HtmlNavigator implementation. /// </summary> /// <param name="name">The local name of the namespace node.</param> /// <returns>Always returns string.Empty for the HtmlNavigator implementation.</returns> public override string GetNamespace(string name) { InternalTrace("name=" + name); return string.Empty; } /// <summary> /// Determines whether the current HtmlNavigator is at the same position as the specified HtmlNavigator. /// </summary> /// <param name="other">The HtmlNavigator that you want to compare against.</param> /// <returns>true if the two navigators have the same position, otherwise, false.</returns> public override bool IsSamePosition(XPathNavigator other) { HtmlNodeNavigator nav = other as HtmlNodeNavigator; if (nav == null) { InternalTrace(">false"); return false; } InternalTrace(">" + (nav._currentnode == _currentnode)); return (nav._currentnode == _currentnode); } /// <summary> /// Moves to the same position as the specified HtmlNavigator. /// </summary> /// <param name="other">The HtmlNavigator positioned on the node that you want to move to.</param> /// <returns>true if successful, otherwise false. If false, the position of the navigator is unchanged.</returns> public override bool MoveTo(XPathNavigator other) { HtmlNodeNavigator nav = other as HtmlNodeNavigator; if (nav == null) { InternalTrace(">false (nav is not an HtmlNodeNavigator)"); return false; } InternalTrace("moveto oid=" + nav.GetHashCode() + ", n:" + nav._currentnode.Name + ", a:" + nav._attindex); if (nav._doc == _doc) { _currentnode = nav._currentnode; _attindex = nav._attindex; InternalTrace(">true"); return true; } // we don't know how to handle that InternalTrace(">false (???)"); return false; } /// <summary> /// Moves to the HTML attribute with matching LocalName and NamespaceURI. /// </summary> /// <param name="localName">The local name of the HTML attribute.</param> /// <param name="namespaceURI">The namespace URI of the attribute. Unsupported with the HtmlNavigator implementation.</param> /// <returns>true if the HTML attribute is found, otherwise, false. If false, the position of the navigator does not change.</returns> public override bool MoveToAttribute(string localName, string namespaceURI) { InternalTrace("localName=" + localName + ", namespaceURI=" + namespaceURI); int index = _currentnode.Attributes.GetAttributeIndex(localName); if (index == -1) { InternalTrace(">false"); return false; } _attindex = index; InternalTrace(">true"); return true; } /// <summary> /// Moves to the first sibling of the current node. /// </summary> /// <returns>true if the navigator is successful moving to the first sibling node, false if there is no first sibling or if the navigator is currently positioned on an attribute node.</returns> public override bool MoveToFirst() { if (_currentnode.ParentNode == null) { InternalTrace(">false"); return false; } if (_currentnode.ParentNode.FirstChild == null) { InternalTrace(">false"); return false; } _currentnode = _currentnode.ParentNode.FirstChild; InternalTrace(">true"); return true; } /// <summary> /// Moves to the first HTML attribute. /// </summary> /// <returns>true if the navigator is successful moving to the first HTML attribute, otherwise, false.</returns> public override bool MoveToFirstAttribute() { if (!HasAttributes) { InternalTrace(">false"); return false; } _attindex = 0; InternalTrace(">true"); return true; } /// <summary> /// Moves to the first child of the current node. /// </summary> /// <returns>true if there is a first child node, otherwise false.</returns> public override bool MoveToFirstChild() { if (!_currentnode.HasChildNodes) { InternalTrace(">false"); return false; } _currentnode = _currentnode.ChildNodes[0]; InternalTrace(">true"); return true; } /// <summary> /// Moves the XPathNavigator to the first namespace node of the current element. /// Always returns false for the HtmlNavigator implementation. /// </summary> /// <param name="scope">An XPathNamespaceScope value describing the namespace scope.</param> /// <returns>Always returns false for the HtmlNavigator implementation.</returns> public override bool MoveToFirstNamespace(XPathNamespaceScope scope) { InternalTrace(null); return false; } /// <summary> /// Moves to the node that has an attribute of type ID whose value matches the specified string. /// </summary> /// <param name="id">A string representing the ID value of the node to which you want to move. This argument does not need to be atomized.</param> /// <returns>true if the move was successful, otherwise false. If false, the position of the navigator is unchanged.</returns> public override bool MoveToId(string id) { InternalTrace("id=" + id); HtmlNode node = _doc.GetElementbyId(id); if (node == null) { InternalTrace(">false"); return false; } _currentnode = node; InternalTrace(">true"); return true; } /// <summary> /// Moves the XPathNavigator to the namespace node with the specified local name. /// Always returns false for the HtmlNavigator implementation. /// </summary> /// <param name="name">The local name of the namespace node.</param> /// <returns>Always returns false for the HtmlNavigator implementation.</returns> public override bool MoveToNamespace(string name) { InternalTrace("name=" + name); return false; } /// <summary> /// Moves to the next sibling of the current node. /// </summary> /// <returns>true if the navigator is successful moving to the next sibling node, false if there are no more siblings or if the navigator is currently positioned on an attribute node. If false, the position of the navigator is unchanged.</returns> public override bool MoveToNext() { if (_currentnode.NextSibling == null) { InternalTrace(">false"); return false; } InternalTrace("_c=" + _currentnode.CloneNode(false).OuterHtml); InternalTrace("_n=" + _currentnode.NextSibling.CloneNode(false).OuterHtml); _currentnode = _currentnode.NextSibling; InternalTrace(">true"); return true; } /// <summary> /// Moves to the next HTML attribute. /// </summary> /// <returns></returns> public override bool MoveToNextAttribute() { InternalTrace(null); if (_attindex >= (_currentnode.Attributes.Count - 1)) { InternalTrace(">false"); return false; } _attindex++; InternalTrace(">true"); return true; } /// <summary> /// Moves the XPathNavigator to the next namespace node. /// Always returns falsefor the HtmlNavigator implementation. /// </summary> /// <param name="scope">An XPathNamespaceScope value describing the namespace scope.</param> /// <returns>Always returns false for the HtmlNavigator implementation.</returns> public override bool MoveToNextNamespace(XPathNamespaceScope scope) { InternalTrace(null); return false; } /// <summary> /// Moves to the parent of the current node. /// </summary> /// <returns>true if there is a parent node, otherwise false.</returns> public override bool MoveToParent() { if (_currentnode.ParentNode == null) { InternalTrace(">false"); return false; } _currentnode = _currentnode.ParentNode; InternalTrace(">true"); return true; } /// <summary> /// Moves to the previous sibling of the current node. /// </summary> /// <returns>true if the navigator is successful moving to the previous sibling node, false if there is no previous sibling or if the navigator is currently positioned on an attribute node.</returns> public override bool MoveToPrevious() { if (_currentnode.PreviousSibling == null) { InternalTrace(">false"); return false; } _currentnode = _currentnode.PreviousSibling; InternalTrace(">true"); return true; } /// <summary> /// Moves to the root node to which the current node belongs. /// </summary> public override void MoveToRoot() { _currentnode = _doc.DocumentNode; InternalTrace(null); } #endregion #region Internal Methods [Conditional("TRACE")] internal void InternalTrace(object traceValue) { if (!Trace) { return; } StackFrame sf = new StackFrame(1, true); string name = sf.GetMethod().Name; string nodename = _currentnode == null ? "(null)" : _currentnode.Name; string nodevalue; if (_currentnode == null) { nodevalue = "(null)"; } else { switch (_currentnode.NodeType) { case HtmlNodeType.Comment: nodevalue = ((HtmlCommentNode) _currentnode).Comment; break; case HtmlNodeType.Document: nodevalue = ""; break; case HtmlNodeType.Text: nodevalue = ((HtmlTextNode) _currentnode).Text; break; default: nodevalue = _currentnode.CloneNode(false).OuterHtml; break; } } System.Diagnostics.Trace.WriteLine(string.Format("oid={0},n={1},a={2},v={3},{4}", GetHashCode(), nodename, _attindex, nodevalue, traceValue), "N!" + name); } #endregion #region Private Methods private void Reset() { InternalTrace(null); _currentnode = _doc.DocumentNode; _attindex = -1; } #endregion } }
// Copyright (c) Microsoft Open Technologies, Inc. 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; using System.Collections.Generic; using System.Text; using System.Xml; using System.IO; using System.Diagnostics; using System.Globalization; using System.Linq; namespace DocumentFormat.OpenXml { /// <summary> /// Specifies the type of each child element's occurence. /// Used in GetElement() and SetElement() for generated code. /// </summary> internal enum OpenXmlCompositeType { Other, /// <summary> /// xsd:sequence, and maxOccurs=1. /// </summary> OneSequence, /// <summary> /// xsd:choice, and maxOccurs=1. /// </summary> OneChoice, /// <summary> /// xsd:all. /// </summary> OneAll } /// <summary> /// Represents the base class for composite elements. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] public abstract class OpenXmlCompositeElement : OpenXmlElement { private OpenXmlElement _lastChild; /// <summary> /// Initializes a new instance of the OpenXmlCompositeElement class. /// </summary> protected OpenXmlCompositeElement() : base() { } /// <summary> /// Initializes a new instance of the OpenXmlCompositeElement class using the supplied outer XML. /// </summary> /// <param name="outerXml">The outer XML of the element.</param> protected OpenXmlCompositeElement(string outerXml) : base(outerXml) { } /// <summary> /// Initializes a new instance of the OpenXmlCompositeElement class using the supplied collection of elements. /// </summary> /// <param name="childrenElements">A collection of elements.</param> protected OpenXmlCompositeElement(IEnumerable childrenElements) : this( ) { if (childrenElements == null) { throw new ArgumentNullException("childrenElements"); } foreach (OpenXmlElement child in childrenElements) { this.AppendChild(child); } } /// <summary> /// Initializes a new instance of the OpenXmlCompositeElement class using the supplied collection of OpenXmlElement elements. /// </summary> /// <param name="childrenElements">A collection of OpenXmlElement elements.</param> protected OpenXmlCompositeElement(IEnumerable<OpenXmlElement> childrenElements) : this() { if (childrenElements == null) { throw new ArgumentNullException("childrenElements"); } foreach (OpenXmlElement child in childrenElements) { this.AppendChild(child); } } /// <summary> /// Initializes a new instance of the OpenXmlCompositeElement using the supplied array of OpenXmlElement elements. /// </summary> /// <param name="childrenElements">An array of OpenXmlElement elements.</param> protected OpenXmlCompositeElement(params OpenXmlElement[] childrenElements) : this() { if (childrenElements == null) { throw new ArgumentNullException("childrenElements"); } foreach (OpenXmlElement child in childrenElements) { this.AppendChild(child); } } #region public properties /// <summary> /// Gets the first child of the current OpenXmlElement element. /// </summary> /// <remarks> /// Returns null (Nothing in Visual Basic) if there is no such OpenXmlElement element. /// </remarks> public override OpenXmlElement FirstChild { get { this.MakeSureParsed(); OpenXmlElement lastChild = this._lastChild; if (lastChild != null) { return lastChild.next; } return null; } } /// <summary> /// Gets the last child of the current OpenXmlElement element. /// Returns null (Nothing in Visual Basic) if there is no such OpenXmlElement element. /// </summary> public override OpenXmlElement LastChild { get { this.MakeSureParsed(); return this._lastChild; } } /// <summary> /// Gets a value that indicates whether the current element has any child elements. /// </summary> public override bool HasChildren { get { return this.LastChild != null; } } /// <summary> /// Gets or sets the concatenated values of the current node and all of its children. /// </summary> public override string InnerText { get { StringBuilder innerText = new StringBuilder(); foreach (OpenXmlElement child in this.ChildElements) { innerText.Append(child.InnerText); } return innerText.ToString(); } //set //{ // throw new InvalidOperationException(); //} } /// <summary> /// Gets or sets the markup that represents only the child nodes of the current node. /// </summary> public override string InnerXml { set { // first, clear all children this.RemoveAllChildren(); if ( ! String.IsNullOrEmpty(value)) { // create an outer XML by wrapping the InnerXml with this element. // because XmlReader can not be created on InnerXml ( InnerXml may have several root elements ). StringWriter w = new StringWriter(CultureInfo.InvariantCulture); XmlTextWriter writer2 = new XmlDOMTextWriter(w); try { writer2.WriteStartElement(this.Prefix, this.LocalName, this.NamespaceUri); writer2.WriteRaw(value); writer2.WriteEndElement(); } finally { writer2.Close(); } // create a temp element to parse the xml. OpenXmlElement newElement = this.CloneNode(false); newElement.OuterXml = w.ToString(); OpenXmlElement child = newElement.FirstChild; OpenXmlElement next = null; // then move all children to this element. while (child != null) { next = child.NextSibling(); child = newElement.RemoveChild(child); this.AppendChild(child); child = next; } } } } #endregion #region change children /// <summary> /// Appends the specified element to the end of the current element's list of child nodes. /// </summary> /// <param name="newChild">The OpenXmlElement element to append.</param> /// <returns>The OpenXmlElement element that was appended. </returns> /// <remarks>Returns null if newChild equals null.</remarks> public override T AppendChild<T>(T newChild) { if (newChild == null) { // throw new ArgumentNullException("newChild"); return null; } if (newChild.Parent != null) { throw new InvalidOperationException(ExceptionMessages.ElementIsPartOfTree); } this.ElementInsertingEvent(newChild); OpenXmlElement prevNode = this.LastChild; OpenXmlElement nextNode = newChild; if (prevNode == null) { nextNode.next = nextNode; this._lastChild = nextNode; } else { nextNode.next = prevNode.next; prevNode.next = nextNode; this._lastChild = nextNode; } newChild.Parent = this; // SetOwner(newChild); this.ElementInsertedEvent(newChild); return newChild; } /// <summary> /// Inserts the specified element immediately after the specified reference element. /// </summary> /// <param name="newChild">The OpenXmlElement element to insert.</param> /// <param name="refChild">The OpenXmlElement element that is in the reference node.</param> /// <returns>The OpenXmlElement element that was inserted.</returns> /// <remarks>Returns null if newChild is null. </remarks> public override T InsertAfter<T>(T newChild, OpenXmlElement refChild) { if (newChild == null) { // throw new ArgumentNullException("newChild"); return null; } if (newChild.Parent != null) { throw new InvalidOperationException(ExceptionMessages.ElementIsPartOfTree); } if (refChild == null) { return this.PrependChild(newChild); } if (refChild.Parent != this) { throw new InvalidOperationException(); } this.ElementInsertingEvent(newChild); OpenXmlElement nextNode = newChild; OpenXmlElement prevNode = refChild; Debug.Assert(nextNode != null); Debug.Assert(prevNode != null); if (prevNode == this._lastChild) { nextNode.next = prevNode.next; prevNode.next = nextNode; this._lastChild = nextNode; } else { OpenXmlElement next = prevNode.next; nextNode.next = next; prevNode.next = nextNode; } newChild.Parent = this; // SetOwner(newChild); this.ElementInsertedEvent(newChild); return newChild; } /// <summary> /// Inserts the specified element immediately before the specified reference element. /// </summary> /// <param name="newChild">The OpenXmlElement to insert.</param> /// <param name="refChild">The OpenXmlElement that is in the reference node.</param> /// <returns>The OpenXmlElement that was inserted.</returns> /// <remarks>Returns null if newChild equals null.</remarks> public override T InsertBefore<T>(T newChild, OpenXmlElement refChild) { if (newChild == null) { // throw new ArgumentNullException("newChild"); return null; } if (newChild.Parent != null) { throw new InvalidOperationException(ExceptionMessages.ElementIsPartOfTree); } if (refChild == null) { return this.AppendChild(newChild); } if (refChild != null && refChild.Parent != this) { throw new InvalidOperationException(); } this.ElementInsertingEvent(newChild); OpenXmlElement prevNode = newChild; OpenXmlElement nextNode = refChild; Debug.Assert(nextNode != null); Debug.Assert(prevNode != null); if (nextNode == this.FirstChild) { prevNode.next = nextNode; this._lastChild.next = prevNode; } else { OpenXmlElement previousSibling = nextNode.PreviousSibling(); prevNode.next = nextNode; previousSibling.next = prevNode; } newChild.Parent = this; // SetOwner(newChild); this.ElementInsertedEvent(newChild); return newChild; } /// <summary> /// Inserts the specified element at the specified index of the current element's children. /// </summary> /// <param name="newChild">The OpenXmlElement element to insert.</param> /// <param name="index">The zero-based index to insert the element to.</param> /// <returns>The OpenXmlElement element that was inserted.</returns> /// <remarks>Returns null if newChild equals null.</remarks> /// <exception cref="ArgumentOutOfRangeException">Thrown when index is less than 0 or is greater than the count of children.</exception> public override T InsertAt<T>(T newChild, int index) { if (newChild == null) { // throw new ArgumentNullException("newChild"); return null; } if (newChild.Parent != null) { throw new InvalidOperationException(ExceptionMessages.ElementIsPartOfTree); } if (index < 0 || index > this.ChildElements.Count) { throw new ArgumentOutOfRangeException("index"); } else if ( index == 0 ) { return this.PrependChild(newChild); } else if ( index == this.ChildElements.Count ) { return this.AppendChild(newChild); } else { OpenXmlElement refChild = this.ChildElements[index]; return this.InsertBefore(newChild, refChild); } } /// <summary> /// Inserts the specified element at the beginning of the current element's list of child nodes. /// </summary> /// <param name="newChild">The OpenXmlElement element to add.</param> /// <returns>The OpenXmlElement that was added.</returns> /// <remarks>Returns null if newChild equals null.</remarks> public override T PrependChild<T>(T newChild) { if (newChild == null) { //throw new ArgumentNullException("newChild"); return null; } if (newChild.Parent != null) { throw new InvalidOperationException(ExceptionMessages.ElementIsPartOfTree); } return this.InsertBefore(newChild, this.FirstChild); } /// <summary> /// Removes the specified child element. /// </summary> /// <param name="oldChild">The element to remove. </param> /// <returns>The element that was removed. </returns> /// <remarks>Returns null if newChild equals null. </remarks> public override T RemoveChild<T>(T oldChild) { if (oldChild == null) { // throw new ArgumentNullException("oldChild"); return null; } if (oldChild.Parent != this) { throw new InvalidOperationException(ExceptionMessages.ElementIsNotChild); } T removedElement = oldChild; OpenXmlElement last = this._lastChild; this.ElementRemovingEvent(removedElement); if (removedElement == this.FirstChild) { if (removedElement == this._lastChild) { this._lastChild = null; } else { OpenXmlElement nextNode = removedElement.next; last.next = nextNode; } } else if (removedElement == this._lastChild) { OpenXmlElement prevNode = removedElement.PreviousSibling(); OpenXmlElement next = removedElement.next; prevNode.next = next; this._lastChild = prevNode; } else { OpenXmlElement prevNode = removedElement.PreviousSibling(); OpenXmlElement next = removedElement.next; prevNode.next = next; } //foreach (OpenXmlElement descendant in removedElement.Descendants()) //{ // descendant.Owner = null; //} removedElement.next = null; removedElement.Parent = null; //removedElement.Owner = null; this.ElementRemovedEvent(removedElement); return removedElement; } /// <summary> /// Removes all of the current element's child elements. /// </summary> public override void RemoveAllChildren() { OpenXmlElement element = this.FirstChild; while (element != null) { OpenXmlElement next = element.NextSibling(); this.RemoveChild(element); element = next; } Debug.Assert(this._lastChild == null); } /// <summary> /// Replaces one of the current element's child elements with another OpenXmlElement element. /// </summary> /// <param name="newChild">The new OpenXmlElement to put in the child list.</param> /// <param name="oldChild">The OpenXmlElement to be replaced in the child list.</param> /// <returns>The OpenXmlElement that was replaced.</returns> /// <remarks>Returns null if newChild equals null.</remarks> public override T ReplaceChild<T>(OpenXmlElement newChild, T oldChild) { if (oldChild == null) { //throw new ArgumentNullException("oldChild"); return null; } if (newChild == null) { throw new ArgumentNullException("newChild"); } if (oldChild.Parent != this) { throw new InvalidOperationException(ExceptionMessages.ElementIsNotChild); } if (newChild.Parent != null) { throw new InvalidOperationException(ExceptionMessages.ElementIsPartOfTree); } OpenXmlElement refChild = oldChild.NextSibling(); this.RemoveChild(oldChild); this.InsertBefore(newChild, refChild); return oldChild; } #endregion /// <summary> /// Saves all of the current node's children to the specified XmlWriter. /// </summary> /// <param name="w">The XmlWriter at which to save the child nodes. </param> internal override void WriteContentTo(XmlWriter w) { if (this.HasChildren) { foreach (OpenXmlElement childElement in this.ChildElements) { childElement.WriteTo(w); } } } #region Event mechanism /// <summary> /// Fires the ElementInserting event. /// </summary> /// <param name="element">The OpenXmlElement element to insert.</param> internal void ElementInsertingEvent(OpenXmlElement element) { if (this.OpenXmlElementContext != null) { this.OpenXmlElementContext.ElementInsertingEvent(element, this); } } /// <summary> /// Fires the ElementInserted event. /// </summary> /// <param name="element">The OpenXmlElement element to insert.</param> internal void ElementInsertedEvent(OpenXmlElement element) { if (this.OpenXmlElementContext != null) { this.OpenXmlElementContext.ElementInsertedEvent(element, this); } } /// <summary> /// Fires the ElementRemoving event. /// </summary> /// <param name="element">The OpenXmlElement element to remove.</param> internal void ElementRemovingEvent(OpenXmlElement element) { if (this.OpenXmlElementContext != null) { this.OpenXmlElementContext.ElementRemovingEvent(element, this); } } /// <summary> /// Fires the ElementRemoved event. /// </summary> /// <param name="element">The OpenXmlElement element to be removed.</param> internal void ElementRemovedEvent(OpenXmlElement element) { if (this.OpenXmlElementContext != null) { this.OpenXmlElementContext.ElementRemovedEvent(element, this); } } #endregion #region internal methods /// <summary> /// Populates the XML into a strong typed DOM tree. /// </summary> /// <param name="xmlReader">The XmlReader to read the XML content.</param> /// <param name="loadMode">Specifies a load mode that is either lazy or full.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] internal override void Populate(XmlReader xmlReader, OpenXmlLoadMode loadMode) { LoadAttributes(xmlReader); if (!xmlReader.IsEmptyElement) { xmlReader.Read(); // read this element while (!xmlReader.EOF) { // O15:#3024890, OpenXmlCompositElement ignores the Whitespace NodeType. if (xmlReader.NodeType == XmlNodeType.Whitespace) { xmlReader.Skip(); continue; } else if (xmlReader.NodeType == XmlNodeType.EndElement) { Debug.Assert(xmlReader.LocalName.Equals(this.LocalName)); xmlReader.Skip(); // move to next node break; } OpenXmlElement element = this.ElementFactory(xmlReader); // set parent before Load( ) call. AlternateContentChoice need parent info on loading. element.Parent = this; bool isACB = element is AlternateContent; if (isACB && element.OpenXmlElementContext != null) { element.OpenXmlElementContext.ACBlockLevel++; } bool mcContextPushed = false; if (!(element is OpenXmlMiscNode)) { // push MC context based on the context of the child element to be loaded mcContextPushed = this.PushMcContext(xmlReader); } //Process the element according to the MC behavior var action = ElementAction.Normal; if (OpenXmlElementContext != null && OpenXmlElementContext.MCSettings.ProcessMode != DocumentFormat.OpenXml.Packaging.MarkupCompatibilityProcessMode.NoProcess) { action = OpenXmlElementContext.MCContext.GetElementAction(element, OpenXmlElementContext.MCSettings.TargetFileFormatVersions); } element.Load(xmlReader, loadMode); if (mcContextPushed) { this.PopMcContext(); } if (isACB && element.OpenXmlElementContext != null) { element.OpenXmlElementContext.ACBlockLevel--; } switch (action) { case ElementAction.Normal: { AddANode(element); break; } case ElementAction.Ignore: { element.Parent = null; continue; } case ElementAction.ProcessContent: { element.Parent = null; while(element.ChildElements.Count > 0) { var node = element.FirstChild; node.Remove(); OpenXmlElement newnode = null; //if node is an UnknowElement, we should try to see whether the parent element can load the node as strong typed element if (node is OpenXmlUnknownElement) { newnode = this.ElementFactory(node.Prefix, node.LocalName, node.NamespaceUri); if (!(newnode is OpenXmlUnknownElement)) { //the following method will load teh element in MCMode.Full //since the node is already MC-processed when loading as unknown type, full loading the outerXml is fine newnode.OuterXml = node.OuterXml; //unnecessary xmlns attr will be added, remove it. RemoveUnnecessaryExtAttr(node, newnode); } else { newnode = null; } } if (newnode != null) { AddANode(newnode); } else { //append the orignal node AddANode(node); } } break; } case ElementAction.ACBlock: { var effectiveNode = OpenXmlElementContext.MCContext.GetContentFromACBlock(element as AlternateContent, OpenXmlElementContext.MCSettings.TargetFileFormatVersions); if (effectiveNode == null) { break; } element.Parent = null; effectiveNode.Parent = null; while(effectiveNode.FirstChild != null) { var node = effectiveNode.FirstChild; node.Remove(); AddANode(node); node.CheckMustUnderstandAttr(); } break; } } } } else { xmlReader.Skip(); } // set raw outer xml to empty to indicate that it is pased this.RawOuterXml = string.Empty; } private static void RemoveUnnecessaryExtAttr(OpenXmlElement node, OpenXmlElement newnode) { //re-construct the _nsMappings for newnode based on the orignal node node.MakeSureParsed(); if (newnode.NamespaceDeclField != null && node.NamespaceDeclField != null) { newnode.NamespaceDeclField = new List<KeyValuePair<string, string>>(node.NamespaceDeclField); } } /// <summary> /// Gets the tag names of the child elements. /// </summary> /// <remarks> /// This property is overriden in generated classes. /// </remarks> internal virtual string[] ElementTagNames { get { return null; } } /// <summary> /// Gets the namespace IDs of the child elements. /// </summary> /// <remarks> /// This property is overriden in generated classes. /// </remarks> internal virtual byte[] ElementNamespaceIds { get { return null; } } private int GetSequenceNumber( OpenXmlElement child ) { for (int i = 0; i < this.ElementNamespaceIds.Length; i++) { if (this.ElementNamespaceIds[i] == child.NamespaceId && Object.Equals(this.ElementTagNames[i], child.LocalName)) { return i; } } return -1; } /// <summary> /// Gets the child element that has the specified sequence number. /// Sequence numbers are generated by a code generator. /// </summary> /// <param name="sequenceNumber">The sequence number of the element.</param> /// <returns>An element that has the specified sequence number. Returns null (Nothing in Visual Basic) if no element is found having the specified sequence number.</returns> /// <remarks> /// Returns null if there are invalid children. /// </remarks> internal T GetElement<T>(int sequenceNumber) where T : OpenXmlElement { T theChild; switch (this.OpenXmlCompositeType) { case OpenXmlCompositeType.Other: throw new InvalidOperationException(); case OpenXmlCompositeType.OneAll: foreach (OpenXmlElement child in this.ChildElements) { // skip unknown element and MiscNode if (OpenXmlElement.IsKnownElement(child)) { int childSequenceNumber = this.GetSequenceNumber(child); if (childSequenceNumber == sequenceNumber) { theChild = child as T; if (theChild != null) { return theChild; } } } } // TODO: should we handle error case? // 1: there are more than 1 elements for a type? // 2: there are more than 2 elements? // 3. there are other elements other than allowed children? break; case OpenXmlCompositeType.OneChoice: { OpenXmlElement child = this.FirstChild; // skip unknown element and MiscNode while (child != null && !OpenXmlElement.IsKnownElement(child)) { child = child.NextSibling(); } // There should be only one valide child. if (child != null) { Debug.Assert(OpenXmlElement.IsKnownElement(child)); int childSequenceNumber = this.GetSequenceNumber(child); if (childSequenceNumber == sequenceNumber) { theChild = child as T; if (theChild != null) { return theChild; } } } } // TODO: should we handle error case? // 1: there are more than 1 elements for a type? // 2: there are more than 2 elements? // 3. there are other elements other than allowed children? break; case OpenXmlCompositeType.OneSequence: { OpenXmlElement child = this.FirstChild; while (child != null) { if (OpenXmlElement.IsKnownElement(child)) { int childSequenceNumber = this.GetSequenceNumber(child); if (childSequenceNumber == sequenceNumber) { theChild = child as T; if (theChild != null) { return theChild; } else { // same tag name, but wrong type, see bug 448241 child = child.NextSibling(); } } else if (childSequenceNumber > sequenceNumber) { return null; } else { child = child.NextSibling(); } } else { // skip unknown element and MiscNode child = child.NextSibling(); } } } // TODO: should we handle error case? // 1: there are more than 1 elements for a type? // 2: there are more than 2 elements? // 3. there are other elements other than allowed children? break; } return null; } internal void SetElement<T>(int sequenceNumber, T newChild) where T : OpenXmlElement { switch (this.OpenXmlCompositeType) { case OpenXmlCompositeType.Other: throw new InvalidOperationException(); case OpenXmlCompositeType.OneAll: { T child = this.GetElement<T>(sequenceNumber); if (child != null) { // remove the old one this.RemoveChild(child); } if (newChild != null) { this.AppendChild(newChild); } } // TODO: should we handle error case? // 1: there are more than 1 elements for a type? // 2: there are more than 2 elements? // 3. there are other elements other than allowed children? break; case OpenXmlCompositeType.OneChoice: { OpenXmlElement child = this.FirstChild; OpenXmlElement previousChild = null; // skip unknown element and MiscNode while (child != null && !OpenXmlElement.IsKnownElement(child)) { previousChild = child; child = child.NextSibling(); } OpenXmlElement next = null; while (child != null) { next = child.NextSibling(); // remove all exist elements if (OpenXmlElement.IsKnownElement(child)) { this.RemoveChild(child); } child = next; } if (newChild != null) { this.InsertAfter(newChild, previousChild); } } // TODO: should we handle error case? // 1: there are more than 1 elements for a type? // 2: there are more than 2 elements? // 3. there are other elements other than allowed children? break; case OpenXmlCompositeType.OneSequence: { OpenXmlElement child = this.FirstChild; OpenXmlElement prev = null; while (child != null) { if (OpenXmlElement.IsKnownElement(child)) { int childSequenceNumber = this.GetSequenceNumber(child); if (childSequenceNumber == sequenceNumber) { // remove the old one if (child is T) { // insert the new element after the previous. prev = child.PreviousSibling(); this.RemoveChild(child); break; } else { // same tag name, but wrong type, see bug 448241 prev = child; } } else if (childSequenceNumber > sequenceNumber) { break; } else { // always insert after the first known element prev = child; // continue search } } // continue search child = child.NextSibling(); } if (newChild != null) { this.InsertAfter(newChild, prev); } } // TODO: should we handle error case? // 1: there are more than 1 elements for a type? // 2: there are more than 2 elements? // 3. there are other elements other than allowed children? break; } } internal virtual OpenXmlCompositeType OpenXmlCompositeType { get { return OpenXmlCompositeType.Other; } } #endregion #region private methods private void AddANode(OpenXmlElement node) { node.Parent = this; if (this._lastChild == null) { node.next = node; this._lastChild = node; } else { node.next = this._lastChild.next; this._lastChild.next = node; this._lastChild = node; } } //private void SetOwner(OpenXmlElement element) //{ // element.Owner = this.Owner; // if (element.XmlParsed) // { // foreach (OpenXmlElement child in element.ChildElements) // { // SetOwner(child); // } // } //} #endregion } }
// ==++== // // // Copyright (c) 2006 Microsoft Corporation. All rights reserved. // // The use and distribution terms for this software are contained in the file // named license.txt, which can be found in the root of this distribution. // By using this software in any fashion, you are agreeing to be bound by the // terms of this license. // // You must not remove this notice, or any other, from this software. // // // ==--== namespace Microsoft.JScript { using Microsoft.JScript.Vsa; using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.Reflection; [System.Runtime.InteropServices.ComVisible(true)] public abstract class ScriptObject : IReflect{ protected ScriptObject parent; //Used by JSObject.GetMembers to cache members that must be delegated to other objects internal SimpleHashtable wrappedMemberCache; public VsaEngine engine; //This is only really useful for ScriptFunctions, IActivation objects and prototype objects. It lives here for the sake of simplicity. //Prototype objects do not need the scope stack, so in fast mode, all prototype objects can share a common engine. internal ScriptObject(ScriptObject parent){ this.parent = parent; this.wrappedMemberCache = null; if (this.parent != null) this.engine = parent.engine; else this.engine = null; } internal virtual bool DeleteMember(String name){ return false; } internal virtual Object GetDefaultValue(PreferredType preferred_type){ throw new JScriptException(JSError.InternalError); } public FieldInfo GetField(String name, BindingFlags bindingAttr){ foreach (MemberInfo member in this.GetMember(name, bindingAttr)) if (member.MemberType == MemberTypes.Field) return (FieldInfo)member; return null; } public virtual FieldInfo[] GetFields(BindingFlags bindingAttr){ ArrayObject arr = this as ArrayObject; if (arr != null && arr.denseArrayLength > 0){ //Interop fails to see elements unless they are returned in a GetXXXs call. An element in //the sparse portion of the array is returned as a FieldInfo. When interop asks for these //migrate the elements stored in the dense portion of the array to the sparse portion so that //they will be accessible. uint i, length; length = arr.denseArrayLength; if (length > arr.len) length = arr.len; for (i = 0; i < length; i++){ Object element = arr.denseArray[i]; if (element != Missing.Value) arr.SetMemberValue2(i.ToString(CultureInfo.InvariantCulture), element); //Implemented on JSObject and bypasses length checking } arr.denseArrayLength = 0; arr.denseArray = null; } MemberInfo[] members = this.GetMembers(bindingAttr); if (members == null) return new FieldInfo[0]; int fieldCount = 0; foreach (MemberInfo member in members) if (member.MemberType == MemberTypes.Field) fieldCount++; FieldInfo[] fields = new FieldInfo[fieldCount]; fieldCount = 0; foreach (MemberInfo member in members) if (member.MemberType == MemberTypes.Field) fields[fieldCount++] = (FieldInfo)member; return fields; } public abstract MemberInfo[] GetMember(String name, BindingFlags bindingAttr); internal virtual Object GetMemberValue(String name){ MemberInfo[] members = this.GetMember(name, BindingFlags.Instance|BindingFlags.Public); if (members.Length == 0) return Missing.Value; return LateBinding.GetMemberValue(this, name, LateBinding.SelectMember(members), members); } public abstract MemberInfo[] GetMembers(BindingFlags bindingAttr); public MethodInfo GetMethod(String name, BindingFlags bindingAttr){ return this.GetMethod(name, bindingAttr, JSBinder.ob, Type.EmptyTypes, null); } public MethodInfo GetMethod(String name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers){ MemberInfo[] members = this.GetMember(name, bindingAttr); if (members.Length == 1) return members[0] as MethodInfo; int methodCount = 0; foreach (MemberInfo member in members) if (member.MemberType == MemberTypes.Method) methodCount++; if (methodCount == 0) return null; MethodInfo[] methods = new MethodInfo[methodCount]; methodCount = 0; foreach (MemberInfo member in members) if (member.MemberType == MemberTypes.Method) methods[methodCount++] = (MethodInfo)member; if (binder == null) binder = JSBinder.ob; return (MethodInfo)binder.SelectMethod(bindingAttr, methods, types, modifiers); } public virtual MethodInfo[] GetMethods(BindingFlags bindingAttr){ MemberInfo[] members = this.GetMembers(bindingAttr); if (members == null) return new MethodInfo[0]; int methodCount = 0; foreach (MemberInfo member in members) if (member.MemberType == MemberTypes.Method) methodCount++; MethodInfo[] methods = new MethodInfo[methodCount]; methodCount = 0; foreach (MemberInfo member in members) if (member.MemberType == MemberTypes.Method) methods[methodCount++] = (MethodInfo)member; return methods; } //Returns the parent object (the object to which the script object delegates requests for properties/methods it does not implement itself). public ScriptObject GetParent(){ return this.parent; } internal virtual void GetPropertyEnumerator(ArrayList enums, ArrayList objects){ MemberInfo[] members = this.GetMembers(BindingFlags.Instance|BindingFlags.Public); if (members.Length > 0){ enums.Add(members.GetEnumerator()); objects.Add(this); } ScriptObject parent = this.GetParent(); if (parent != null) parent.GetPropertyEnumerator(enums, objects); } public PropertyInfo GetProperty(String name, BindingFlags bindingAttr){ return this.GetProperty(name, bindingAttr, JSBinder.ob, null, Type.EmptyTypes, null); } public PropertyInfo GetProperty(String name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers){ MemberInfo[] members = this.GetMember(name, bindingAttr); if (members.Length == 1) return members[0] as PropertyInfo; int propertyCount = 0; foreach (MemberInfo member in members) if (member.MemberType == MemberTypes.Property) propertyCount++; if (propertyCount == 0) return null; PropertyInfo[] properties = new PropertyInfo[propertyCount]; propertyCount = 0; foreach (MemberInfo member in members) if (member.MemberType == MemberTypes.Property) properties[propertyCount++] = (PropertyInfo)member; if (binder == null) binder = JSBinder.ob; return (PropertyInfo)binder.SelectProperty(bindingAttr, properties, returnType, types, modifiers); } public virtual PropertyInfo[] GetProperties(BindingFlags bindingAttr){ MemberInfo[] members = this.GetMembers(bindingAttr); if (members == null) return new PropertyInfo[0]; int propertyCount = 0; foreach (MemberInfo member in members) if (member.MemberType == MemberTypes.Property) propertyCount++; PropertyInfo[] properties = new PropertyInfo[propertyCount]; propertyCount = 0; foreach (MemberInfo member in members) if (member.MemberType == MemberTypes.Property) properties[propertyCount++] = (PropertyInfo)member; return properties; } internal virtual Object GetValueAtIndex(uint index){ return this.GetMemberValue(index.ToString(CultureInfo.CurrentUICulture)); } #if !DEBUG [DebuggerStepThroughAttribute] [DebuggerHiddenAttribute] #endif public virtual Object InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo locale, String[] namedParameters){ if (target != this) throw new TargetException(); bool preferredTypeSpecified = name.StartsWith("< JScript-", StringComparison.Ordinal); bool dispid0 = (name == null || name == String.Empty || name.Equals("[DISPID=0]") || preferredTypeSpecified); if ((invokeAttr & BindingFlags.CreateInstance) != 0){ if ((invokeAttr & (BindingFlags.InvokeMethod|BindingFlags.GetField|BindingFlags.GetProperty| BindingFlags.SetField|BindingFlags.SetProperty|BindingFlags.PutDispProperty)) != 0) throw new ArgumentException(JScriptException.Localize("Bad binding flags", locale)); //js: x = new foo() --> dispid0, create if (dispid0) throw new MissingMethodException(); //js: x = new foo.name() --> dispid0, create LateBinding lb = new LateBinding(name, this); return lb.Call(binder, args, modifiers, locale, namedParameters, true, false, this.engine); } //According to docs, name == null is only valid for CreateInstance if (name == null) throw new ArgumentException(JScriptException.Localize("Bad name", locale)); if ((invokeAttr & (BindingFlags.InvokeMethod|BindingFlags.GetField|BindingFlags.GetProperty)) != 0){ if ((invokeAttr & (BindingFlags.SetField|BindingFlags.SetProperty|BindingFlags.PutDispProperty)) != 0) throw new ArgumentException(JScriptException.Localize("Bad binding flags", locale)); if (dispid0){ //All callable functions inherit from ScriptFunction which overrides this method to handle //the InvokeMethod case. //js,vbs: x = foo() --> dispid0, invoke if ((invokeAttr & (BindingFlags.GetField|BindingFlags.GetProperty)) == 0) throw new MissingMethodException(); //js: x = foo --> dispid0, propget; vbs: x = foo --> dispid0, invoke|propget if (args == null || args.Length == 0){ if (this is JSObject || this is GlobalScope || this is ClassScope){ PreferredType preferredType = PreferredType.Either; if (preferredTypeSpecified){ if (name.StartsWith("< JScript-Number", StringComparison.Ordinal)) preferredType = PreferredType.Number; else if (name.StartsWith("< JScript-String", StringComparison.Ordinal)) preferredType = PreferredType.String; else if (name.StartsWith("< JScript-LocaleString", StringComparison.Ordinal)) preferredType = PreferredType.LocaleString; } return this.GetDefaultValue(preferredType); } throw new MissingFieldException(); } //We support indexed properties with exactly one index on all script objects. //js,vbs: x = foo(1,2) --> dispid0, invoke|propget if (args.Length > 1) throw new ArgumentException(JScriptException.Localize("Too many arguments", locale)); //js,vbs: x = foo(1) --> dispid0, invoke|propget Object val = args[0]; if (val is Int32) return this[(int)val]; IConvertible ic = Convert.GetIConvertible(val); if (ic != null && Convert.IsPrimitiveNumericTypeCode(ic.GetTypeCode())){ double d = ic.ToDouble(null); if (d >= 0 && d <= Int32.MaxValue && d == System.Math.Round(d)) return this[(int)d]; } return this[Convert.ToString(val)]; } //If no arguments are supplied, prefer GetXXXX rather than Invoke. //js: x = foo.bar --> name="bar", propget; vbs: x = foo.bar --> name="bar", propget|invoke if ((args == null || args.Length == 0) && (invokeAttr & (BindingFlags.GetField|BindingFlags.GetProperty)) != 0){ Object member = this.GetMemberValue(name); if (member != Missing.Value) return member; //js: x = foo.bar --> name="bar", propget if ((invokeAttr & BindingFlags.InvokeMethod) == 0) throw new MissingFieldException(); } //Use LateBinding to call because arguments have been supplied. //vbs: x = foo.bar --> name="bar", propget|invoke //js,vbs: x = foo.bar() --> name="bar", invoke //js,vbs: x = foo.bar(1) --> name="bar", invoke|propget LateBinding lb = new LateBinding(name, this); return lb.Call(binder, args, modifiers, locale, namedParameters, false, false, this.engine); } if ((invokeAttr & (BindingFlags.SetField | BindingFlags.SetProperty | BindingFlags.PutDispProperty)) != 0){ if (dispid0){ if (args == null || args.Length < 2) throw new ArgumentException(JScriptException.Localize("Too few arguments", locale)); else if (args.Length > 2) throw new ArgumentException(JScriptException.Localize("Too many arguments", locale)); Object val = args[0]; if (val is Int32){ this[(int)val] = args[1]; return null; } IConvertible ic = Convert.GetIConvertible(val); if (ic != null && Convert.IsPrimitiveNumericTypeCode(ic.GetTypeCode())){ double d = ic.ToDouble(null); if (d >= 0 && d <= Int32.MaxValue && d == System.Math.Round(d)){ this[(int)d] = args[1]; return null; } } this[Convert.ToString(val)] = args[1]; return null; } if (args == null || args.Length < 1) throw new ArgumentException(JScriptException.Localize("Too few arguments", locale)); else if (args.Length > 1) throw new ArgumentException(JScriptException.Localize("Too many arguments", locale)); this.SetMemberValue(name, args[0]); return null; } throw new ArgumentException(JScriptException.Localize("Bad binding flags", locale)); } //This routine combines a GetField/GetProperty (with expando) and a subsequent SetValue operation. //It is used when the Field/Property cannot be cached. It is overridden by JSObject and GlobalScope to provide expando internal virtual void SetMemberValue(String name, Object value){ MemberInfo[] members = this.GetMember(name, BindingFlags.Instance|BindingFlags.Public); LateBinding.SetMemberValue(this, name, value, LateBinding.SelectMember(members), members); } internal void SetParent(ScriptObject parent){ this.parent = parent; if (parent != null) this.engine = parent.engine; } //This routine combines a GetField/GetProperty and a subsequent SetValue operation. //It is used when the Field/Property cannot be cached. //It has the advantage that Arrays need never create a JSField object to access array elements. //Also, it avoids the need to convert the index into a string. internal virtual void SetValueAtIndex(uint index, Object value){ this.SetMemberValue(index.ToString(CultureInfo.InvariantCulture), value); } public Object this[double index]{ get{ if (this == null) throw new JScriptException(JSError.ObjectExpected); Object result; if (index >= 0 && index <= UInt32.MaxValue && index == System.Math.Round(index)) result = this.GetValueAtIndex((uint)index); else result = this.GetMemberValue(Convert.ToString(index)); return result is Missing ? null : result; } set{ if (index >= 0 && index <= UInt32.MaxValue && index == System.Math.Round(index)) this.SetValueAtIndex((uint)index, value); else this.SetMemberValue(Convert.ToString(index), value); } } public Object this[int index]{ get{ if (this == null) throw new JScriptException(JSError.ObjectExpected); Object result; if (index >= 0) result = this.GetValueAtIndex((uint)index); else result = this.GetMemberValue(Convert.ToString(index)); return result is Missing ? null : result; } set{ if (this == null) throw new JScriptException(JSError.ObjectExpected); if (index >= 0) this.SetValueAtIndex((uint)index, value); else this.SetMemberValue(Convert.ToString(index), value); } } public Object this[String name]{ get{ if (this == null) throw new JScriptException(JSError.ObjectExpected); Object result = this.GetMemberValue(name); return result is Missing ? null : result; } set{ if (this == null) throw new JScriptException(JSError.ObjectExpected); this.SetMemberValue(name, value); } } public Object this[params Object[] pars]{ get{ int n = pars.Length; if (n == 0) if (this is ScriptFunction || this == null) throw new JScriptException(JSError.FunctionExpected); else throw new JScriptException(JSError.TooFewParameters); if (this == null) throw new JScriptException(JSError.ObjectExpected); Object val = pars[n-1]; if (val is Int32) return this[(int)val]; IConvertible ic = Convert.GetIConvertible(val); if (ic != null && Convert.IsPrimitiveNumericTypeCode(ic.GetTypeCode())){ double d = ic.ToDouble(null); if (d >= 0 && d <= Int32.MaxValue && d == System.Math.Round(d)) return this[(int)d]; } return this[Convert.ToString(val)]; } set{ int n = pars.Length; if (n == 0) if (this == null) throw new JScriptException(JSError.FunctionExpected); else if (this is ScriptFunction) throw new JScriptException(JSError.CannotAssignToFunctionResult); else throw new JScriptException(JSError.TooFewParameters); if (this == null) throw new JScriptException(JSError.ObjectExpected); Object val = pars[n-1]; if (val is Int32){ this[(int)val] = value; return; } IConvertible ic = Convert.GetIConvertible(val); if (ic != null && Convert.IsPrimitiveNumericTypeCode(ic.GetTypeCode())){ double d = ic.ToDouble(null); if (d >= 0 && d <= Int32.MaxValue && d == System.Math.Round(d)){ this[(int)d] = value; return; } } this[Convert.ToString(val)] = value; } } public virtual Type UnderlyingSystemType{ get{ return this.GetType(); } } protected static MemberInfo[] WrapMembers(MemberInfo[] members, Object obj){ if (members == null) return null; int n = members.Length; if (n == 0) return members; MemberInfo[] result = new MemberInfo[n]; for (int i = 0; i < n; i++) result[i] = ScriptObject.WrapMember(members[i], obj); return result; } protected static MemberInfo[] WrapMembers(MemberInfo member, Object obj){ MemberInfo[] result = new MemberInfo[1]; result[0] = ScriptObject.WrapMember(member, obj); return result; } protected static MemberInfo[] WrapMembers(MemberInfo[] members, Object obj, SimpleHashtable cache){ if (members == null) return null; int n = members.Length; if (n == 0) return members; MemberInfo[] result = new MemberInfo[n]; for (int i = 0; i < n; i++){ MemberInfo wrappedMember = (MemberInfo)cache[members[i]]; if (null == wrappedMember){ wrappedMember = ScriptObject.WrapMember(members[i], obj); cache[members[i]] = wrappedMember; } result[i] = wrappedMember; } return result; } internal static MemberInfo WrapMember(MemberInfo member, Object obj){ switch (member.MemberType){ case MemberTypes.Field: FieldInfo field = (FieldInfo)member; if (field.IsStatic || field.IsLiteral) return field; else if (!(field is JSWrappedField)) return new JSWrappedField(field, obj); else return field; case MemberTypes.Method: MethodInfo method = (MethodInfo)member; if (method.IsStatic) return method; else if (!(method is JSWrappedMethod)) return new JSWrappedMethod(method, obj); else return method; case MemberTypes.Property: PropertyInfo property = (PropertyInfo)member; if (property is JSWrappedProperty) return property; MethodInfo getMethod = JSProperty.GetGetMethod(property, true); MethodInfo setMethod = JSProperty.GetSetMethod(property, true); if ((getMethod == null || getMethod.IsStatic) && (setMethod == null || setMethod.IsStatic)) return property; else return new JSWrappedProperty(property, obj); default: return member; } } } }
/*************************************************************************** copyright : (C) 2005 by Brian Nickel email : [email protected] based on : id3v2frame.cpp from TagLib ***************************************************************************/ /*************************************************************************** * This library is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License version * * 2.1 as published by the Free Software Foundation. * * * * 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 * ***************************************************************************/ using System.Collections; using System; using TagLib; namespace TagLib.Id3v2 { public class AttachedPictureFrame : Frame, IPicture { ////////////////////////////////////////////////////////////////////////// // private properties ////////////////////////////////////////////////////////////////////////// private StringType text_encoding; private string mime_type; private PictureType type; private string description; private ByteVector data; ////////////////////////////////////////////////////////////////////////// // public methods ////////////////////////////////////////////////////////////////////////// public AttachedPictureFrame () : base ("APIC") { text_encoding = StringType.UTF8; mime_type = null; type = PictureType.Other; description = null; data = null; } public AttachedPictureFrame (IPicture picture) : base("APIC") { text_encoding = StringType.UTF8; mime_type = picture.MimeType; type = picture.Type; description = picture.Description; data = picture.Data; } public AttachedPictureFrame (ByteVector data) : base (data) { text_encoding = StringType.UTF8; mime_type = null; type = PictureType.Other; description = null; this.data = null; SetData (data, 0); } public override string ToString () { string s = "[" + mime_type + "]"; return description != null ? s : description + " " + s; } public static AttachedPictureFrame Find (Tag tag, string description) { foreach (AttachedPictureFrame f in tag.GetFrames ("APIC")) if (f != null && f.Description == description) return f; return null; } public static AttachedPictureFrame Find (Tag tag, PictureType type) { foreach (AttachedPictureFrame f in tag.GetFrames ("APIC")) if (f != null && f.Type == type) return f; return null; } public static AttachedPictureFrame Find (Tag tag, string description, PictureType type) { foreach (AttachedPictureFrame f in tag.GetFrames ("APIC")) if (f != null && f.Description == description && f.Type == type) return f; return null; } ////////////////////////////////////////////////////////////////////////// // public properties ////////////////////////////////////////////////////////////////////////// public StringType TextEncoding { get {return text_encoding;} set {text_encoding = value;} } public string MimeType { get {return mime_type;} set {mime_type = value;} } public PictureType Type { get {return type;} set {type = value;} } public string Description { get {return description;} set {description = value;} } public ByteVector Data { get {return data;} set {data = value;} } ////////////////////////////////////////////////////////////////////////// // protected methods ////////////////////////////////////////////////////////////////////////// protected override void ParseFields (ByteVector data) { if (data.Count < 5) { Debugger.Debug ("A picture frame must contain at least 5 bytes."); return; } int pos = 0; text_encoding = (StringType) data [pos++]; int byte_align = text_encoding == StringType.Latin1 || text_encoding == StringType.UTF8 ? 1 : 2; int offset; if (Header.Version > 2) { offset = data.Find (TextDelimiter (StringType.Latin1), pos); if(offset < pos) return; mime_type = data.Mid (pos, offset - pos).ToString (StringType.Latin1); pos = offset + 1; } else { ByteVector ext = data.Mid (pos, 3); if (ext == "JPG") mime_type = "image/jpeg"; else if (ext == "PNG") mime_type = "image/png"; else mime_type = "image/unknown"; pos += 3; } type = (PictureType) data [pos++]; offset = data.Find (TextDelimiter (text_encoding), pos, byte_align); if(offset < pos) return; description = data.Mid (pos, offset - pos).ToString (text_encoding); pos = offset + 1; this.data = data.Mid (pos); } protected override ByteVector RenderFields () { ByteVector data = new ByteVector (); data.Add ((byte) TextEncoding); data.Add (ByteVector.FromString (MimeType, TextEncoding)); data.Add (TextDelimiter (StringType.Latin1)); data.Add ((byte) type); data.Add (ByteVector.FromString (Description, TextEncoding)); data.Add (TextDelimiter (TextEncoding)); data.Add (this.data); return data; } protected internal AttachedPictureFrame (ByteVector data, int offset, FrameHeader h) : base (h) { text_encoding = StringType.UTF8; mime_type = null; type = PictureType.Other; description = null; this.data = null; ParseFields (FieldData (data, offset)); } } }
// 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.Reflection; 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 MaskStoreSingle() { var test = new StoreBinaryOpTest__MaskStoreSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.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 (Avx.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 (Avx.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(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } 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 StoreBinaryOpTest__MaskStoreSingle { private struct TestStruct { public Vector256<Single> _fld1; public Vector256<Single> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); return testStruct; } public void RunStructFldScenario(StoreBinaryOpTest__MaskStoreSingle testClass) { Avx.MaskStore((Single*)testClass._dataTable.outArrayPtr, _fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector256<Single> _clsVar1; private static Vector256<Single> _clsVar2; private Vector256<Single> _fld1; private Vector256<Single> _fld2; private SimpleBinaryOpTest__DataTable<Single, Single, Single> _dataTable; static StoreBinaryOpTest__MaskStoreSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); } public StoreBinaryOpTest__MaskStoreSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new SimpleBinaryOpTest__DataTable<Single, Single, Single>(_data1, _data2, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); Avx.MaskStore( (Single*)_dataTable.outArrayPtr, Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); Avx.MaskStore( (Single*)_dataTable.outArrayPtr, Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); Avx.MaskStore( (Single*)_dataTable.outArrayPtr, Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); typeof(Avx).GetMethod(nameof(Avx.MaskStore), new Type[] { typeof(Single*), typeof(Vector256<Single>), typeof(Vector256<Single>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.outArrayPtr, typeof(Single*)), Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); typeof(Avx).GetMethod(nameof(Avx.MaskStore), new Type[] { typeof(Single*), typeof(Vector256<Single>), typeof(Vector256<Single>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.outArrayPtr, typeof(Single*)), Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); typeof(Avx).GetMethod(nameof(Avx.MaskStore), new Type[] { typeof(Single*), typeof(Vector256<Single>), typeof(Vector256<Single>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.outArrayPtr, typeof(Single*)), Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); Avx.MaskStore( (Single*)_dataTable.outArrayPtr, _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr); Avx.MaskStore((Single*)_dataTable.outArrayPtr, left, right); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr)); Avx.MaskStore((Single*)_dataTable.outArrayPtr, left, right); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr)); Avx.MaskStore((Single*)_dataTable.outArrayPtr, left, right); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new StoreBinaryOpTest__MaskStoreSingle(); Avx.MaskStore((Single*)_dataTable.outArrayPtr, test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); Avx.MaskStore((Single*)_dataTable.outArrayPtr, _fld1, _fld2); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); Avx.MaskStore((Single*)_dataTable.outArrayPtr, test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(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(Vector256<Single> left, Vector256<Single> right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits((BitConverter.SingleToInt32Bits(left[0]) < 0) ? right[0] : BitConverter.SingleToInt32Bits(result[0]))) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits((BitConverter.SingleToInt32Bits(left[i]) < 0) ? right[i] : BitConverter.SingleToInt32Bits(result[i]))) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.MaskStore)}<Single>(Vector256<Single>, Vector256<Single>): {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; } } } }
// 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; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; namespace System.Net.Http { public class HttpClient : HttpMessageInvoker { #region Fields private static readonly TimeSpan s_defaultTimeout = TimeSpan.FromSeconds(100); private static readonly TimeSpan s_maxTimeout = TimeSpan.FromMilliseconds(int.MaxValue); private static readonly TimeSpan s_infiniteTimeout = Threading.Timeout.InfiniteTimeSpan; private const HttpCompletionOption defaultCompletionOption = HttpCompletionOption.ResponseContentRead; private volatile bool _operationStarted; private volatile bool _disposed; private CancellationTokenSource _pendingRequestsCts; private HttpRequestHeaders _defaultRequestHeaders; private Uri _baseAddress; private TimeSpan _timeout; private int _maxResponseContentBufferSize; #endregion Fields #region Properties public HttpRequestHeaders DefaultRequestHeaders { get { if (_defaultRequestHeaders == null) { _defaultRequestHeaders = new HttpRequestHeaders(); } return _defaultRequestHeaders; } } public Uri BaseAddress { get { return _baseAddress; } set { CheckBaseAddress(value, nameof(value)); CheckDisposedOrStarted(); if (NetEventSource.IsEnabled) NetEventSource.UriBaseAddress(this, value); _baseAddress = value; } } public TimeSpan Timeout { get { return _timeout; } set { if (value != s_infiniteTimeout && (value <= TimeSpan.Zero || value > s_maxTimeout)) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposedOrStarted(); _timeout = value; } } public long MaxResponseContentBufferSize { get { return _maxResponseContentBufferSize; } set { if (value <= 0) { throw new ArgumentOutOfRangeException(nameof(value)); } if (value > HttpContent.MaxBufferSize) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_buffersize_limit, HttpContent.MaxBufferSize)); } CheckDisposedOrStarted(); Debug.Assert(HttpContent.MaxBufferSize <= int.MaxValue); _maxResponseContentBufferSize = (int)value; } } #endregion Properties #region Constructors public HttpClient() : this(new HttpClientHandler()) { } public HttpClient(HttpMessageHandler handler) : this(handler, true) { } public HttpClient(HttpMessageHandler handler, bool disposeHandler) : base(handler, disposeHandler) { _timeout = s_defaultTimeout; _maxResponseContentBufferSize = HttpContent.MaxBufferSize; _pendingRequestsCts = new CancellationTokenSource(); } #endregion Constructors #region Public Send #region Simple Get Overloads public Task<string> GetStringAsync(string requestUri) => GetStringAsync(CreateUri(requestUri)); public Task<string> GetStringAsync(Uri requestUri) => GetStringAsyncCore(GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead)); private async Task<string> GetStringAsyncCore(Task<HttpResponseMessage> getTask) { // Wait for the response message. using (HttpResponseMessage responseMessage = await getTask.ConfigureAwait(false)) { // Make sure it completed successfully. responseMessage.EnsureSuccessStatusCode(); // Get the response content. HttpContent c = responseMessage.Content; if (c != null) { #if NET46 return await c.ReadAsStringAsync().ConfigureAwait(false); #else HttpContentHeaders headers = c.Headers; // Since the underlying byte[] will never be exposed, we use an ArrayPool-backed // stream to which we copy all of the data from the response. using (Stream responseStream = c.TryReadAsStream() ?? await c.ReadAsStreamAsync().ConfigureAwait(false)) using (var buffer = new HttpContent.LimitArrayPoolWriteStream(_maxResponseContentBufferSize, (int)headers.ContentLength.GetValueOrDefault())) { await responseStream.CopyToAsync(buffer).ConfigureAwait(false); if (buffer.Length > 0) { // Decode and return the data from the buffer. return HttpContent.ReadBufferAsString(buffer.GetBuffer(), headers); } } #endif } // No content to return. return string.Empty; } } public Task<byte[]> GetByteArrayAsync(string requestUri) => GetByteArrayAsync(CreateUri(requestUri)); public Task<byte[]> GetByteArrayAsync(Uri requestUri) => GetByteArrayAsyncCore(GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead)); private async Task<byte[]> GetByteArrayAsyncCore(Task<HttpResponseMessage> getTask) { // Wait for the response message. using (HttpResponseMessage responseMessage = await getTask.ConfigureAwait(false)) { // Make sure it completed successfully. responseMessage.EnsureSuccessStatusCode(); // Get the response content. HttpContent c = responseMessage.Content; if (c != null) { #if NET46 return await c.ReadAsByteArrayAsync().ConfigureAwait(false); #else HttpContentHeaders headers = c.Headers; using (Stream responseStream = c.TryReadAsStream() ?? await c.ReadAsStreamAsync().ConfigureAwait(false)) { long? contentLength = headers.ContentLength; Stream buffer; // declared here to share the state machine field across both if/else branches if (contentLength.HasValue) { // If we got a content length, then we assume that it's correct and create a MemoryStream // to which the content will be transferred. That way, assuming we actually get the exact // amount we were expecting, we can simply return the MemoryStream's underlying buffer. buffer = new HttpContent.LimitMemoryStream(_maxResponseContentBufferSize, (int)contentLength.GetValueOrDefault()); await responseStream.CopyToAsync(buffer).ConfigureAwait(false); if (buffer.Length > 0) { return ((HttpContent.LimitMemoryStream)buffer).GetSizedBuffer(); } } else { // If we didn't get a content length, then we assume we're going to have to grow // the buffer potentially several times and that it's unlikely the underlying buffer // at the end will be the exact size needed, in which case it's more beneficial to use // ArrayPool buffers and copy out to a new array at the end. buffer = new HttpContent.LimitArrayPoolWriteStream(_maxResponseContentBufferSize); try { await responseStream.CopyToAsync(buffer).ConfigureAwait(false); if (buffer.Length > 0) { return ((HttpContent.LimitArrayPoolWriteStream)buffer).ToArray(); } } finally { buffer.Dispose(); } } } #endif } // No content to return. return Array.Empty<byte>(); } } // Unbuffered by default public Task<Stream> GetStreamAsync(string requestUri) { return GetStreamAsync(CreateUri(requestUri)); } // Unbuffered by default public Task<Stream> GetStreamAsync(Uri requestUri) { return FinishGetStreamAsync(GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead)); } private async Task<Stream> FinishGetStreamAsync(Task<HttpResponseMessage> getTask) { HttpResponseMessage response = await getTask.ConfigureAwait(false); response.EnsureSuccessStatusCode(); HttpContent c = response.Content; return c != null ? (c.TryReadAsStream() ?? await c.ReadAsStreamAsync().ConfigureAwait(false)) : Stream.Null; } #endregion Simple Get Overloads #region REST Send Overloads public Task<HttpResponseMessage> GetAsync(string requestUri) { return GetAsync(CreateUri(requestUri)); } public Task<HttpResponseMessage> GetAsync(Uri requestUri) { return GetAsync(requestUri, defaultCompletionOption); } public Task<HttpResponseMessage> GetAsync(string requestUri, HttpCompletionOption completionOption) { return GetAsync(CreateUri(requestUri), completionOption); } public Task<HttpResponseMessage> GetAsync(Uri requestUri, HttpCompletionOption completionOption) { return GetAsync(requestUri, completionOption, CancellationToken.None); } public Task<HttpResponseMessage> GetAsync(string requestUri, CancellationToken cancellationToken) { return GetAsync(CreateUri(requestUri), cancellationToken); } public Task<HttpResponseMessage> GetAsync(Uri requestUri, CancellationToken cancellationToken) { return GetAsync(requestUri, defaultCompletionOption, cancellationToken); } public Task<HttpResponseMessage> GetAsync(string requestUri, HttpCompletionOption completionOption, CancellationToken cancellationToken) { return GetAsync(CreateUri(requestUri), completionOption, cancellationToken); } public Task<HttpResponseMessage> GetAsync(Uri requestUri, HttpCompletionOption completionOption, CancellationToken cancellationToken) { return SendAsync(new HttpRequestMessage(HttpMethod.Get, requestUri), completionOption, cancellationToken); } public Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content) { return PostAsync(CreateUri(requestUri), content); } public Task<HttpResponseMessage> PostAsync(Uri requestUri, HttpContent content) { return PostAsync(requestUri, content, CancellationToken.None); } public Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content, CancellationToken cancellationToken) { return PostAsync(CreateUri(requestUri), content, cancellationToken); } public Task<HttpResponseMessage> PostAsync(Uri requestUri, HttpContent content, CancellationToken cancellationToken) { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri); request.Content = content; return SendAsync(request, cancellationToken); } public Task<HttpResponseMessage> PutAsync(string requestUri, HttpContent content) { return PutAsync(CreateUri(requestUri), content); } public Task<HttpResponseMessage> PutAsync(Uri requestUri, HttpContent content) { return PutAsync(requestUri, content, CancellationToken.None); } public Task<HttpResponseMessage> PutAsync(string requestUri, HttpContent content, CancellationToken cancellationToken) { return PutAsync(CreateUri(requestUri), content, cancellationToken); } public Task<HttpResponseMessage> PutAsync(Uri requestUri, HttpContent content, CancellationToken cancellationToken) { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, requestUri); request.Content = content; return SendAsync(request, cancellationToken); } public Task<HttpResponseMessage> PatchAsync(string requestUri, HttpContent content) { return PatchAsync(CreateUri(requestUri), content); } public Task<HttpResponseMessage> PatchAsync(Uri requestUri, HttpContent content) { return PatchAsync(requestUri, content, CancellationToken.None); } public Task<HttpResponseMessage> PatchAsync(string requestUri, HttpContent content, CancellationToken cancellationToken) { return PatchAsync(CreateUri(requestUri), content, cancellationToken); } public Task<HttpResponseMessage> PatchAsync(Uri requestUri, HttpContent content, CancellationToken cancellationToken) { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Patch, requestUri); request.Content = content; return SendAsync(request, cancellationToken); } public Task<HttpResponseMessage> DeleteAsync(string requestUri) { return DeleteAsync(CreateUri(requestUri)); } public Task<HttpResponseMessage> DeleteAsync(Uri requestUri) { return DeleteAsync(requestUri, CancellationToken.None); } public Task<HttpResponseMessage> DeleteAsync(string requestUri, CancellationToken cancellationToken) { return DeleteAsync(CreateUri(requestUri), cancellationToken); } public Task<HttpResponseMessage> DeleteAsync(Uri requestUri, CancellationToken cancellationToken) { return SendAsync(new HttpRequestMessage(HttpMethod.Delete, requestUri), cancellationToken); } #endregion REST Send Overloads #region Advanced Send Overloads public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request) { return SendAsync(request, defaultCompletionOption, CancellationToken.None); } public override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { return SendAsync(request, defaultCompletionOption, cancellationToken); } public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption) { return SendAsync(request, completionOption, CancellationToken.None); } public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken) { if (request == null) { throw new ArgumentNullException(nameof(request)); } CheckDisposed(); CheckRequestMessage(request); SetOperationStarted(); PrepareRequestMessage(request); // PrepareRequestMessage will resolve the request address against the base address. // We need a CancellationTokenSource to use with the request. We always have the global // _pendingRequestsCts to use, plus we may have a token provided by the caller, and we may // have a timeout. If we have a timeout or a caller-provided token, we need to create a new // CTS (we can't, for example, timeout the pending requests CTS, as that could cancel other // unrelated operations). Otherwise, we can use the pending requests CTS directly. CancellationTokenSource cts; bool disposeCts; bool hasTimeout = _timeout != s_infiniteTimeout; if (hasTimeout || cancellationToken.CanBeCanceled) { disposeCts = true; cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _pendingRequestsCts.Token); if (hasTimeout) { cts.CancelAfter(_timeout); } } else { disposeCts = false; cts = _pendingRequestsCts; } // Initiate the send. Task<HttpResponseMessage> sendTask; try { sendTask = base.SendAsync(request, cts.Token); } catch { HandleFinishSendAsyncCleanup(cts, disposeCts); throw; } return completionOption == HttpCompletionOption.ResponseContentRead ? FinishSendAsyncBuffered(sendTask, request, cts, disposeCts) : FinishSendAsyncUnbuffered(sendTask, request, cts, disposeCts); } private async Task<HttpResponseMessage> FinishSendAsyncBuffered( Task<HttpResponseMessage> sendTask, HttpRequestMessage request, CancellationTokenSource cts, bool disposeCts) { HttpResponseMessage response = null; try { // Wait for the send request to complete, getting back the response. response = await sendTask.ConfigureAwait(false); if (response == null) { throw new InvalidOperationException(SR.net_http_handler_noresponse); } // Buffer the response content if we've been asked to and we have a Content to buffer. if (response.Content != null) { await response.Content.LoadIntoBufferAsync(_maxResponseContentBufferSize, cts.Token).ConfigureAwait(false); } if (NetEventSource.IsEnabled) NetEventSource.ClientSendCompleted(this, response, request); return response; } catch (Exception e) { response?.Dispose(); HandleFinishSendAsyncError(e, cts); throw; } finally { HandleFinishSendAsyncCleanup(cts, disposeCts); } } private async Task<HttpResponseMessage> FinishSendAsyncUnbuffered( Task<HttpResponseMessage> sendTask, HttpRequestMessage request, CancellationTokenSource cts, bool disposeCts) { try { HttpResponseMessage response = await sendTask.ConfigureAwait(false); if (response == null) { throw new InvalidOperationException(SR.net_http_handler_noresponse); } if (NetEventSource.IsEnabled) NetEventSource.ClientSendCompleted(this, response, request); return response; } catch (Exception e) { HandleFinishSendAsyncError(e, cts); throw; } finally { HandleFinishSendAsyncCleanup(cts, disposeCts); } } private void HandleFinishSendAsyncError(Exception e, CancellationTokenSource cts) { if (NetEventSource.IsEnabled) NetEventSource.Error(this, e); // If the cancellation token was canceled, we consider the exception to be caused by the // cancellation (e.g. WebException when reading from canceled response stream). if (cts.IsCancellationRequested && e is HttpRequestException) { if (NetEventSource.IsEnabled) NetEventSource.Error(this, $"Canceled"); throw new OperationCanceledException(cts.Token); } } private void HandleFinishSendAsyncCleanup(CancellationTokenSource cts, bool disposeCts) { // Dispose of the CancellationTokenSource if it was created specially for this request // rather than being used across multiple requests. if (disposeCts) { cts.Dispose(); } // This method used to also dispose of the request content, e.g.: // request.Content?.Dispose(); // This has multiple problems: // 1. It prevents code from reusing request content objects for subsequent requests, // as disposing of the object likely invalidates it for further use. // 2. It prevents the possibility of partial or full duplex communication, even if supported // by the handler, as the request content may still be in use even if the response // (or response headers) has been received. // By changing this to not dispose of the request content, disposal may end up being // left for the finalizer to handle, or the developer can explicitly dispose of the // content when they're done with it. But it allows request content to be reused, // and more importantly it enables handlers that allow receiving of the response before // fully sending the request. Prior to this change, a handler like CurlHandler would // fail trying to access certain sites, if the site sent its response before it had // completely received the request: CurlHandler might then find that the request content // was disposed of while it still needed to read from it. } public void CancelPendingRequests() { CheckDisposed(); if (NetEventSource.IsEnabled) NetEventSource.Enter(this); // With every request we link this cancellation token source. CancellationTokenSource currentCts = Interlocked.Exchange(ref _pendingRequestsCts, new CancellationTokenSource()); currentCts.Cancel(); currentCts.Dispose(); if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } #endregion Advanced Send Overloads #endregion Public Send #region IDisposable Members protected override void Dispose(bool disposing) { if (disposing && !_disposed) { _disposed = true; // Cancel all pending requests (if any). Note that we don't call CancelPendingRequests() but cancel // the CTS directly. The reason is that CancelPendingRequests() would cancel the current CTS and create // a new CTS. We don't want a new CTS in this case. _pendingRequestsCts.Cancel(); _pendingRequestsCts.Dispose(); } base.Dispose(disposing); } #endregion #region Private Helpers private void SetOperationStarted() { // This method flags the HttpClient instances as "active". I.e. we executed at least one request (or are // in the process of doing so). This information is used to lock-down all property setters. Once a // Send/SendAsync operation started, no property can be changed. if (!_operationStarted) { _operationStarted = true; } } private void CheckDisposedOrStarted() { CheckDisposed(); if (_operationStarted) { throw new InvalidOperationException(SR.net_http_operation_started); } } private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().ToString()); } } private static void CheckRequestMessage(HttpRequestMessage request) { if (!request.MarkAsSent()) { throw new InvalidOperationException(SR.net_http_client_request_already_sent); } } private void PrepareRequestMessage(HttpRequestMessage request) { Uri requestUri = null; if ((request.RequestUri == null) && (_baseAddress == null)) { throw new InvalidOperationException(SR.net_http_client_invalid_requesturi); } if (request.RequestUri == null) { requestUri = _baseAddress; } else { // If the request Uri is an absolute Uri, just use it. Otherwise try to combine it with the base Uri. if (!request.RequestUri.IsAbsoluteUri) { if (_baseAddress == null) { throw new InvalidOperationException(SR.net_http_client_invalid_requesturi); } else { requestUri = new Uri(_baseAddress, request.RequestUri); } } } // We modified the original request Uri. Assign the new Uri to the request message. if (requestUri != null) { request.RequestUri = requestUri; } // Add default headers if (_defaultRequestHeaders != null) { request.Headers.AddHeaders(_defaultRequestHeaders); } } private static void CheckBaseAddress(Uri baseAddress, string parameterName) { if (baseAddress == null) { return; // It's OK to not have a base address specified. } if (!baseAddress.IsAbsoluteUri) { throw new ArgumentException(SR.net_http_client_absolute_baseaddress_required, parameterName); } if (!HttpUtilities.IsHttpUri(baseAddress)) { throw new ArgumentException(SR.net_http_client_http_baseaddress_required, parameterName); } } private Uri CreateUri(string uri) { if (string.IsNullOrEmpty(uri)) { return null; } return new Uri(uri, UriKind.RelativeOrAbsolute); } #endregion Private Helpers } }
// 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 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 GeneratedSmartCampaignSettingServiceClientTest { [Category("Autogenerated")][Test] public void GetSmartCampaignSettingRequestObject() { moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient> mockGrpcClient = new moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient>(moq::MockBehavior.Strict); GetSmartCampaignSettingRequest request = new GetSmartCampaignSettingRequest { ResourceNameAsSmartCampaignSettingName = gagvr::SmartCampaignSettingName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), }; gagvr::SmartCampaignSetting expectedResponse = new gagvr::SmartCampaignSetting { ResourceNameAsSmartCampaignSettingName = gagvr::SmartCampaignSettingName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), PhoneNumber = new gagvr::SmartCampaignSetting.Types.PhoneNumber(), FinalUrl = "final_url01c3df1e", BusinessName = "business_nameba1c7bb8", BusinessLocationId = 7879742372906296557L, AdvertisingLanguageCode = "advertising_language_coded5ffed87", }; mockGrpcClient.Setup(x => x.GetSmartCampaignSetting(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SmartCampaignSettingServiceClient client = new SmartCampaignSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::SmartCampaignSetting response = client.GetSmartCampaignSetting(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetSmartCampaignSettingRequestObjectAsync() { moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient> mockGrpcClient = new moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient>(moq::MockBehavior.Strict); GetSmartCampaignSettingRequest request = new GetSmartCampaignSettingRequest { ResourceNameAsSmartCampaignSettingName = gagvr::SmartCampaignSettingName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), }; gagvr::SmartCampaignSetting expectedResponse = new gagvr::SmartCampaignSetting { ResourceNameAsSmartCampaignSettingName = gagvr::SmartCampaignSettingName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), PhoneNumber = new gagvr::SmartCampaignSetting.Types.PhoneNumber(), FinalUrl = "final_url01c3df1e", BusinessName = "business_nameba1c7bb8", BusinessLocationId = 7879742372906296557L, AdvertisingLanguageCode = "advertising_language_coded5ffed87", }; mockGrpcClient.Setup(x => x.GetSmartCampaignSettingAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::SmartCampaignSetting>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SmartCampaignSettingServiceClient client = new SmartCampaignSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::SmartCampaignSetting responseCallSettings = await client.GetSmartCampaignSettingAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::SmartCampaignSetting responseCancellationToken = await client.GetSmartCampaignSettingAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetSmartCampaignSetting() { moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient> mockGrpcClient = new moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient>(moq::MockBehavior.Strict); GetSmartCampaignSettingRequest request = new GetSmartCampaignSettingRequest { ResourceNameAsSmartCampaignSettingName = gagvr::SmartCampaignSettingName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), }; gagvr::SmartCampaignSetting expectedResponse = new gagvr::SmartCampaignSetting { ResourceNameAsSmartCampaignSettingName = gagvr::SmartCampaignSettingName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), PhoneNumber = new gagvr::SmartCampaignSetting.Types.PhoneNumber(), FinalUrl = "final_url01c3df1e", BusinessName = "business_nameba1c7bb8", BusinessLocationId = 7879742372906296557L, AdvertisingLanguageCode = "advertising_language_coded5ffed87", }; mockGrpcClient.Setup(x => x.GetSmartCampaignSetting(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SmartCampaignSettingServiceClient client = new SmartCampaignSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::SmartCampaignSetting response = client.GetSmartCampaignSetting(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetSmartCampaignSettingAsync() { moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient> mockGrpcClient = new moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient>(moq::MockBehavior.Strict); GetSmartCampaignSettingRequest request = new GetSmartCampaignSettingRequest { ResourceNameAsSmartCampaignSettingName = gagvr::SmartCampaignSettingName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), }; gagvr::SmartCampaignSetting expectedResponse = new gagvr::SmartCampaignSetting { ResourceNameAsSmartCampaignSettingName = gagvr::SmartCampaignSettingName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), PhoneNumber = new gagvr::SmartCampaignSetting.Types.PhoneNumber(), FinalUrl = "final_url01c3df1e", BusinessName = "business_nameba1c7bb8", BusinessLocationId = 7879742372906296557L, AdvertisingLanguageCode = "advertising_language_coded5ffed87", }; mockGrpcClient.Setup(x => x.GetSmartCampaignSettingAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::SmartCampaignSetting>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SmartCampaignSettingServiceClient client = new SmartCampaignSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::SmartCampaignSetting responseCallSettings = await client.GetSmartCampaignSettingAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::SmartCampaignSetting responseCancellationToken = await client.GetSmartCampaignSettingAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetSmartCampaignSettingResourceNames() { moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient> mockGrpcClient = new moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient>(moq::MockBehavior.Strict); GetSmartCampaignSettingRequest request = new GetSmartCampaignSettingRequest { ResourceNameAsSmartCampaignSettingName = gagvr::SmartCampaignSettingName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), }; gagvr::SmartCampaignSetting expectedResponse = new gagvr::SmartCampaignSetting { ResourceNameAsSmartCampaignSettingName = gagvr::SmartCampaignSettingName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), PhoneNumber = new gagvr::SmartCampaignSetting.Types.PhoneNumber(), FinalUrl = "final_url01c3df1e", BusinessName = "business_nameba1c7bb8", BusinessLocationId = 7879742372906296557L, AdvertisingLanguageCode = "advertising_language_coded5ffed87", }; mockGrpcClient.Setup(x => x.GetSmartCampaignSetting(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SmartCampaignSettingServiceClient client = new SmartCampaignSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::SmartCampaignSetting response = client.GetSmartCampaignSetting(request.ResourceNameAsSmartCampaignSettingName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetSmartCampaignSettingResourceNamesAsync() { moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient> mockGrpcClient = new moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient>(moq::MockBehavior.Strict); GetSmartCampaignSettingRequest request = new GetSmartCampaignSettingRequest { ResourceNameAsSmartCampaignSettingName = gagvr::SmartCampaignSettingName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), }; gagvr::SmartCampaignSetting expectedResponse = new gagvr::SmartCampaignSetting { ResourceNameAsSmartCampaignSettingName = gagvr::SmartCampaignSettingName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), PhoneNumber = new gagvr::SmartCampaignSetting.Types.PhoneNumber(), FinalUrl = "final_url01c3df1e", BusinessName = "business_nameba1c7bb8", BusinessLocationId = 7879742372906296557L, AdvertisingLanguageCode = "advertising_language_coded5ffed87", }; mockGrpcClient.Setup(x => x.GetSmartCampaignSettingAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::SmartCampaignSetting>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SmartCampaignSettingServiceClient client = new SmartCampaignSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::SmartCampaignSetting responseCallSettings = await client.GetSmartCampaignSettingAsync(request.ResourceNameAsSmartCampaignSettingName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::SmartCampaignSetting responseCancellationToken = await client.GetSmartCampaignSettingAsync(request.ResourceNameAsSmartCampaignSettingName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateSmartCampaignSettingsRequestObject() { moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient> mockGrpcClient = new moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient>(moq::MockBehavior.Strict); MutateSmartCampaignSettingsRequest request = new MutateSmartCampaignSettingsRequest { CustomerId = "customer_id3b3724cb", Operations = { new SmartCampaignSettingOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateSmartCampaignSettingsResponse expectedResponse = new MutateSmartCampaignSettingsResponse { PartialFailureError = new gr::Status(), Results = { new MutateSmartCampaignSettingResult(), }, }; mockGrpcClient.Setup(x => x.MutateSmartCampaignSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SmartCampaignSettingServiceClient client = new SmartCampaignSettingServiceClientImpl(mockGrpcClient.Object, null); MutateSmartCampaignSettingsResponse response = client.MutateSmartCampaignSettings(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateSmartCampaignSettingsRequestObjectAsync() { moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient> mockGrpcClient = new moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient>(moq::MockBehavior.Strict); MutateSmartCampaignSettingsRequest request = new MutateSmartCampaignSettingsRequest { CustomerId = "customer_id3b3724cb", Operations = { new SmartCampaignSettingOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateSmartCampaignSettingsResponse expectedResponse = new MutateSmartCampaignSettingsResponse { PartialFailureError = new gr::Status(), Results = { new MutateSmartCampaignSettingResult(), }, }; mockGrpcClient.Setup(x => x.MutateSmartCampaignSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateSmartCampaignSettingsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SmartCampaignSettingServiceClient client = new SmartCampaignSettingServiceClientImpl(mockGrpcClient.Object, null); MutateSmartCampaignSettingsResponse responseCallSettings = await client.MutateSmartCampaignSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateSmartCampaignSettingsResponse responseCancellationToken = await client.MutateSmartCampaignSettingsAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateSmartCampaignSettings() { moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient> mockGrpcClient = new moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient>(moq::MockBehavior.Strict); MutateSmartCampaignSettingsRequest request = new MutateSmartCampaignSettingsRequest { CustomerId = "customer_id3b3724cb", Operations = { new SmartCampaignSettingOperation(), }, }; MutateSmartCampaignSettingsResponse expectedResponse = new MutateSmartCampaignSettingsResponse { PartialFailureError = new gr::Status(), Results = { new MutateSmartCampaignSettingResult(), }, }; mockGrpcClient.Setup(x => x.MutateSmartCampaignSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SmartCampaignSettingServiceClient client = new SmartCampaignSettingServiceClientImpl(mockGrpcClient.Object, null); MutateSmartCampaignSettingsResponse response = client.MutateSmartCampaignSettings(request.CustomerId, request.Operations); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateSmartCampaignSettingsAsync() { moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient> mockGrpcClient = new moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient>(moq::MockBehavior.Strict); MutateSmartCampaignSettingsRequest request = new MutateSmartCampaignSettingsRequest { CustomerId = "customer_id3b3724cb", Operations = { new SmartCampaignSettingOperation(), }, }; MutateSmartCampaignSettingsResponse expectedResponse = new MutateSmartCampaignSettingsResponse { PartialFailureError = new gr::Status(), Results = { new MutateSmartCampaignSettingResult(), }, }; mockGrpcClient.Setup(x => x.MutateSmartCampaignSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateSmartCampaignSettingsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SmartCampaignSettingServiceClient client = new SmartCampaignSettingServiceClientImpl(mockGrpcClient.Object, null); MutateSmartCampaignSettingsResponse responseCallSettings = await client.MutateSmartCampaignSettingsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateSmartCampaignSettingsResponse responseCancellationToken = await client.MutateSmartCampaignSettingsAsync(request.CustomerId, request.Operations, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the glacier-2012-06-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Glacier.Model { /// <summary> /// Describes an Amazon Glacier job. /// </summary> public partial class GlacierJobDescription { private ActionCode _action; private string _archiveId; private string _archiveSHA256TreeHash; private long? _archiveSizeInBytes; private bool? _completed; private DateTime? _completionDate; private DateTime? _creationDate; private InventoryRetrievalJobDescription _inventoryRetrievalParameters; private long? _inventorySizeInBytes; private string _jobDescription; private string _jobId; private string _retrievalByteRange; private string _sha256TreeHash; private string _snsTopic; private StatusCode _statusCode; private string _statusMessage; private string _vaultARN; /// <summary> /// Gets and sets the property Action. /// <para> /// The job type. It is either ArchiveRetrieval or InventoryRetrieval. /// </para> /// </summary> public ActionCode Action { get { return this._action; } set { this._action = value; } } // Check to see if Action property is set internal bool IsSetAction() { return this._action != null; } /// <summary> /// Gets and sets the property ArchiveId. /// <para> /// For an ArchiveRetrieval job, this is the archive ID requested for download. Otherwise, /// this field is null. /// </para> /// </summary> public string ArchiveId { get { return this._archiveId; } set { this._archiveId = value; } } // Check to see if ArchiveId property is set internal bool IsSetArchiveId() { return this._archiveId != null; } /// <summary> /// Gets and sets the property ArchiveSHA256TreeHash. /// <para> /// The SHA256 tree hash of the entire archive for an archive retrieval. For inventory /// retrieval jobs, this field is null. /// </para> /// </summary> public string ArchiveSHA256TreeHash { get { return this._archiveSHA256TreeHash; } set { this._archiveSHA256TreeHash = value; } } // Check to see if ArchiveSHA256TreeHash property is set internal bool IsSetArchiveSHA256TreeHash() { return this._archiveSHA256TreeHash != null; } /// <summary> /// Gets and sets the property ArchiveSizeInBytes. /// <para> /// For an ArchiveRetrieval job, this is the size in bytes of the archive being requested /// for download. For the InventoryRetrieval job, the value is null. /// </para> /// </summary> public long ArchiveSizeInBytes { get { return this._archiveSizeInBytes.GetValueOrDefault(); } set { this._archiveSizeInBytes = value; } } // Check to see if ArchiveSizeInBytes property is set internal bool IsSetArchiveSizeInBytes() { return this._archiveSizeInBytes.HasValue; } /// <summary> /// Gets and sets the property Completed. /// <para> /// The job status. When a job is completed, you get the job's output. /// </para> /// </summary> public bool Completed { get { return this._completed.GetValueOrDefault(); } set { this._completed = value; } } // Check to see if Completed property is set internal bool IsSetCompleted() { return this._completed.HasValue; } /// <summary> /// Gets and sets the property CompletionDate. /// <para> /// The UTC time that the archive retrieval request completed. While the job is in progress, /// the value will be null. /// </para> /// </summary> public DateTime CompletionDate { get { return this._completionDate.GetValueOrDefault(); } set { this._completionDate = value; } } // Check to see if CompletionDate property is set internal bool IsSetCompletionDate() { return this._completionDate.HasValue; } /// <summary> /// Gets and sets the property CreationDate. /// <para> /// The UTC date when the job was created. A string representation of ISO 8601 date format, /// for example, "2012-03-20T17:03:43.221Z". /// </para> /// </summary> public DateTime CreationDate { get { return this._creationDate.GetValueOrDefault(); } set { this._creationDate = value; } } // Check to see if CreationDate property is set internal bool IsSetCreationDate() { return this._creationDate.HasValue; } /// <summary> /// Gets and sets the property InventoryRetrievalParameters. /// <para> /// Parameters used for range inventory retrieval. /// </para> /// </summary> public InventoryRetrievalJobDescription InventoryRetrievalParameters { get { return this._inventoryRetrievalParameters; } set { this._inventoryRetrievalParameters = value; } } // Check to see if InventoryRetrievalParameters property is set internal bool IsSetInventoryRetrievalParameters() { return this._inventoryRetrievalParameters != null; } /// <summary> /// Gets and sets the property InventorySizeInBytes. /// <para> /// For an InventoryRetrieval job, this is the size in bytes of the inventory requested /// for download. For the ArchiveRetrieval job, the value is null. /// </para> /// </summary> public long InventorySizeInBytes { get { return this._inventorySizeInBytes.GetValueOrDefault(); } set { this._inventorySizeInBytes = value; } } // Check to see if InventorySizeInBytes property is set internal bool IsSetInventorySizeInBytes() { return this._inventorySizeInBytes.HasValue; } /// <summary> /// Gets and sets the property JobDescription. /// <para> /// The job description you provided when you initiated the job. /// </para> /// </summary> public string JobDescription { get { return this._jobDescription; } set { this._jobDescription = value; } } // Check to see if JobDescription property is set internal bool IsSetJobDescription() { return this._jobDescription != null; } /// <summary> /// Gets and sets the property JobId. /// <para> /// An opaque string that identifies an Amazon Glacier job. /// </para> /// </summary> public string JobId { get { return this._jobId; } set { this._jobId = value; } } // Check to see if JobId property is set internal bool IsSetJobId() { return this._jobId != null; } /// <summary> /// Gets and sets the property RetrievalByteRange. /// <para> /// The retrieved byte range for archive retrieval jobs in the form "<i>StartByteValue</i>-<i>EndByteValue</i>" /// If no range was specified in the archive retrieval, then the whole archive is retrieved /// and <i>StartByteValue</i> equals 0 and <i>EndByteValue</i> equals the size of the /// archive minus 1. For inventory retrieval jobs this field is null. /// </para> /// </summary> public string RetrievalByteRange { get { return this._retrievalByteRange; } set { this._retrievalByteRange = value; } } // Check to see if RetrievalByteRange property is set internal bool IsSetRetrievalByteRange() { return this._retrievalByteRange != null; } /// <summary> /// Gets and sets the property SHA256TreeHash. /// <para> /// For an ArchiveRetrieval job, it is the checksum of the archive. Otherwise, the value /// is null. /// </para> /// /// <para> /// The SHA256 tree hash value for the requested range of an archive. If the Initiate /// a Job request for an archive specified a tree-hash aligned range, then this field /// returns a value. /// </para> /// /// <para> /// For the specific case when the whole archive is retrieved, this value is the same /// as the ArchiveSHA256TreeHash value. /// </para> /// /// <para> /// This field is null in the following situations: <ul> <li> /// <para> /// Archive retrieval jobs that specify a range that is not tree-hash aligned. /// </para> /// </li> </ul> <ul> <li> /// <para> /// Archival jobs that specify a range that is equal to the whole archive and the job /// status is InProgress. /// </para> /// </li> </ul> <ul> <li> /// <para> /// Inventory jobs. /// </para> /// </li> </ul> /// </para> /// </summary> public string SHA256TreeHash { get { return this._sha256TreeHash; } set { this._sha256TreeHash = value; } } // Check to see if SHA256TreeHash property is set internal bool IsSetSHA256TreeHash() { return this._sha256TreeHash != null; } /// <summary> /// Gets and sets the property SNSTopic. /// <para> /// An Amazon Simple Notification Service (Amazon SNS) topic that receives notification. /// </para> /// </summary> public string SNSTopic { get { return this._snsTopic; } set { this._snsTopic = value; } } // Check to see if SNSTopic property is set internal bool IsSetSNSTopic() { return this._snsTopic != null; } /// <summary> /// Gets and sets the property StatusCode. /// <para> /// The status code can be InProgress, Succeeded, or Failed, and indicates the status /// of the job. /// </para> /// </summary> public StatusCode StatusCode { get { return this._statusCode; } set { this._statusCode = value; } } // Check to see if StatusCode property is set internal bool IsSetStatusCode() { return this._statusCode != null; } /// <summary> /// Gets and sets the property StatusMessage. /// <para> /// A friendly message that describes the job status. /// </para> /// </summary> public string StatusMessage { get { return this._statusMessage; } set { this._statusMessage = value; } } // Check to see if StatusMessage property is set internal bool IsSetStatusMessage() { return this._statusMessage != null; } /// <summary> /// Gets and sets the property VaultARN. /// <para> /// The Amazon Resource Name (ARN) of the vault from which the archive retrieval was requested. /// </para> /// </summary> public string VaultARN { get { return this._vaultARN; } set { this._vaultARN = value; } } // Check to see if VaultARN property is set internal bool IsSetVaultARN() { return this._vaultARN != null; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Ms.Converter.Areas.HelpPage.ModelDescriptions; using Ms.Converter.Areas.HelpPage.Models; namespace Ms.Converter.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using UnityEngine; using UnityEngine.UI; using System; public class DemoInputManager : MonoBehaviour { // Cardboard / Daydream switching does not apply to pre-native integration versions // of Unity, or platforms other than Android, since those are Cardboard-only. #if UNITY_HAS_GOOGLEVR && UNITY_ANDROID private const string MESSAGE_CANVAS_NAME = "MessageCanvas"; private const string MESSAGE_TEXT_NAME = "MessageText"; private const string LASER_GAMEOBJECT_NAME = "Laser"; private const string CONTROLLER_CONNECTING_MESSAGE = "Controller connecting..."; private const string CONTROLLER_DISCONNECTED_MESSAGE = "Controller disconnected"; private const string CONTROLLER_SCANNING_MESSAGE = "Controller scanning..."; private const string EMPTY_VR_SDK_WARNING_MESSAGE = "Please enable a VR SDK in Player Settings > Virtual Reality Supported\n"; // Java class, method, and field constants. private const int ANDROID_MIN_DAYDREAM_API = 24; private const string FIELD_SDK_INT = "SDK_INT"; private const string PACKAGE_BUILD_VERSION = "android.os.Build$VERSION"; private const string PACKAGE_DAYDREAM_API_CLASS = "com.google.vr.ndk.base.DaydreamApi"; private const string PACKAGE_UNITY_PLAYER = "com.unity3d.player.UnityPlayer"; private const string METHOD_CURRENT_ACTIVITY = "currentActivity"; private const string METHOD_IS_DAYDREAM_READY = "isDaydreamReadyPlatform"; private bool isDaydream = false; public static string CARDBOARD_DEVICE_NAME = "cardboard"; public static string DAYDREAM_DEVICE_NAME = "daydream"; [Tooltip("Reference to GvrControllerMain")] public GameObject controllerMain; public static string CONTROLLER_MAIN_PROP_NAME = "controllerMain"; [Tooltip("Reference to GvrControllerPointer")] public GameObject controllerPointer; public static string CONTROLLER_POINTER_PROP_NAME = "controllerPointer"; [Tooltip("Reference to GvrReticlePointer")] public GameObject reticlePointer; public static string RETICLE_POINTER_PROP_NAME = "reticlePointer"; public GameObject messageCanvas; public Text messageText; #if UNITY_EDITOR public enum EmulatedPlatformType { Daydream, Cardboard } // Cardboard by default if there is no native integration. [Tooltip("Emulated GVR Platform")] public EmulatedPlatformType gvrEmulatedPlatformType = EmulatedPlatformType.Daydream; public static string EMULATED_PLATFORM_PROP_NAME = "gvrEmulatedPlatformType"; #endif // UNITY_EDITOR void Start() { if (messageCanvas == null) { messageCanvas = transform.Find(MESSAGE_CANVAS_NAME).gameObject; if (messageCanvas != null) { messageText = messageCanvas.transform.Find(MESSAGE_TEXT_NAME).GetComponent<Text>(); } } #if UNITY_EDITOR if (playerSettingsHasDaydream() || playerSettingsHasCardboard()) { // The list is populated with valid VR SDK(s), pick the first one. gvrEmulatedPlatformType = (UnityEngine.VR.VRSettings.supportedDevices[0] == DAYDREAM_DEVICE_NAME) ? EmulatedPlatformType.Daydream : EmulatedPlatformType.Cardboard; } isDaydream = (gvrEmulatedPlatformType == EmulatedPlatformType.Daydream); #else // First loaded device in Player Settings. string vrDeviceName = UnityEngine.VR.VRSettings.loadedDeviceName; if (vrDeviceName != CARDBOARD_DEVICE_NAME && vrDeviceName != DAYDREAM_DEVICE_NAME) { Debug.Log(string.Format("Loaded device was {0} must be one of {1} or {2}", vrDeviceName, DAYDREAM_DEVICE_NAME, CARDBOARD_DEVICE_NAME)); return; } // On a non-Daydream ready phone, fall back to Cardboard if it's present in the // list of enabled VR SDKs. if (!IsDeviceDaydreamReady() && playerSettingsHasCardboard()) { vrDeviceName = CARDBOARD_DEVICE_NAME; } isDaydream = (vrDeviceName == DAYDREAM_DEVICE_NAME); #endif // UNITY_EDITOR SetVRInputMechanism(); } // Runtime switching enabled only in-editor. void Update() { UpdateStatusMessage(); #if UNITY_EDITOR UpdateEmulatedPlatformIfPlayerSettingsChanged(); if ((isDaydream && gvrEmulatedPlatformType == EmulatedPlatformType.Daydream) || (!isDaydream && gvrEmulatedPlatformType == EmulatedPlatformType.Cardboard)) { return; } isDaydream = (gvrEmulatedPlatformType == EmulatedPlatformType.Daydream); SetVRInputMechanism(); #endif // UNITY_EDITOR } public static bool playerSettingsHasDaydream() { string[] playerSettingsVrSdks = UnityEngine.VR.VRSettings.supportedDevices; return Array.Exists<string>(playerSettingsVrSdks, element => element.Equals(DemoInputManager.DAYDREAM_DEVICE_NAME)); } public static bool playerSettingsHasCardboard() { string[] playerSettingsVrSdks = UnityEngine.VR.VRSettings.supportedDevices; return Array.Exists<string>(playerSettingsVrSdks, element => element.Equals(DemoInputManager.CARDBOARD_DEVICE_NAME)); } #if UNITY_EDITOR private void UpdateEmulatedPlatformIfPlayerSettingsChanged() { if (!playerSettingsHasDaydream() && !playerSettingsHasCardboard()) { return; } // Player Settings > VR SDK list may have changed at runtime. The emulated platform // may not have been manually updated if that's the case. if (gvrEmulatedPlatformType == EmulatedPlatformType.Daydream && !playerSettingsHasDaydream()) { gvrEmulatedPlatformType = EmulatedPlatformType.Cardboard; } else if (gvrEmulatedPlatformType == EmulatedPlatformType.Cardboard && !playerSettingsHasCardboard()) { gvrEmulatedPlatformType = EmulatedPlatformType.Daydream; } } #endif // UNITY_EDITOR #if !UNITY_EDITOR // Running on an Android device. private static bool IsDeviceDaydreamReady() { // Check API level. using (var version = new AndroidJavaClass(PACKAGE_BUILD_VERSION)) { if (version.GetStatic<int>(FIELD_SDK_INT) < ANDROID_MIN_DAYDREAM_API) { return false; } } // API level > 24, check whether the device is Daydream-ready.. AndroidJavaObject androidActivity = null; try { using (AndroidJavaObject unityPlayer = new AndroidJavaClass(PACKAGE_UNITY_PLAYER)) { androidActivity = unityPlayer.GetStatic<AndroidJavaObject>(METHOD_CURRENT_ACTIVITY); } } catch (AndroidJavaException e) { Debug.LogError("Exception while connecting to the Activity: " + e); return false; } AndroidJavaClass daydreamApiClass = new AndroidJavaClass(PACKAGE_DAYDREAM_API_CLASS); if (daydreamApiClass == null || androidActivity == null) { return false; } return daydreamApiClass.CallStatic<bool>(METHOD_IS_DAYDREAM_READY, androidActivity); } #endif // !UNITY_EDITOR private void UpdateStatusMessage() { if (messageText == null || messageCanvas == null) { return; } bool isVrSdkListEmpty = !playerSettingsHasCardboard() && !playerSettingsHasDaydream(); if (!isDaydream) { if (messageCanvas.activeSelf) { messageText.text = EMPTY_VR_SDK_WARNING_MESSAGE; messageCanvas.SetActive(false || isVrSdkListEmpty); } return; } string vrSdkWarningMessage = isVrSdkListEmpty ? EMPTY_VR_SDK_WARNING_MESSAGE : ""; string controllerMessage = ""; GvrPointerGraphicRaycaster graphicRaycaster = messageCanvas.GetComponent<GvrPointerGraphicRaycaster>(); // This is an example of how to process the controller's state to display a status message. switch (GvrController.State) { case GvrConnectionState.Connected: break; case GvrConnectionState.Disconnected: controllerMessage = CONTROLLER_DISCONNECTED_MESSAGE; messageText.color = Color.white; break; case GvrConnectionState.Scanning: controllerMessage = CONTROLLER_SCANNING_MESSAGE; messageText.color = Color.cyan; break; case GvrConnectionState.Connecting: controllerMessage = CONTROLLER_CONNECTING_MESSAGE; messageText.color = Color.yellow; break; case GvrConnectionState.Error: controllerMessage = "ERROR: " + GvrController.ErrorDetails; messageText.color = Color.red; break; default: // Shouldn't happen. Debug.LogError("Invalid controller state: " + GvrController.State); break; } messageText.text = string.Format("{0}{1}", vrSdkWarningMessage, controllerMessage); if (graphicRaycaster != null) { graphicRaycaster.enabled = !isVrSdkListEmpty || GvrController.State != GvrConnectionState.Connected; } messageCanvas.SetActive(isVrSdkListEmpty || (GvrController.State != GvrConnectionState.Connected)); } private void SetVRInputMechanism() { SetGazeInputActive(!isDaydream); SetControllerInputActive(isDaydream); } private void SetGazeInputActive(bool active) { if (reticlePointer == null) { return; } reticlePointer.SetActive(active); // Update the pointer type only if this is currently activated. if (!active) { return; } GvrBasePointer pointer = reticlePointer.GetComponent<GvrBasePointer>(); if (pointer != null) { GvrPointerManager.Pointer = pointer; } } private void SetControllerInputActive(bool active) { if (controllerMain != null) { controllerMain.SetActive(active); } if (controllerPointer == null) { return; } controllerPointer.SetActive(active); // Update the pointer type only if this is currently activated. if (!active) { return; } GvrBasePointer pointer = controllerPointer.GetComponentInChildren<GvrBasePointer>(); if (pointer != null) { GvrPointerManager.Pointer = pointer; } } #endif // UNITY_HAS_GOOGLEVR && UNITY_ANDROID }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Orleans; using Orleans.Concurrency; using Orleans.Runtime; using UnitTests.GrainInterfaces; namespace UnitTests.Grains { internal class StressTestGrain : Grain, IStressTestGrain { private string label; private Logger logger; public override Task OnActivateAsync() { if (this.GetPrimaryKeyLong() == -2) throw new ArgumentException("Primary key cannot be -2 for this test case"); logger = base.GetLogger("StressTestGrain " + base.RuntimeIdentity); label = this.GetPrimaryKeyLong().ToString(); logger.Info("OnActivateAsync"); return TaskDone.Done; } public Task<string> GetLabel() { return Task.FromResult(label); } public Task SetLabel(string label) { this.label = label; //logger.Info("SetLabel {0} received", label); return TaskDone.Done; } public Task<IStressTestGrain> GetGrainReference() { return Task.FromResult(this.AsReference<IStressTestGrain>()); } public Task PingOthers(long[] others) { List<Task> promises = new List<Task>(); foreach (long key in others) { IStressTestGrain g1 = GrainFactory.GetGrain<IStressTestGrain>(key); Task promise = g1.GetLabel(); promises.Add(promise); } return Task.WhenAll(promises); } public Task<List<Tuple<GrainId, int, List<Tuple<SiloAddress, ActivationId>>>>> LookUpMany( SiloAddress destination, List<Tuple<GrainId, int>> grainAndETagList, int retries = 0) { var list = new List<Tuple<GrainId, int, List<Tuple<SiloAddress, ActivationId>>>>(); foreach (Tuple<GrainId, int> tuple in grainAndETagList) { GrainId id = tuple.Item1; var reply = new List<Tuple<SiloAddress, ActivationId>>(); for (int i = 0; i < 10; i++) { reply.Add(new Tuple<SiloAddress, ActivationId>(SiloAddress.NewLocalAddress(0), ActivationId.NewId())); } list.Add(new Tuple<GrainId, int, List<Tuple<SiloAddress, ActivationId>>>(id, 3, reply)); } return Task.FromResult(list); } public Task<byte[]> Echo(byte[] data) { return Task.FromResult(data); } public Task Ping(byte[] data) { return TaskDone.Done; } public async Task PingWithDelay(byte[] data, TimeSpan delay) { await Task.Delay(delay); } public Task Send(byte[] data) { return TaskDone.Done; } public Task DeactivateSelf() { DeactivateOnIdle(); return TaskDone.Done; } } [Reentrant] internal class ReentrantStressTestGrain : Grain, IReentrantStressTestGrain { private string label; private Logger logger; public override Task OnActivateAsync() { label = this.GetPrimaryKeyLong().ToString(); logger = base.GetLogger("ReentrantStressTestGrain " + base.Data.Address.ToString()); logger.Info("OnActivateAsync"); return TaskDone.Done; } public Task<string> GetRuntimeInstanceId() { return Task.FromResult(RuntimeIdentity); } public Task<byte[]> Echo(byte[] data) { return Task.FromResult(data); } public Task Ping(byte[] data) { return TaskDone.Done; } public async Task PingWithDelay(byte[] data, TimeSpan delay) { await Task.Delay(delay); } public Task PingMutableArray(byte[] data, long nextGrain, bool nextGrainIsRemote) { if (nextGrain > 0) { if (nextGrainIsRemote) { return GrainFactory.GetGrain<IReentrantStressTestGrain>(nextGrain).PingMutableArray(data, -1, false); } return GrainFactory.GetGrain<IReentrantLocalStressTestGrain>(nextGrain) .PingMutableArray(data, -1, false); } return TaskDone.Done; } public Task PingImmutableArray(Immutable<byte[]> data, long nextGrain, bool nextGrainIsRemote) { if (nextGrain > 0) { if (nextGrainIsRemote) { return GrainFactory.GetGrain<IReentrantStressTestGrain>(nextGrain) .PingImmutableArray(data, -1, false); } return GrainFactory.GetGrain<IReentrantLocalStressTestGrain>(nextGrain) .PingImmutableArray(data, -1, false); } return TaskDone.Done; } public Task PingMutableDictionary(Dictionary<int, string> data, long nextGrain, bool nextGrainIsRemote) { if (nextGrain > 0) { if (nextGrainIsRemote) { return GrainFactory.GetGrain<IReentrantStressTestGrain>(nextGrain) .PingMutableDictionary(data, -1, false); } return GrainFactory.GetGrain<IReentrantLocalStressTestGrain>(nextGrain) .PingMutableDictionary(data, -1, false); } return TaskDone.Done; } public Task PingImmutableDictionary(Immutable<Dictionary<int, string>> data, long nextGrain, bool nextGrainIsRemote) { if (nextGrain > 0) { if (nextGrainIsRemote) { return GrainFactory.GetGrain<IReentrantStressTestGrain>(nextGrain) .PingImmutableDictionary(data, -1, false); } return GrainFactory.GetGrain<IReentrantLocalStressTestGrain>(nextGrain) .PingImmutableDictionary(data, -1, false); } return TaskDone.Done; } public async Task InterleavingConsistencyTest(int numItems) { TimeSpan delay = TimeSpan.FromMilliseconds(1); SafeRandom random = new SafeRandom(); List<Task> getFileMetadataPromises = new List<Task>(numItems*2); Dictionary<int, string> fileMetadatas = new Dictionary<int, string>(numItems*2); for (int i = 0; i < numItems; i++) { int capture = i; Func<Task> func = ( async () => { await Task.Delay(random.NextTimeSpan(delay)); int fileMetadata = capture; if ((fileMetadata%2) == 0) { fileMetadatas.Add(fileMetadata, fileMetadata.ToString()); } }); getFileMetadataPromises.Add(func()); } await Task.WhenAll(getFileMetadataPromises.ToArray()); List<Task> tagPromises = new List<Task>(fileMetadatas.Count); foreach (KeyValuePair<int, string> keyValuePair in fileMetadatas) { int fileId = keyValuePair.Key; Func<Task> func = (async () => { await Task.Delay(random.NextTimeSpan(delay)); string fileMetadata = fileMetadatas[fileId]; }); tagPromises.Add(func()); } await Task.WhenAll(tagPromises); // sort the fileMetadatas according to fileIds. List<string> results = new List<string>(fileMetadatas.Count); for (int i = 0; i < numItems; i++) { string metadata; if (fileMetadatas.TryGetValue(i, out metadata)) { results.Add(metadata); } } if (numItems != results.Count) { //throw new OrleansException(String.Format("numItems != results.Count, {0} != {1}", numItems, results.Count)); } } } [Reentrant] [StatelessWorker] public class ReentrantLocalStressTestGrain : Grain, IReentrantLocalStressTestGrain { private string label; private Logger logger; public override Task OnActivateAsync() { label = this.GetPrimaryKeyLong().ToString(); logger = base.GetLogger("ReentrantLocalStressTestGrain " + base.Data.Address.ToString()); logger.Info("OnActivateAsync"); return TaskDone.Done; } public Task<byte[]> Echo(byte[] data) { return Task.FromResult(data); } public Task<string> GetRuntimeInstanceId() { return Task.FromResult(RuntimeIdentity); } public Task Ping(byte[] data) { return TaskDone.Done; } public async Task PingWithDelay(byte[] data, TimeSpan delay) { await Task.Delay(delay); } public Task PingMutableArray(byte[] data, long nextGrain, bool nextGrainIsRemote) { if (nextGrain > 0) { if (nextGrainIsRemote) { return GrainFactory.GetGrain<IReentrantStressTestGrain>(nextGrain).PingMutableArray(data, -1, false); } return GrainFactory.GetGrain<IReentrantLocalStressTestGrain>(nextGrain) .PingMutableArray(data, -1, false); } return TaskDone.Done; } public Task PingImmutableArray(Immutable<byte[]> data, long nextGrain, bool nextGrainIsRemote) { if (nextGrain > 0) { if (nextGrainIsRemote) { return GrainFactory.GetGrain<IReentrantStressTestGrain>(nextGrain) .PingImmutableArray(data, -1, false); } return GrainFactory.GetGrain<IReentrantLocalStressTestGrain>(nextGrain) .PingImmutableArray(data, -1, false); } return TaskDone.Done; } public Task PingMutableDictionary(Dictionary<int, string> data, long nextGrain, bool nextGrainIsRemote) { if (nextGrain > 0) { if (nextGrainIsRemote) { return GrainFactory.GetGrain<IReentrantStressTestGrain>(nextGrain) .PingMutableDictionary(data, -1, false); } return GrainFactory.GetGrain<IReentrantLocalStressTestGrain>(nextGrain) .PingMutableDictionary(data, -1, false); } return TaskDone.Done; } public Task PingImmutableDictionary(Immutable<Dictionary<int, string>> data, long nextGrain, bool nextGrainIsRemote) { if (nextGrain > 0) { if (nextGrainIsRemote) { return GrainFactory.GetGrain<IReentrantStressTestGrain>(nextGrain) .PingImmutableDictionary(data, -1, false); } return GrainFactory.GetGrain<IReentrantLocalStressTestGrain>(nextGrain) .PingImmutableDictionary(data, -1, false); } return TaskDone.Done; } } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace Core.UserProfiles.Sync { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// This method is deprecated because the autohosted option is no longer available. /// </summary> [ObsoleteAttribute("This method is deprecated because the autohosted option is no longer available.", true)] public string GetDatabaseConnectionString() { throw new NotSupportedException("This method is deprecated because the autohosted option is no longer available."); } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; bool contextTokenExpired = false; try { if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } } catch (SecurityTokenExpiredException) { contextTokenExpired = true; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]) && !contextTokenExpired) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
/*************************************************************************************************************************************** * Copyright (C) 2001-2012 LearnLift USA * * Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, [email protected] * * * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************************************************************************/ using System; using System.Collections.Generic; using System.IO; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using MLifter.BusinessLayer; using MLifter.DAL.Interfaces; namespace MLifterTest.BusinessLayer { internal static class TestInfrastructure { private static Random random = new Random((int)DateTime.Now.Ticks); /// <summary> /// Gets the loopcount. /// </summary> /// <value>The loopcount.</value> /// <remarks>Documented by Dev10, 2008-07-30</remarks> public static int LoopCount { get { return 100; } } /// <summary> /// Gets the random. /// </summary> /// <value>The random.</value> /// <remarks>Documented by Dev10, 2008-07-30</remarks> public static Random Random { get { return random; } } /// <summary> /// Gets a value indicating whether [random bool]. /// </summary> /// <value><c>true</c> if [random bool]; otherwise, <c>false</c>.</value> /// <remarks>Documented by Dev03, 2008-09-12</remarks> public static bool RandomBool { get { return (random.Next(2) == 0); } } /// <summary> /// Mies the class cleanup. /// </summary> /// <remarks>Documented by Dev02, 2008-09-29</remarks> public static void MyClassCleanup() { MLifterTest.DAL.TestInfrastructure.cleanupQueue.DoCleanup(); } /// <summary> /// Gets the connection. /// </summary> /// <param name="testContext">The test context.</param> /// <returns></returns> /// <remarks>Documented by Dev02, 2008-09-10</remarks> public static Dictionary GetConnection(TestContext testContext) { return GetConnection(testContext, false); } /// <summary> /// Gets the connection. /// </summary> /// <param name="testContext">The test context.</param> /// <param name="standAlone">if set to <c>true</c> a stand alone user will be created.</param> /// <returns></returns> /// <remarks>Documented by Dev02, 2008-09-10</remarks> public static Dictionary GetConnection(TestContext testContext, bool standAlone) { MLifterTest.DAL.LMConnectionParameter param = new MLifterTest.DAL.LMConnectionParameter(testContext); param.Callback = MLifterTest.DAL.TestInfrastructure.GetAdminUser; param.ConnectionType = string.Empty; param.IsProtected = false; param.LearningModuleId = -1; param.Password = string.Empty; param.RepositoryName = string.Empty; param.standAlone = standAlone; IDictionary targetDAL = MLifterTest.DAL.TestInfrastructure.GetLMConnection(param); Dictionary target = new Dictionary(targetDAL, null); return target; } /// <summary> /// Gets a persistent LM connection according choosen connectionType e.g. file or pgsql. /// </summary> /// <param name="testContext">The test context.</param> /// <param name="connectionType">Type of the connection.</param> /// <returns></returns> /// <remarks>Documented by Dev10, 2008-26-09</remarks> public static Dictionary GetPersistentLMConnection(TestContext testContext, string connectionType) { return GetPersistentLMConnection(testContext, connectionType, false); } /// <summary> /// Gets a persistent LM connection according chosen connectionType e.g. file or pgsql. /// </summary> /// <param name="testContext">The test context.</param> /// <param name="connectionType">Type of the connection.</param> /// <param name="standAlone">if set to <c>true</c> a stand alone user will be created.</param> /// <returns></returns> /// <remarks>Documented by Dev10, 2008-26-09</remarks> public static Dictionary GetPersistentLMConnection(TestContext testContext, string connectionType, bool standAlone) { MLifterTest.DAL.LMConnectionParameter param = new MLifterTest.DAL.LMConnectionParameter(testContext); param.Callback = MLifterTest.DAL.TestInfrastructure.GetAdminUser; param.ConnectionType = connectionType; param.IsProtected = false; param.LearningModuleId = -1; param.Password = string.Empty; param.RepositoryName = string.Empty; param.standAlone = standAlone; IDictionary targetDAL = MLifterTest.DAL.TestInfrastructure.GetLMConnection(param); Dictionary target = new Dictionary(targetDAL, null); return target; } /// <summary> /// Gets the connection string. /// </summary> /// <param name="testContex">The test contex.</param> /// <returns></returns> /// <remarks>Documented by Dev03, 2009-01-30</remarks> public static ConnectionStringStruct GetConnectionString(TestContext testContex) { using (Dictionary dictionary = TestInfrastructure.GetConnection(testContex)) { dictionary.Save(); return dictionary.DictionaryDAL.Parent.CurrentUser.ConnectionString; } } /// <summary> /// Gets the connection string for LM with dummy data. /// </summary> /// <param name="testContex">The test contex.</param> /// <returns></returns> /// <remarks>Documented by Dev03, 2009-01-30</remarks> public static ConnectionStringStruct GetConnectionStringWithDummyData(TestContext testContext) { using (Dictionary dictionary = TestInfrastructure.GetConnection(testContext)) { DAL.ICardsTests.FillDummyDic(dictionary.DictionaryDAL); dictionary.Save(); MLifter.DAL.Log.CloseUserSession(dictionary.DictionaryDAL.Parent); return dictionary.DictionaryDAL.Parent.CurrentUser.ConnectionString; } } /// <summary> /// Determines whether the specified test context is active. /// </summary> /// <param name="testContext">The test context.</param> /// <returns> /// <c>true</c> if the specified test context is active; otherwise, <c>false</c>. /// </returns> /// <remarks>Documented by Dev02, 2008-09-10</remarks> public static bool IsActive(TestContext testContext) { return MLifterTest.DAL.TestInfrastructure.IsActive(testContext); } /// <summary> /// Get the Connection Type /// </summary> /// <param name="testContext">The test context.</param> /// <returns></returns> /// <remarks>Documented by Dev10, 2008-26-09</remarks> public static string ConnectionType(TestContext testContext) { return MLifterTest.DAL.TestInfrastructure.ConnectionType(testContext); } /// <summary> /// Gets the test audio. /// </summary> /// <returns></returns> /// <remarks>Documented by Dev03, 2008-08-20</remarks> public static string GetTestAudio() { return MLifterTest.DAL.TestInfrastructure.GetTestAudio(); } /// <summary> /// Gets the test image. /// </summary> /// <returns></returns> /// <remarks>Documented by Dev03, 2008-08-20</remarks> public static string GetTestImage() { return MLifterTest.DAL.TestInfrastructure.GetTestImage(); } /// <summary> /// Gets the test video. /// </summary> /// <returns></returns> /// <remarks>Documented by Dev03, 2008-08-20</remarks> public static string GetTestVideo() { return MLifterTest.DAL.TestInfrastructure.GetTestVideo(); } public static void FillDummyDic(Dictionary dictionary) { List<int> chapters = new List<int>(); for (int k = 0; k < 10; k++) { int chapterId = dictionary.Chapters.AddChapter("Chapter " + Convert.ToString(k + 1), "Chapter Description" + Convert.ToString(k + 1)); chapters.Add(chapterId); dictionary.QueryChapters.Add(chapterId); } for (int i = 0; i < TestInfrastructure.LoopCount; i++) { bool hasQImage = TestInfrastructure.RandomBool, hasAImage = TestInfrastructure.RandomBool; bool hasQAudio = TestInfrastructure.RandomBool, hasAAudio = TestInfrastructure.RandomBool; bool hasQEAudio = TestInfrastructure.RandomBool, hasAEAudio = TestInfrastructure.RandomBool; bool hasQVideo = TestInfrastructure.RandomBool, hasAVideo = TestInfrastructure.RandomBool; bool hasQExample = TestInfrastructure.RandomBool, hasAExample = TestInfrastructure.RandomBool; int cardId = dictionary.Cards.AddCard("question " + i, "answer " + i, (hasQExample) ? "question example " + i : String.Empty, (hasAExample) ? "answer example " + i : String.Empty, String.Empty, String.Empty, chapters[TestInfrastructure.Random.Next(0, chapters.Count)]); if (hasQImage) dictionary.Cards.AddMedia(cardId, TestInfrastructure.GetTestImage(), EMedia.Image, Side.Question, true, true, false); if (hasAImage) dictionary.Cards.AddMedia(cardId, TestInfrastructure.GetTestImage(), EMedia.Image, Side.Answer, true, true, false); if (hasQAudio) dictionary.Cards.AddMedia(cardId, TestInfrastructure.GetTestAudio(), EMedia.Audio, Side.Question, true, true, false); if (hasAAudio) dictionary.Cards.AddMedia(cardId, TestInfrastructure.GetTestAudio(), EMedia.Audio, Side.Answer, true, true, false); if (hasQEAudio) dictionary.Cards.AddMedia(cardId, TestInfrastructure.GetTestAudio(), EMedia.Audio, Side.Question, true, false, true); if (hasAEAudio) dictionary.Cards.AddMedia(cardId, TestInfrastructure.GetTestAudio(), EMedia.Audio, Side.Answer, true, false, true); if (hasQVideo) dictionary.Cards.AddMedia(cardId, TestInfrastructure.GetTestVideo(), EMedia.Video, Side.Question, true, true, false); if (hasAVideo) dictionary.Cards.AddMedia(cardId, TestInfrastructure.GetTestVideo(), EMedia.Video, Side.Answer, true, true, false); } } } }
using System; using System.IO; using System.Text; using ValveResourceFormat.Blocks; using ValveResourceFormat.Utils; namespace ValveResourceFormat.ResourceTypes { public class Sound : ResourceData { public enum AudioFileType { AAC = 0, WAV = 1, MP3 = 2, } public enum AudioFormatV4 { PCM16 = 0, PCM8 = 1, MP3 = 2, ADPCM = 3, } // https://github.com/naudio/NAudio/blob/fb35ce8367f30b8bc5ea84e7d2529e172cf4c381/NAudio.Core/Wave/WaveFormats/WaveFormatEncoding.cs public enum WaveAudioFormat { Unknown = 0, PCM = 1, ADPCM = 2, } /// <summary> /// Gets the audio file type. /// </summary> /// <value>The file type.</value> public AudioFileType SoundType { get; private set; } /// <summary> /// Gets the samples per second. /// </summary> /// <value>The sample rate.</value> public uint SampleRate { get; private set; } /// <summary> /// Gets the bit size. /// </summary> /// <value>The bit size.</value> public uint Bits { get; private set; } /// <summary> /// Gets the number of channels. 1 for mono, 2 for stereo. /// </summary> /// <value>The number of channels.</value> public uint Channels { get; private set; } /// <summary> /// Gets the bitstream encoding format. /// </summary> /// <value>The audio format.</value> public WaveAudioFormat AudioFormat { get; private set; } public uint SampleSize { get; private set; } public uint SampleCount { get; private set; } public int LoopStart { get; private set; } public int LoopEnd { get; private set; } public float Duration { get; private set; } public uint StreamingDataSize { get; private set; } private BinaryReader Reader; public override void Read(BinaryReader reader, Resource resource) { Reader = reader; reader.BaseStream.Position = Offset; if (resource.Version > 4) { throw new InvalidDataException($"Invalid vsnd version '{resource.Version}'"); } if (resource.Version >= 4) { SampleRate = reader.ReadUInt16(); var soundFormat = (AudioFormatV4)reader.ReadByte(); Channels = reader.ReadByte(); switch (soundFormat) { case AudioFormatV4.PCM8: SoundType = AudioFileType.WAV; Bits = 8; SampleSize = 1; AudioFormat = WaveAudioFormat.PCM; break; case AudioFormatV4.PCM16: SoundType = AudioFileType.WAV; Bits = 16; SampleSize = 2; AudioFormat = WaveAudioFormat.PCM; break; case AudioFormatV4.MP3: SoundType = AudioFileType.MP3; break; case AudioFormatV4.ADPCM: SoundType = AudioFileType.WAV; Bits = 4; SampleSize = 1; AudioFormat = WaveAudioFormat.ADPCM; throw new NotImplementedException("ADPCM is currently not implemented correctly."); default: throw new UnexpectedMagicException("Unexpected audio type", (int)soundFormat, nameof(soundFormat)); } } else { var bitpackedSoundInfo = reader.ReadUInt32(); var type = ExtractSub(bitpackedSoundInfo, 0, 2); if (type > 2) { throw new InvalidDataException($"Unknown sound type in old vsnd version: {type}"); } SoundType = (AudioFileType)type; Bits = ExtractSub(bitpackedSoundInfo, 2, 5); Channels = ExtractSub(bitpackedSoundInfo, 7, 2); SampleSize = ExtractSub(bitpackedSoundInfo, 9, 3); AudioFormat = (WaveAudioFormat)ExtractSub(bitpackedSoundInfo, 12, 2); SampleRate = ExtractSub(bitpackedSoundInfo, 14, 17); } LoopStart = reader.ReadInt32(); SampleCount = reader.ReadUInt32(); Duration = reader.ReadSingle(); // Skipping over m_Sentence (CSentence_t) and m_pHeader reader.BaseStream.Position += 12; StreamingDataSize = reader.ReadUInt32(); if (resource.Version < 1) { return; } var d = reader.ReadUInt32(); if (d != 0) { throw new UnexpectedMagicException("Unexpected", d, nameof(d)); } var e = reader.ReadUInt32(); if (e != 0) { throw new UnexpectedMagicException("Unexpected", e, nameof(e)); } if (resource.Version < 2) { return; } var f = reader.ReadUInt32(); if (f != 0) { throw new UnexpectedMagicException("Unexpected", f, nameof(f)); } // v2 and v3 are the same? if (resource.Version < 4) { return; } LoopEnd = reader.ReadInt32(); } private static uint ExtractSub(uint l, byte offset, byte nrBits) { var rightShifted = l >> offset; var mask = (1 << nrBits) - 1; return (uint)(rightShifted & mask); } /// <summary> /// Returns a fully playable sound data. /// In case of WAV files, header is automatically generated as Valve removes it when compiling. /// </summary> /// <returns>Byte array containing sound data.</returns> public byte[] GetSound() { using (var sound = GetSoundStream()) { return sound.ToArray(); } } /// <summary> /// Returns a fully playable sound data. /// In case of WAV files, header is automatically generated as Valve removes it when compiling. /// </summary> /// <returns>Memory stream containing sound data.</returns> public MemoryStream GetSoundStream() { Reader.BaseStream.Position = Offset + Size; var stream = new MemoryStream(); if (SoundType == AudioFileType.WAV) { // http://soundfile.sapp.org/doc/WaveFormat/ // http://www.codeproject.com/Articles/129173/Writing-a-Proper-Wave-File var headerRiff = new byte[] { 0x52, 0x49, 0x46, 0x46 }; var formatWave = new byte[] { 0x57, 0x41, 0x56, 0x45 }; var formatTag = new byte[] { 0x66, 0x6d, 0x74, 0x20 }; var subChunkId = new byte[] { 0x64, 0x61, 0x74, 0x61 }; var byteRate = SampleRate * Channels * (Bits / 8); var blockAlign = Channels * (Bits / 8); if (AudioFormat == WaveAudioFormat.ADPCM) { byteRate = 1; blockAlign = 4; } stream.Write(headerRiff, 0, headerRiff.Length); stream.Write(PackageInt(StreamingDataSize + 42, 4), 0, 4); stream.Write(formatWave, 0, formatWave.Length); stream.Write(formatTag, 0, formatTag.Length); stream.Write(PackageInt(16, 4), 0, 4); // Subchunk1Size stream.Write(PackageInt((uint)AudioFormat, 2), 0, 2); stream.Write(PackageInt(Channels, 2), 0, 2); stream.Write(PackageInt(SampleRate, 4), 0, 4); stream.Write(PackageInt(byteRate, 4), 0, 4); stream.Write(PackageInt(blockAlign, 2), 0, 2); stream.Write(PackageInt(Bits, 2), 0, 2); //stream.Write(PackageInt(0,2), 0, 2); // Extra param size stream.Write(subChunkId, 0, subChunkId.Length); stream.Write(PackageInt(StreamingDataSize, 4), 0, 4); } Reader.BaseStream.CopyTo(stream, (int)StreamingDataSize); // Flush and reset position so that consumers can read it stream.Flush(); stream.Seek(0, SeekOrigin.Begin); return stream; } private static byte[] PackageInt(uint source, int length) { var retVal = new byte[length]; retVal[0] = (byte)(source & 0xFF); retVal[1] = (byte)((source >> 8) & 0xFF); if (length == 4) { retVal[2] = (byte)((source >> 0x10) & 0xFF); retVal[3] = (byte)((source >> 0x18) & 0xFF); } return retVal; } public override string ToString() { var output = new StringBuilder(); output.AppendLine($"SoundType: {SoundType}"); output.AppendLine($"Sample Rate: {SampleRate}"); output.AppendLine($"Bits: {Bits}"); output.AppendLine($"SampleSize: {SampleSize}"); output.AppendLine($"SampleCount: {SampleCount}"); output.AppendLine($"Format: {AudioFormat}"); output.AppendLine($"Channels: {Channels}"); var loopStart = TimeSpan.FromSeconds(LoopStart); output.AppendLine($"LoopStart: ({loopStart}) {LoopStart}"); var loopEnd = TimeSpan.FromSeconds(LoopEnd); output.AppendLine($"LoopEnd: ({loopEnd}) {LoopEnd}"); var duration = TimeSpan.FromSeconds(Duration); output.AppendLine($"Duration: {duration} ({Duration})"); return output.ToString(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; namespace Microsoft.CSharp.RuntimeBinder.Semantics { // ---------------------------------------------------------------------------- // // AggregateType // // Represents a generic constructed (or instantiated) type. Parent is the AggregateSymbol. // ---------------------------------------------------------------------------- internal partial class AggregateType : CType { private TypeArray _pTypeArgsThis; private TypeArray _pTypeArgsAll; // includes args from outer types private AggregateSymbol _pOwningAggregate; private AggregateType _baseType; // This is the result of calling SubstTypeArray on the aggregate's baseClass. private TypeArray _ifacesAll; // This is the result of calling SubstTypeArray on the aggregate's ifacesAll. private TypeArray _winrtifacesAll; //This is the list of collection interfaces implemented by a WinRT object. public bool fConstraintsChecked; // Have the constraints been checked yet? public bool fConstraintError; // Did the constraints check produce an error? // These two flags are used to track hiding within interfaces. // Their use and validity is always localized. See e.g. MemberLookup::LookupInInterfaces. public bool fAllHidden; // All members are hidden by a derived interface member. public bool fDiffHidden; // Members other than a specific kind are hidden by a derived interface member or class member. public AggregateType outerType; // the outer type if this is a nested type public void SetOwningAggregate(AggregateSymbol agg) { _pOwningAggregate = agg; } public AggregateSymbol GetOwningAggregate() { return _pOwningAggregate; } public AggregateType GetBaseClass() { return _baseType ?? (_baseType = getAggregate().GetTypeManager().SubstType(getAggregate().GetBaseClass(), GetTypeArgsAll()) as AggregateType); } public IEnumerable<AggregateType> TypeHierarchy { get { if (isInterfaceType()) { yield return this; foreach (AggregateType iface in GetIfacesAll().Items) { yield return iface; } yield return getAggregate().GetTypeManager().ObjectAggregateType; } else { for (AggregateType agg = this; agg != null; agg = agg.GetBaseClass()) { yield return agg; } } } } public void SetTypeArgsThis(TypeArray pTypeArgsThis) { TypeArray pOuterTypeArgs; if (outerType != null) { Debug.Assert(outerType.GetTypeArgsThis() != null); Debug.Assert(outerType.GetTypeArgsAll() != null); pOuterTypeArgs = outerType.GetTypeArgsAll(); } else { pOuterTypeArgs = BSYMMGR.EmptyTypeArray(); } Debug.Assert(pTypeArgsThis != null); _pTypeArgsThis = pTypeArgsThis; SetTypeArgsAll(pOuterTypeArgs); } private void SetTypeArgsAll(TypeArray outerTypeArgs) { Debug.Assert(_pTypeArgsThis != null); // Here we need to check our current type args. If we have an open placeholder, // then we need to have all open placeholders, and we want to flush // our outer type args so that they're open placeholders. // // This is because of the following scenario: // // class B<T> // { // class C<U> // { // } // class D // { // void Foo() // { // Type T = typeof(C<>); // } // } // } // // The outer type will be B<T>, but the inner type will be C<>. However, // this will eventually be represented in IL as B<>.C<>. As such, we should // keep our data structures clear - if we have one open type argument, then // all of them must be open type arguments. // // Ensure that invariant here. TypeArray pCheckedOuterTypeArgs = outerTypeArgs; TypeManager pTypeManager = getAggregate().GetTypeManager(); if (_pTypeArgsThis.Count > 0 && AreAllTypeArgumentsUnitTypes(_pTypeArgsThis)) { if (outerTypeArgs.Count > 0 && !AreAllTypeArgumentsUnitTypes(outerTypeArgs)) { // We have open placeholder types in our type, but not the parent. pCheckedOuterTypeArgs = pTypeManager.CreateArrayOfUnitTypes(outerTypeArgs.Count); } } _pTypeArgsAll = pTypeManager.ConcatenateTypeArrays(pCheckedOuterTypeArgs, _pTypeArgsThis); } private bool AreAllTypeArgumentsUnitTypes(TypeArray typeArray) { if (typeArray.Count == 0) { return true; } for (int i = 0; i < typeArray.Count; i++) { Debug.Assert(typeArray[i] != null); if (!typeArray[i].IsOpenTypePlaceholderType()) { return false; } } return true; } public TypeArray GetTypeArgsThis() { return _pTypeArgsThis; } public TypeArray GetTypeArgsAll() { return _pTypeArgsAll; } public TypeArray GetIfacesAll() { if (_ifacesAll == null) { _ifacesAll = getAggregate().GetTypeManager().SubstTypeArray(getAggregate().GetIfacesAll(), GetTypeArgsAll()); } return _ifacesAll; } public TypeArray GetWinRTCollectionIfacesAll(SymbolLoader pSymbolLoader) { if (_winrtifacesAll == null) { TypeArray ifaces = GetIfacesAll(); System.Collections.Generic.List<CType> typeList = new System.Collections.Generic.List<CType>(); for (int i = 0; i < ifaces.Count; i++) { AggregateType type = ifaces[i].AsAggregateType(); Debug.Assert(type.isInterfaceType()); if (type.IsCollectionType()) { typeList.Add(type); } } _winrtifacesAll = pSymbolLoader.getBSymmgr().AllocParams(typeList.Count, typeList.ToArray()); } return _winrtifacesAll; } public TypeArray GetDelegateParameters(SymbolLoader pSymbolLoader) { Debug.Assert(isDelegateType()); MethodSymbol invoke = pSymbolLoader.LookupInvokeMeth(getAggregate()); if (invoke == null || !invoke.isInvoke()) { // This can happen if the delegate is internal to another assembly. return null; } return getAggregate().GetTypeManager().SubstTypeArray(invoke.Params, this); } public CType GetDelegateReturnType(SymbolLoader pSymbolLoader) { Debug.Assert(isDelegateType()); MethodSymbol invoke = pSymbolLoader.LookupInvokeMeth(getAggregate()); if (invoke == null || !invoke.isInvoke()) { // This can happen if the delegate is internal to another assembly. return null; } return getAggregate().GetTypeManager().SubstType(invoke.RetType, this); } } }
// Copyright (C) 2014 dot42 // // Original filename: Java.Beans.cs // // 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. #pragma warning disable 1717 namespace Java.Beans { /// <summary> /// <para>An event that indicates that a constraint or a boundary of a property has changed. </para> /// </summary> /// <java-name> /// java/beans/PropertyChangeEvent /// </java-name> [Dot42.DexImport("java/beans/PropertyChangeEvent", AccessFlags = 33)] public partial class PropertyChangeEvent : global::Java.Util.EventObject /* scope: __dot42__ */ { /// <summary> /// <para>The constructor used to create a new <c> PropertyChangeEvent </c> .</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 1)] public PropertyChangeEvent(object source, string propertyName, object oldValue, object newValue) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the name of the property that has changed. If an unspecified set of properties has changed it returns null.</para><para></para> /// </summary> /// <returns> /// <para>the name of the property that has changed, or null. </para> /// </returns> /// <java-name> /// getPropertyName /// </java-name> [Dot42.DexImport("getPropertyName", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetPropertyName() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Sets the propagationId object.</para><para><para>getPropagationId() </para></para> /// </summary> /// <java-name> /// setPropagationId /// </java-name> [Dot42.DexImport("setPropagationId", "(Ljava/lang/Object;)V", AccessFlags = 1)] public virtual void SetPropagationId(object propagationId) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the propagationId object. This is reserved for future use. Beans 1.0 demands that a listener receiving this property and then sending its own PropertyChangeEvent sets the received propagationId on the new PropertyChangeEvent's propagationId field.</para><para></para> /// </summary> /// <returns> /// <para>the propagationId object. </para> /// </returns> /// <java-name> /// getPropagationId /// </java-name> [Dot42.DexImport("getPropagationId", "()Ljava/lang/Object;", AccessFlags = 1)] public virtual object GetPropagationId() /* MethodBuilder.Create */ { return default(object); } /// <summary> /// <para>Returns the old value that the property had. If the old value is unknown this method returns null.</para><para></para> /// </summary> /// <returns> /// <para>the old property value or null. </para> /// </returns> /// <java-name> /// getOldValue /// </java-name> [Dot42.DexImport("getOldValue", "()Ljava/lang/Object;", AccessFlags = 1)] public virtual object GetOldValue() /* MethodBuilder.Create */ { return default(object); } /// <summary> /// <para>Returns the new value that the property now has. If the new value is unknown this method returns null.</para><para></para> /// </summary> /// <returns> /// <para>the old property value or null. </para> /// </returns> /// <java-name> /// getNewValue /// </java-name> [Dot42.DexImport("getNewValue", "()Ljava/lang/Object;", AccessFlags = 1)] public virtual object GetNewValue() /* MethodBuilder.Create */ { return default(object); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal PropertyChangeEvent() /* TypeBuilder.AddDefaultConstructor */ { } /// <summary> /// <para>Returns the name of the property that has changed. If an unspecified set of properties has changed it returns null.</para><para></para> /// </summary> /// <returns> /// <para>the name of the property that has changed, or null. </para> /// </returns> /// <java-name> /// getPropertyName /// </java-name> public string PropertyName { [Dot42.DexImport("getPropertyName", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetPropertyName(); } } /// <summary> /// <para>Returns the propagationId object. This is reserved for future use. Beans 1.0 demands that a listener receiving this property and then sending its own PropertyChangeEvent sets the received propagationId on the new PropertyChangeEvent's propagationId field.</para><para></para> /// </summary> /// <returns> /// <para>the propagationId object. </para> /// </returns> /// <java-name> /// getPropagationId /// </java-name> public object PropagationId { [Dot42.DexImport("getPropagationId", "()Ljava/lang/Object;", AccessFlags = 1)] get{ return GetPropagationId(); } [Dot42.DexImport("setPropagationId", "(Ljava/lang/Object;)V", AccessFlags = 1)] set{ SetPropagationId(value); } } /// <summary> /// <para>Returns the old value that the property had. If the old value is unknown this method returns null.</para><para></para> /// </summary> /// <returns> /// <para>the old property value or null. </para> /// </returns> /// <java-name> /// getOldValue /// </java-name> public object OldValue { [Dot42.DexImport("getOldValue", "()Ljava/lang/Object;", AccessFlags = 1)] get{ return GetOldValue(); } } /// <summary> /// <para>Returns the new value that the property now has. If the new value is unknown this method returns null.</para><para></para> /// </summary> /// <returns> /// <para>the old property value or null. </para> /// </returns> /// <java-name> /// getNewValue /// </java-name> public object NewValue { [Dot42.DexImport("getNewValue", "()Ljava/lang/Object;", AccessFlags = 1)] get{ return GetNewValue(); } } } /// <summary> /// <para>Manages a list of listeners to be notified when a property changes. Listeners subscribe to be notified of all property changes, or of changes to a single named property.</para><para>This class is thread safe. No locking is necessary when subscribing or unsubscribing listeners, or when publishing events. Callers should be careful when publishing events because listeners may not be thread safe. </para> /// </summary> /// <java-name> /// java/beans/PropertyChangeSupport /// </java-name> [Dot42.DexImport("java/beans/PropertyChangeSupport", AccessFlags = 33)] public partial class PropertyChangeSupport : global::Java.Io.ISerializable /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new instance that uses the source bean as source for any event.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/Object;)V", AccessFlags = 1)] public PropertyChangeSupport(object sourceBean) /* MethodBuilder.Create */ { } /// <java-name> /// firePropertyChange /// </java-name> [Dot42.DexImport("firePropertyChange", "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 1)] public virtual void FirePropertyChange(string @string, object @object, object object1) /* MethodBuilder.Create */ { } /// <java-name> /// fireIndexedPropertyChange /// </java-name> [Dot42.DexImport("fireIndexedPropertyChange", "(Ljava/lang/String;ILjava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 1)] public virtual void FireIndexedPropertyChange(string @string, int int32, object @object, object object1) /* MethodBuilder.Create */ { } /// <summary> /// <para>Unsubscribes <c> listener </c> from change notifications for the property named <c> propertyName </c> . If multiple subscriptions exist for <c> listener </c> , it will receive one fewer notifications when the property changes. If the property name or listener is null or not subscribed, this method silently does nothing. </para> /// </summary> /// <java-name> /// removePropertyChangeListener /// </java-name> [Dot42.DexImport("removePropertyChangeListener", "(Ljava/lang/String;Ljava/beans/PropertyChangeListener;)V", AccessFlags = 1)] public virtual void RemovePropertyChangeListener(string propertyName, global::Java.Beans.IPropertyChangeListener listener) /* MethodBuilder.Create */ { } /// <summary> /// <para>Subscribes <c> listener </c> to change notifications for the property named <c> propertyName </c> . If the listener is already subscribed, it will receive an additional notification when the property changes. If the property name or listener is null, this method silently does nothing. </para> /// </summary> /// <java-name> /// addPropertyChangeListener /// </java-name> [Dot42.DexImport("addPropertyChangeListener", "(Ljava/lang/String;Ljava/beans/PropertyChangeListener;)V", AccessFlags = 1)] public virtual void AddPropertyChangeListener(string propertyName, global::Java.Beans.IPropertyChangeListener listener) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the subscribers to be notified when <c> propertyName </c> changes. This includes both listeners subscribed to all property changes and listeners subscribed to the named property only. </para> /// </summary> /// <java-name> /// getPropertyChangeListeners /// </java-name> [Dot42.DexImport("getPropertyChangeListeners", "(Ljava/lang/String;)[Ljava/beans/PropertyChangeListener;", AccessFlags = 1)] public virtual global::Java.Beans.IPropertyChangeListener[] GetPropertyChangeListeners(string propertyName) /* MethodBuilder.Create */ { return default(global::Java.Beans.IPropertyChangeListener[]); } /// <java-name> /// firePropertyChange /// </java-name> [Dot42.DexImport("firePropertyChange", "(Ljava/lang/String;ZZ)V", AccessFlags = 1)] public virtual void FirePropertyChange(string @string, bool boolean, bool boolean1) /* MethodBuilder.Create */ { } /// <java-name> /// fireIndexedPropertyChange /// </java-name> [Dot42.DexImport("fireIndexedPropertyChange", "(Ljava/lang/String;IZZ)V", AccessFlags = 1)] public virtual void FireIndexedPropertyChange(string @string, int int32, bool boolean, bool boolean1) /* MethodBuilder.Create */ { } /// <java-name> /// firePropertyChange /// </java-name> [Dot42.DexImport("firePropertyChange", "(Ljava/lang/String;II)V", AccessFlags = 1)] public virtual void FirePropertyChange(string @string, int int32, int int321) /* MethodBuilder.Create */ { } /// <java-name> /// fireIndexedPropertyChange /// </java-name> [Dot42.DexImport("fireIndexedPropertyChange", "(Ljava/lang/String;III)V", AccessFlags = 1)] public virtual void FireIndexedPropertyChange(string @string, int int32, int int321, int int322) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns true if there are listeners registered to the property with the given name.</para><para></para> /// </summary> /// <returns> /// <para>true if there are listeners registered to that property, false otherwise. </para> /// </returns> /// <java-name> /// hasListeners /// </java-name> [Dot42.DexImport("hasListeners", "(Ljava/lang/String;)Z", AccessFlags = 1)] public virtual bool HasListeners(string propertyName) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Unsubscribes <c> listener </c> from change notifications for all properties. If the listener has multiple subscriptions, it will receive one fewer notification when properties change. If the property name or listener is null or not subscribed, this method silently does nothing. </para> /// </summary> /// <java-name> /// removePropertyChangeListener /// </java-name> [Dot42.DexImport("removePropertyChangeListener", "(Ljava/beans/PropertyChangeListener;)V", AccessFlags = 1)] public virtual void RemovePropertyChangeListener(global::Java.Beans.IPropertyChangeListener listener) /* MethodBuilder.Create */ { } /// <summary> /// <para>Subscribes <c> listener </c> to change notifications for all properties. If the listener is already subscribed, it will receive an additional notification. If the listener is null, this method silently does nothing. </para> /// </summary> /// <java-name> /// addPropertyChangeListener /// </java-name> [Dot42.DexImport("addPropertyChangeListener", "(Ljava/beans/PropertyChangeListener;)V", AccessFlags = 1)] public virtual void AddPropertyChangeListener(global::Java.Beans.IPropertyChangeListener listener) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns all subscribers. This includes both listeners subscribed to all property changes and listeners subscribed to a single property. </para> /// </summary> /// <java-name> /// getPropertyChangeListeners /// </java-name> [Dot42.DexImport("getPropertyChangeListeners", "()[Ljava/beans/PropertyChangeListener;", AccessFlags = 1)] public virtual global::Java.Beans.IPropertyChangeListener[] GetPropertyChangeListeners() /* MethodBuilder.Create */ { return default(global::Java.Beans.IPropertyChangeListener[]); } /// <summary> /// <para>Publishes a property change event to all listeners of that property. If the event's old and new values are equal (but non-null), no event will be published. </para> /// </summary> /// <java-name> /// firePropertyChange /// </java-name> [Dot42.DexImport("firePropertyChange", "(Ljava/beans/PropertyChangeEvent;)V", AccessFlags = 1)] public virtual void FirePropertyChange(global::Java.Beans.PropertyChangeEvent @event) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal PropertyChangeSupport() /* TypeBuilder.AddDefaultConstructor */ { } /// <summary> /// <para>Returns all subscribers. This includes both listeners subscribed to all property changes and listeners subscribed to a single property. </para> /// </summary> /// <java-name> /// getPropertyChangeListeners /// </java-name> public global::Java.Beans.IPropertyChangeListener[] PropertyChangeListeners { [Dot42.DexImport("getPropertyChangeListeners", "()[Ljava/beans/PropertyChangeListener;", AccessFlags = 1)] get{ return GetPropertyChangeListeners(); } } } /// <summary> /// <para>A type of PropertyChangeEvent that indicates that an indexed property has changed. </para> /// </summary> /// <java-name> /// java/beans/IndexedPropertyChangeEvent /// </java-name> [Dot42.DexImport("java/beans/IndexedPropertyChangeEvent", AccessFlags = 33)] public partial class IndexedPropertyChangeEvent : global::Java.Beans.PropertyChangeEvent /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new property changed event with an indication of the property index.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;I)V", AccessFlags = 1)] public IndexedPropertyChangeEvent(object source, string propertyName, object oldValue, object newValue, int index) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the index of the property that was changed in this event. </para> /// </summary> /// <java-name> /// getIndex /// </java-name> [Dot42.DexImport("getIndex", "()I", AccessFlags = 1)] public virtual int GetIndex() /* MethodBuilder.Create */ { return default(int); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal IndexedPropertyChangeEvent() /* TypeBuilder.AddDefaultConstructor */ { } /// <summary> /// <para>Returns the index of the property that was changed in this event. </para> /// </summary> /// <java-name> /// getIndex /// </java-name> public int Index { [Dot42.DexImport("getIndex", "()I", AccessFlags = 1)] get{ return GetIndex(); } } } /// <summary> /// <para>A PropertyChangeListener can subscribe with a event source. Whenever that source raises a PropertyChangeEvent this listener will get notified. </para> /// </summary> /// <java-name> /// java/beans/PropertyChangeListener /// </java-name> [Dot42.DexImport("java/beans/PropertyChangeListener", AccessFlags = 1537)] public partial interface IPropertyChangeListener : global::Java.Util.IEventListener /* scope: __dot42__ */ { /// <summary> /// <para>The source bean calls this method when an event is raised.</para><para></para> /// </summary> /// <java-name> /// propertyChange /// </java-name> [Dot42.DexImport("propertyChange", "(Ljava/beans/PropertyChangeEvent;)V", AccessFlags = 1025)] void PropertyChange(global::Java.Beans.PropertyChangeEvent @event) /* MethodBuilder.Create */ ; } /// <summary> /// <para>The implementation of this listener proxy just delegates the received events to its listener. </para> /// </summary> /// <java-name> /// java/beans/PropertyChangeListenerProxy /// </java-name> [Dot42.DexImport("java/beans/PropertyChangeListenerProxy", AccessFlags = 33)] public partial class PropertyChangeListenerProxy : global::Java.Util.EventListenerProxy, global::Java.Beans.IPropertyChangeListener /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new listener proxy that associates a listener with a property name.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/beans/PropertyChangeListener;)V", AccessFlags = 1)] public PropertyChangeListenerProxy(string propertyName, global::Java.Beans.IPropertyChangeListener listener) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the name of the property associated with this listener proxy.</para><para></para> /// </summary> /// <returns> /// <para>the name of the associated property. </para> /// </returns> /// <java-name> /// getPropertyName /// </java-name> [Dot42.DexImport("getPropertyName", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetPropertyName() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>The source bean calls this method when an event is raised.</para><para></para> /// </summary> /// <java-name> /// propertyChange /// </java-name> [Dot42.DexImport("propertyChange", "(Ljava/beans/PropertyChangeEvent;)V", AccessFlags = 1)] public virtual void PropertyChange(global::Java.Beans.PropertyChangeEvent @event) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal PropertyChangeListenerProxy() /* TypeBuilder.AddDefaultConstructor */ { } /// <summary> /// <para>Returns the name of the property associated with this listener proxy.</para><para></para> /// </summary> /// <returns> /// <para>the name of the associated property. </para> /// </returns> /// <java-name> /// getPropertyName /// </java-name> public string PropertyName { [Dot42.DexImport("getPropertyName", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetPropertyName(); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Ais.Internal.Dcm.Web.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.Collections.Generic; using System.Text; #if FRB_XNA using Microsoft.Xna.Framework.Graphics; #endif namespace FlatRedBall.ManagedSpriteGroups { public class TextureGrid<T> { #region Fields internal List<List<T>> mTextures; internal T mBaseTexture; List<float> mFirstPaintedX = new List<float>(); List<float> mLastPaintedX = new List<float>(); float mFirstPaintedY; float mLastPaintedY; internal float mXOffset; internal float mYOffset; float mGridSpacingX; float mGridSpacingY; float mSpaceHalfX; float mSpaceHalfY; float mSpaceFourthX; float mSpaceFourthY; #endregion #region Properties public T BaseTexture { get { return mBaseTexture; } set { mBaseTexture = value; } } public float GridSpacingX { get { return mGridSpacingX; } set { mGridSpacingX = value; mSpaceFourthX = mGridSpacingX / 4.0f; mSpaceHalfX = mGridSpacingX / 2.0f; } } public float GridSpacingY { get { return mGridSpacingY; } set { mGridSpacingY = value; mSpaceFourthY = mGridSpacingY / 4.0f; mSpaceHalfY = mGridSpacingY / 2.0f; } } public List<T> this[int i] { get { return mTextures[i]; } } public List<float> FirstPaintedX { get { return mFirstPaintedX; } set { mFirstPaintedX = value; } } public List<float> LastPaintedX { get { return mLastPaintedX; } set { mLastPaintedX = value; } } public float FirstPaintedY { get { return mFirstPaintedY; } set { mFirstPaintedY = value; } } public float LastPaintedY { get { return mLastPaintedY; } set { mLastPaintedY = value; } } public List<List<T>> Textures { get { return mTextures; } set { mTextures = value; } } #endregion #region Methods #region Constructor public TextureGrid() { mTextures = new List<List<T>>(); mFirstPaintedX = new List<float>(); mLastPaintedX = new List<float>(); } #endregion public void Initialize(T baseTexture, float xOffset, float yOffset, float gridSpacingX, float gridSpacingY) { this.mBaseTexture = baseTexture; mXOffset = xOffset; mYOffset = yOffset; mGridSpacingX = gridSpacingX; mGridSpacingY = gridSpacingY; this.mFirstPaintedY = float.NaN; this.mLastPaintedY = float.NaN; } public void InvertZ() { // Actually, Y is Z when the SpriteGrid that uses this goes into the Z plane mFirstPaintedY = -mFirstPaintedY; mLastPaintedY = -mLastPaintedY; } public void Clear() { mFirstPaintedX.Clear(); mLastPaintedX.Clear(); mFirstPaintedY = float.NaN; mLastPaintedY = float.NaN; mTextures.Clear(); } #region XML Docs /// <summary> /// Shifts the position of all textures in the TextureGrid. /// </summary> /// <param name="x">The distance along the x axis to shift the grid.</param> /// <param name="y">The distance along the y axis to shift the grid.</param> #endregion public void ChangeGrid(float x, float y) { mFirstPaintedY += y; mLastPaintedY += y; for (int i = 0; i < mFirstPaintedX.Count; i++) { if (float.IsNaN(this.mFirstPaintedX[i]) == false) { mFirstPaintedX[i] += x; mLastPaintedX[i] += x; } } mXOffset += x; mYOffset += y; } public TextureGrid<T> Clone() { TextureGrid<T> gridToReturn = (TextureGrid<T>)(MemberwiseClone()); gridToReturn.mTextures = new List<List<T>>(); foreach (List<T> array in mTextures) { List<T> ta = new List<T>(); gridToReturn.mTextures.Add(ta); foreach (T texture in array) ta.Add(texture); } gridToReturn.mFirstPaintedX = new List<float>(); foreach (float f in mFirstPaintedX) gridToReturn.mFirstPaintedX.Add(f); gridToReturn.mLastPaintedX = new List<float>(); foreach (float f in mLastPaintedX) gridToReturn.mLastPaintedX.Add(f); return gridToReturn; } public T GetTextureAt(double x, double y) { if (mTextures.Count == 0) return mBaseTexture; //#if FRB_MDX if (y - mSpaceHalfY < mLastPaintedY && y + mSpaceHalfY > mFirstPaintedY) { int yOn = (int)System.Math.Round((y - mFirstPaintedY) / mGridSpacingY); if (mFirstPaintedX.Count > 0 && x > mFirstPaintedX[yOn] - mSpaceHalfX && x <= mLastPaintedX[yOn] + mSpaceHalfX) { int xOn = (int)System.Math.Round((x - mFirstPaintedX[yOn]) / mGridSpacingX); if(xOn > mTextures[yOn].Count - 1) return mTextures[yOn][mTextures[yOn].Count - 1]; else return mTextures[yOn][xOn]; } } //#elif FRB_XNA // if (y + mSpaceHalfY > mLastPaintedY && y - mSpaceHalfY < mFirstPaintedY) // { // int yOn = -(int)System.Math.Round((y - mFirstPaintedY) / mGridSpacingY); // if (mFirstPaintedX.Count > 0 && // x > mFirstPaintedX[yOn] - mSpaceHalfX && x <= mLastPaintedX[yOn] + mSpaceHalfX) // { // return mTextures[yOn][(int)System.Math.Round((x - mFirstPaintedX[yOn]) / mGridSpacingX)]; // } // } //#endif return mBaseTexture; } public List<TextureLocation<T>> GetTextureLocationDifferences(TextureGrid<T> originalGrid) { List<TextureLocation<T>> textureLocationArray = new List<TextureLocation<T>>(); // These are empty grids, so there's no changes. if (this.FirstPaintedX.Count == 0 && originalGrid.FirstPaintedX.Count == 0) { return textureLocationArray; } int thisYOn = 0; int originalYOn = 0; #region Get minY which is the smallest painted Y float minY = (float)System.Math.Min(mFirstPaintedY, originalGrid.mFirstPaintedY); if (originalGrid.mTextures.Count == 0) { minY = mFirstPaintedY; } else if (this.mTextures.Count == 0) { minY = originalGrid.mFirstPaintedY; } if (float.IsNaN(originalGrid.mFirstPaintedY)) minY = mFirstPaintedY; #endregion #region Get maxY which is the largest painted Y float maxY = (float)System.Math.Max(mLastPaintedY, originalGrid.mLastPaintedY); if (originalGrid.mTextures.Count == 0) { maxY = mLastPaintedY; } else if (this.mTextures.Count == 0) { maxY = originalGrid.mLastPaintedY; } if (float.IsNaN(originalGrid.mLastPaintedY)) maxY = mLastPaintedY; #endregion if (originalGrid.mTextures.Count == 0) { originalYOn = 0; thisYOn = 0; } else if (originalGrid.mFirstPaintedY - mFirstPaintedY > mSpaceHalfY) { thisYOn = 0; originalYOn = (int)System.Math.Round((mFirstPaintedY - originalGrid.mFirstPaintedY) / mGridSpacingY); } else if (mFirstPaintedY - originalGrid.mFirstPaintedY > mSpaceHalfY) {// if the this instance begins below originalGrid originalYOn = 0; thisYOn = (int)System.Math.Round((mFirstPaintedY - originalGrid.mFirstPaintedY) / mGridSpacingY); } // float minX = 0; float maxX = 0; T originalTexture = default(T); for (float y = minY; y - mSpaceFourthY < maxY; y += mGridSpacingY) { if (originalGrid.mTextures.Count == 0 || originalYOn < 0) {// if the this instance begins below originalGrid for (float x = this.mFirstPaintedX[thisYOn]; x - mSpaceFourthX < this.mLastPaintedX[thisYOn]; x += mGridSpacingX) { textureLocationArray.Add(new TextureLocation<T>(originalGrid.mBaseTexture, x, y)); } } else if (thisYOn < 0) {// the original grid is below this grid for (float x = originalGrid.mFirstPaintedX[originalYOn]; x - mSpaceFourthX < originalGrid.mLastPaintedX[originalYOn]; x += mGridSpacingX) { textureLocationArray.Add(new TextureLocation<T>(this.mBaseTexture, x, y)); } } else {// y is above the bottom border of both grids if (thisYOn > this.mTextures.Count - 1) { // y is above the this instance top for (float x = originalGrid.mFirstPaintedX[originalYOn]; x - mSpaceFourthX < originalGrid.mLastPaintedX[originalYOn]; x += mGridSpacingX) { textureLocationArray.Add(new TextureLocation<T>(this.mBaseTexture, x, y)); } } else if (originalYOn > originalGrid.mTextures.Count - 1) { // Y is above the originalGrid's top for (float x = this.mFirstPaintedX[thisYOn]; x - mSpaceFourthX < this.mLastPaintedX[thisYOn]; x += mGridSpacingX) { textureLocationArray.Add(new TextureLocation<T>(originalGrid.mBaseTexture, x, y)); } } else { // y is between the top and bottom of both grids maxX = System.Math.Max(this.mLastPaintedX[thisYOn], originalGrid.mLastPaintedX[originalYOn]); for (float x = System.Math.Min(this.mFirstPaintedX[thisYOn], originalGrid.mFirstPaintedX[originalYOn]); x - mSpaceFourthX < maxX; x += mGridSpacingX) { originalTexture = originalGrid.GetTextureAt(x, y); T newTexture = this.GetTextureAt(x, y); bool areBothNull = newTexture == null && originalTexture == null; if (!areBothNull) { if ((originalTexture == null && newTexture != null) || originalTexture.Equals(this.GetTextureAt(x, y)) == false) textureLocationArray.Add(new TextureLocation<T>(originalTexture, x, y)); } } } } // moving up one row, so increment the y value originalYOn++; thisYOn++; } return textureLocationArray; } public List<T> GetUsedTextures() { List<T> arrayToReturn = new List<T>(); if (mBaseTexture != null) { arrayToReturn.Add(mBaseTexture); } foreach (List<T> ta in mTextures) { foreach (T tex in ta) { if (tex != null && !arrayToReturn.Contains(tex)) arrayToReturn.Add(tex); } } return arrayToReturn; } public bool IsTextureReferenced(T texture) { if (mBaseTexture.Equals(texture)) return true; foreach (List<T> fta in mTextures) { if (fta.Contains(texture)) return true; } return false; } public void PaintGridAtPosition(float x, float y, T textureToPaint) { T textureAtXY = this.GetTextureAt(x, y); if ( (textureAtXY == null && textureToPaint == null) || (textureToPaint != null && textureToPaint.Equals(textureAtXY))) return; #region locate the center position of this texture. // float x = XOffset + (int)(System.Math.Round( (xFloat)/mGridSpacing)) * mGridSpacing; // float y = YOffset + (int)(System.Math.Round( (yFloat)/mGridSpacing)) * mGridSpacing; #endregion #region this is the first texture we are painting if (mTextures.Count == 0) { // this is the first texture, so we mark it mFirstPaintedX.Add(x); mFirstPaintedY = y; mLastPaintedX.Add(x); mLastPaintedY = y; mTextures.Add(new List<T>()); mTextures[0].Add(textureToPaint); } #endregion else { int yOn = (int)(System.Math.Round((y - mFirstPaintedY) / mGridSpacingY)); #region If the position we are painting is higher than all others, Add to the ArrayLists so they include this high if (yOn > mFirstPaintedX.Count - 1) { while (yOn > mFirstPaintedX.Count - 1) { mFirstPaintedX.Add(float.NaN); mLastPaintedX.Add(float.NaN); mTextures.Add(new List<T>()); mLastPaintedY += mGridSpacingY; } } #endregion #region if the position we are painting is lower than all others, insert on the ArrayLists so they include this low else if (yOn < 0) { while (yOn < 0) { mFirstPaintedX.Insert(0, float.NaN); mLastPaintedX.Insert(0, float.NaN); mFirstPaintedY -= mGridSpacingY; mTextures.Insert(0, new List<T>()); yOn++; } } #endregion #region the position is on an already-existing row else { int xOn = (int)System.Math.Round((x - mFirstPaintedX[yOn]) / mGridSpacingX); if (float.IsNaN(mFirstPaintedX[yOn])) { // first texture mFirstPaintedX[yOn] = x; mLastPaintedX[yOn] = x; mTextures[yOn].Add(textureToPaint); } #region this is the furthest right on this row else if (xOn > mTextures[yOn].Count - 1) { while (xOn > mTextures[yOn].Count - 1) { mLastPaintedX[yOn] += mGridSpacingX; mTextures[yOn].Add(mBaseTexture); } mTextures[yOn][xOn] = textureToPaint; } #endregion #region this is the furthest left on this row else if (xOn < 0) { while (xOn < 0) { mFirstPaintedX[yOn] -= mGridSpacingX; mTextures[yOn].Insert(0, mBaseTexture); xOn++; } mTextures[yOn][0] = textureToPaint; } #endregion else { // reduce the textures 2D array here if painting the base texture mTextures[yOn][xOn] = textureToPaint; if ( (textureToPaint == null && mBaseTexture == null) || (textureToPaint != null && textureToPaint.Equals(mBaseTexture))) { this.ReduceGridAtIndex(yOn, xOn); } } } #endregion /* Since we may have painted the baseTexture, the grid may have contracted. If that's the case * we need to make sure that it's not completely contracted so that firstPainted.Count == 0 */ if (mFirstPaintedX.Count != 0 && yOn < mFirstPaintedX.Count && float.IsNaN(mFirstPaintedX[yOn])) { // first texture mFirstPaintedX[yOn] = x; mLastPaintedX[yOn] = x; mTextures[yOn].Add(textureToPaint); } } } #region XML Docs /// <summary> /// This "shrinks" the grid if its edges are the same as its baseTexture /// </summary> /// <remarks> /// To use the least amount of memory, TextureGrids only store non-baseTexture strips. /// If the ends of a horizontal strip are the baseTexture, then the strip should be contracted /// inward. If an entire horizontal strip is the baseTexture, then it should be removed. /// /// Usually, tests should begin from a specific location, as it is usually called after the /// grid is painted. This method will first check to see if the arguments are on the left or /// right side of a strip. Then a loop will move inward as long as it continues to encounter /// the base texture. Once it encounters a non-baseTexture, then it stops, and reduces the /// particular horizontal strip. /// /// If an entire strip is cleared and it is either the top or bottom strip, then it will /// be removed, and the strip above or below (depending on position) will be tested as well. /// If the strip is in the center (not the top or bottom), then it will be reduced, but cannot /// be removed. /// </remarks> /// <param name="yFloat">The y location in absolute coordinates to start the tests at.</param> /// <param name="xFloat">The x location in absolute coordinates to start the tests at.</param> #endregion public void ReduceGrid(float yFloat, float xFloat) { // float x = XOffset + (int)(System.Math.Round( (xFloat)/mGridSpacing)) * mGridSpacing; // float y = YOffset + (int)(System.Math.Round( (yFloat)/mGridSpacing)) * mGridSpacing; float x = (int)(System.Math.Round((xFloat) / mGridSpacingX)) * mGridSpacingX; float y = (int)(System.Math.Round((yFloat) / mGridSpacingY)) * mGridSpacingY; int yOn = (int)(System.Math.Round((y - mFirstPaintedY) / mGridSpacingY)); int xOn = (int)System.Math.Round((x - mFirstPaintedX[yOn]) / mGridSpacingX); ReduceGridAtIndex(yOn, xOn); } #region XML Docs /// <summary> /// This "shrinks" the grid if its edges are the same as its baseTexture /// </summary> /// <remarks> /// To use the least amount of memory, TextureGrids only store non-baseTexture strips. /// If the ends of a horizontal strip are the baseTexture, then the strip should be contracted /// inward. If an entire horizontal strip is the baseTexture, then it should be removed. /// /// Usually, tests should begin from a specific location, as it is usually called after the /// grid is painted. This method will first check to see if the arguments are on the left or /// right side of a strip. Then a loop will move inward as long as it continues to encounter /// the base texture. Once it encounters a non-baseTexture, then it stops, and reduces the /// particular horizontal strip. /// /// If an entire strip is cleared and it is either the top or bottom strip, then it will /// be removed, and the strip above or below (depending on position) will be tested as well. /// If the strip is in the center (not the top or bottom), then it will be reduced, but cannot /// be removed. /// </remarks> /// <param name="yOn">The y index start the tests at.</param> /// <param name="xOn">The x index to start the tests at.</param> #endregion public void ReduceGridAtIndex(int yOn, int xOn) { if (mTextures.Count == 0) return; // on the left side of the row #region move right along the row, remove textures and changing firstPaintedX[yOn] if (xOn == 0) { while (mTextures[yOn].Count > 0) { T objectAt = this.mTextures[yOn][0]; if ((objectAt == null && mBaseTexture == null) || (objectAt != null && objectAt.Equals(mBaseTexture))) { mTextures[yOn].RemoveAt(0); mFirstPaintedX[yOn] += this.mGridSpacingX; } else break; } } #endregion // on the right side of the row #region move left along the row, remove textures and changing lastPaintedX[yOn] else if (xOn == mTextures[yOn].Count - 1) { while (mTextures[yOn].Count > 0) { T objectAt = mTextures[yOn][mTextures[yOn].Count - 1]; if ((objectAt == null && mBaseTexture == null) || (objectAt != null && objectAt.Equals(mBaseTexture))) { mTextures[yOn].RemoveAt(mTextures[yOn].Count - 1); mLastPaintedX[yOn] -= this.mGridSpacingX; } else break; } } #endregion #region if we removed the entire row, and it is the top or bottom if (mTextures[yOn].Count == 0 && (yOn == mFirstPaintedX.Count - 1 || yOn == 0)) { mTextures.RemoveAt(yOn); mFirstPaintedX.RemoveAt(yOn); mLastPaintedX.RemoveAt(yOn); if (yOn == 0 && mTextures.Count != 0) { mFirstPaintedY += mGridSpacingY; ReduceGridAtIndex(0, 0); } else { mLastPaintedY -= mGridSpacingY; ReduceGridAtIndex(yOn - 1, 0); } } #endregion } public void ReplaceTexture(T oldTexture, T newTexture) { if ((mBaseTexture == null && oldTexture == null) || (mBaseTexture != null && mBaseTexture.Equals(oldTexture))) { mBaseTexture = newTexture; } for (int k = 0; k < mTextures.Count; k++) { List<T> fta = mTextures[k]; for (int i = 0; i < fta.Count; i++) { if ((fta[i] == null && oldTexture == null ) || (fta[i] != null && fta[i].Equals(oldTexture))) fta[i] = newTexture; } } TrimGrid(); } /* public void ReplaceTexture(string oldTexture, string newTexture) { if (mBaseTexture.fileName == oldTexture) { mBaseTexture = spriteManager.AddTexture(newTexture); } foreach (List<Texture2D> fta in mTextures) { for (int i = 0; i < fta.Count; i++) { if (fta[i].fileName == oldTexture) fta[i] = spriteManager.AddTexture(newTexture); } } TrimGrid(); } */ public void ScaleBy(double scaleValue) { GridSpacingX = (float)(mGridSpacingX * scaleValue); GridSpacingY = (float)(mGridSpacingY * scaleValue); mFirstPaintedY = (float)(mFirstPaintedY * scaleValue); mLastPaintedY = (float)(mLastPaintedY * scaleValue); mXOffset = (float)(mXOffset * scaleValue); mYOffset = (float)(mYOffset * scaleValue); for (int i = 0; i < mFirstPaintedX.Count; i++) { mFirstPaintedX[i] = (float)(mFirstPaintedX[i] * scaleValue); mLastPaintedX[i] = (float)(mLastPaintedX[i] * scaleValue); } } public void SetFrom(TextureGrid<T> instanceToSetFrom) { mBaseTexture = instanceToSetFrom.mBaseTexture; mTextures = new List<List<T>>(); for (int i = 0; i < instanceToSetFrom.mTextures.Count; i++ ) { mTextures.Add(new List<T>(instanceToSetFrom.mTextures[i])); } mFirstPaintedX = new List<float>(instanceToSetFrom.mFirstPaintedX); mLastPaintedX = new List<float>(instanceToSetFrom.mLastPaintedX); mFirstPaintedY = instanceToSetFrom.mFirstPaintedY; mLastPaintedY = instanceToSetFrom.mLastPaintedY; mXOffset = instanceToSetFrom.mXOffset; mYOffset = instanceToSetFrom.mYOffset; mGridSpacingX = instanceToSetFrom.mGridSpacingX; mGridSpacingY = instanceToSetFrom.mGridSpacingY; mSpaceHalfX = instanceToSetFrom.mSpaceHalfX; mSpaceHalfY = instanceToSetFrom.mSpaceHalfY; mSpaceFourthX = instanceToSetFrom.mSpaceFourthX; mSpaceFourthY = instanceToSetFrom.mSpaceFourthY; } #region XML Docs /// <summary> /// Checks the boundaries of the grid and removes any references to textures that match the base Texture2D. /// </summary> /// <remarks> /// This method is called automatically by the ReplaceTexture method so that the structure /// stays as small as possible afterchanges have been made. /// </remarks> #endregion public void TrimGrid() { TrimGrid(float.NegativeInfinity, float.PositiveInfinity); } public void TrimGrid(float minimumX, float maximumX) { // begin at the top of the grid and move down for (int yOn = mTextures.Count - 1; yOn > -1; yOn--) { /* The ReduceGridAtIndex will not only reduce off of the left and right side, but * it will remove entire rows. If a row is removed, the method will recur and move * down one row. It will continue doing so until it no longer removes an enire row or until * all rows have been remvoed. * * Because of this, it is possible that more than one row will be removed during the method call. * Therefore, there needs to be an if statement making sure that row[yOn] exists */ while (yOn < mTextures.Count && mTextures[yOn].Count > 0 && mFirstPaintedX[yOn] < minimumX) { mTextures[yOn].RemoveAt(0); mFirstPaintedX[yOn] += this.mGridSpacingX; } while (yOn < mTextures.Count && mTextures[yOn].Count > 0 && mLastPaintedX[yOn] > maximumX) { mTextures[yOn].RemoveAt(mTextures[yOn].Count - 1); mLastPaintedX[yOn] -= this.mGridSpacingX; } if (yOn < mTextures.Count && mTextures.Count > 0) { ReduceGridAtIndex(yOn, 0); } if (yOn < mTextures.Count && mTextures.Count > 0 && mTextures[yOn].Count > 0) ReduceGridAtIndex(yOn, mTextures[yOn].Count - 1); } } public override string ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append("BaseTexture:").Append(mBaseTexture.ToString()); sb.Append("\nNumTextureRows:").Append(mTextures.Count); sb.Append("\nfirstPaintedY:").Append(mFirstPaintedY); sb.Append("\nlastPaintedY:").Append(mLastPaintedY).Append("\n"); return sb.ToString(); //return base.ToString(); } #endregion internal void ChopOffBottom() { mTextures.RemoveAt(0); mFirstPaintedX.RemoveAt(0); mLastPaintedX.RemoveAt(0); mFirstPaintedY += mGridSpacingY; } internal void ChopOffTop() { int lastIndex = mTextures.Count - 1; mTextures.RemoveAt(lastIndex); mFirstPaintedX.RemoveAt(lastIndex); mLastPaintedX.RemoveAt(lastIndex); mLastPaintedY -= mGridSpacingY; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Xunit; namespace System.Collections.Immutable.Test { public class ImmutableArrayBuilderTest : SimpleElementImmutablesTestBase { [Fact] public void CreateBuilderDefaultCapacity() { var builder = ImmutableArray.CreateBuilder<int>(); Assert.NotNull(builder); Assert.NotSame(builder, ImmutableArray.CreateBuilder<int>()); } [Fact] public void CreateBuilderInvalidCapacity() { Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateBuilder<int>(-1)); } [Fact] public void NormalConstructionValueType() { var builder = ImmutableArray.CreateBuilder<int>(3); Assert.Equal(0, builder.Count); Assert.False(((ICollection<int>)builder).IsReadOnly); for (int i = 0; i < builder.Count; i++) { Assert.Equal(0, builder[i]); } builder.Add(5); builder.Add(6); builder.Add(7); Assert.Equal(5, builder[0]); Assert.Equal(6, builder[1]); Assert.Equal(7, builder[2]); } [Fact] public void NormalConstructionRefType() { #if NET45PLUS var builder = ImmutableArray.CreateBuilder<GenericParameterHelper>(3); #else var builder = new ImmutableArray<GenericParameterHelper>.Builder(3); #endif Assert.Equal(0, builder.Count); Assert.False(((ICollection<GenericParameterHelper>)builder).IsReadOnly); for (int i = 0; i < builder.Count; i++) { Assert.Null(builder[i]); } builder.Add(new GenericParameterHelper(5)); builder.Add(new GenericParameterHelper(6)); builder.Add(new GenericParameterHelper(7)); Assert.Equal(5, builder[0].Data); Assert.Equal(6, builder[1].Data); Assert.Equal(7, builder[2].Data); } [Fact] public void AddRangeIEnumerable() { #if NET45PLUS var builder = ImmutableArray.CreateBuilder<int>(2); #else var builder = new ImmutableArray<int>.Builder(2); #endif builder.AddRange((IEnumerable<int>)new[] { 1 }); Assert.Equal(1, builder.Count); builder.AddRange((IEnumerable<int>)new[] { 2 }); Assert.Equal(2, builder.Count); // Exceed capacity builder.AddRange(Enumerable.Range(3, 2)); // use an enumerable without a breakable Count Assert.Equal(4, builder.Count); Assert.Equal(Enumerable.Range(1, 4), builder); } [Fact] public void Add() { var builder = ImmutableArray.CreateBuilder<int>(0); builder.Add(1); builder.Add(2); Assert.Equal(new int[] { 1, 2 }, builder); Assert.Equal(2, builder.Count); builder = ImmutableArray.CreateBuilder<int>(1); builder.Add(1); builder.Add(2); Assert.Equal(new int[] { 1, 2 }, builder); Assert.Equal(2, builder.Count); builder = ImmutableArray.CreateBuilder<int>(2); builder.Add(1); builder.Add(2); Assert.Equal(new int[] { 1, 2 }, builder); Assert.Equal(2, builder.Count); } [Fact] public void AddRangeBuilder() { #if NET45PLUS var builder1 = ImmutableArray.CreateBuilder<int>(2); var builder2 = ImmutableArray.CreateBuilder<int>(2); #else var builder1 = new ImmutableArray<int>.Builder(2); var builder2 = new ImmutableArray<int>.Builder(2); #endif builder1.AddRange(builder2); Assert.Equal(0, builder1.Count); Assert.Equal(0, builder2.Count); builder2.Add(1); builder2.Add(2); builder1.AddRange(builder2); Assert.Equal(2, builder1.Count); Assert.Equal(2, builder2.Count); Assert.Equal(new[] { 1, 2 }, builder1); } [Fact] public void AddRangeImmutableArray() { #if NET45PLUS var builder1 = ImmutableArray.CreateBuilder<int>(2); #else var builder1 = new ImmutableArray<int>.Builder(2); #endif var array = ImmutableArray.Create(1, 2, 3); builder1.AddRange(array); Assert.Equal(new[] { 1, 2, 3 }, builder1); } [Fact] public void AddRangeDerivedArray() { #if NET45PLUS var builder = ImmutableArray.CreateBuilder<object>(); #else var builder = new ImmutableArray<object>.Builder(); #endif builder.AddRange(new[] { "a", "b" }); Assert.Equal(new[] { "a", "b" }, builder); } [Fact] public void AddRangeDerivedImmutableArray() { #if NET45PLUS var builder = ImmutableArray.CreateBuilder<object>(); #else var builder = new ImmutableArray<object>.Builder(); #endif builder.AddRange(new[] { "a", "b" }.ToImmutableArray()); Assert.Equal(new[] { "a", "b" }, builder); } [Fact] public void AddRangeDerivedBuilder() { #if NET45PLUS var builder = ImmutableArray.CreateBuilder<string>(); #else var builder = new ImmutableArray<string>.Builder(); #endif builder.AddRange(new[] { "a", "b" }); #if NET45PLUS var builderBase = ImmutableArray.CreateBuilder<object>(); #else var builderBase = new ImmutableArray<object>.Builder(); #endif builderBase.AddRange(builder); Assert.Equal(new[] { "a", "b" }, builderBase); } [Fact] public void Contains() { #if NET45PLUS var builder = ImmutableArray.CreateBuilder<int>(); #else var builder = new ImmutableArray<int>.Builder(); #endif Assert.False(builder.Contains(1)); builder.Add(1); Assert.True(builder.Contains(1)); } [Fact] public void IndexOf() { IndexOfTests.IndexOfTest( seq => (ImmutableArray<int>.Builder)this.GetEnumerableOf(seq), (b, v) => b.IndexOf(v), (b, v, i) => b.IndexOf(v, i), (b, v, i, c) => b.IndexOf(v, i, c), (b, v, i, c, eq) => b.IndexOf(v, i, c, eq)); } [Fact] public void LastIndexOf() { IndexOfTests.LastIndexOfTest( seq => (ImmutableArray<int>.Builder)this.GetEnumerableOf(seq), (b, v) => b.LastIndexOf(v), (b, v, eq) => b.LastIndexOf(v, b.Count > 0 ? b.Count - 1 : 0, b.Count, eq), (b, v, i) => b.LastIndexOf(v, i), (b, v, i, c) => b.LastIndexOf(v, i, c), (b, v, i, c, eq) => b.LastIndexOf(v, i, c, eq)); } [Fact] public void Insert() { #if NET45PLUS var builder = ImmutableArray.CreateBuilder<int>(); #else var builder = new ImmutableArray<int>.Builder(); #endif builder.AddRange(1, 2, 3); builder.Insert(1, 4); builder.Insert(4, 5); Assert.Equal(new[] { 1, 4, 2, 3, 5 }, builder); Assert.Throws<ArgumentOutOfRangeException>(() => builder.Insert(-1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => builder.Insert(builder.Count + 1, 0)); } [Fact] public void Remove() { #if NET45PLUS var builder = ImmutableArray.CreateBuilder<int>(); #else var builder = new ImmutableArray<int>.Builder(); #endif builder.AddRange(1, 2, 3, 4); Assert.True(builder.Remove(1)); Assert.False(builder.Remove(6)); Assert.Equal(new[] { 2, 3, 4 }, builder); Assert.True(builder.Remove(3)); Assert.Equal(new[] { 2, 4 }, builder); Assert.True(builder.Remove(4)); Assert.Equal(new[] { 2 }, builder); Assert.True(builder.Remove(2)); Assert.Equal(0, builder.Count); } [Fact] public void RemoveAt() { #if NET45PLUS var builder = ImmutableArray.CreateBuilder<int>(); #else var builder = new ImmutableArray<int>.Builder(); #endif builder.AddRange(1, 2, 3, 4); builder.RemoveAt(0); Assert.Throws<ArgumentOutOfRangeException>(() => builder.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => builder.RemoveAt(3)); Assert.Equal(new[] { 2, 3, 4 }, builder); builder.RemoveAt(1); Assert.Equal(new[] { 2, 4 }, builder); builder.RemoveAt(1); Assert.Equal(new[] { 2 }, builder); builder.RemoveAt(0); Assert.Equal(0, builder.Count); } [Fact] public void ReverseContents() { #if NET45PLUS var builder = ImmutableArray.CreateBuilder<int>(); #else var builder = new ImmutableArray<int>.Builder(); #endif builder.AddRange(1, 2, 3, 4); builder.Reverse(); Assert.Equal(new[] { 4, 3, 2, 1 }, builder); builder.RemoveAt(0); builder.Reverse(); Assert.Equal(new[] { 1, 2, 3 }, builder); builder.RemoveAt(0); builder.Reverse(); Assert.Equal(new[] { 3, 2 }, builder); builder.RemoveAt(0); builder.Reverse(); Assert.Equal(new[] { 2 }, builder); builder.RemoveAt(0); builder.Reverse(); Assert.Equal(new int[0], builder); } [Fact] public void Sort() { #if NET45PLUS var builder = ImmutableArray.CreateBuilder<int>(); #else var builder = new ImmutableArray<int>.Builder(); #endif builder.AddRange(2, 4, 1, 3); builder.Sort(); Assert.Equal(new[] { 1, 2, 3, 4 }, builder); } [Fact] public void SortNullComparer() { #if NET45PLUS var builder = ImmutableArray.CreateBuilder<int>(); #else var builder = new ImmutableArray<int>.Builder(); #endif builder.AddRange(2, 4, 1, 3); builder.Sort(null); Assert.Equal(new[] { 1, 2, 3, 4 }, builder); } [Fact] public void SortOneElementArray() { int[] resultantArray = new[] { 4 }; #if NET45PLUS var builder1 = ImmutableArray.CreateBuilder<int>(); #else var builder1 = new ImmutableArray<int>.Builder(); #endif builder1.Add(4); builder1.Sort(); Assert.Equal(resultantArray, builder1); #if NET45PLUS var builder2 = ImmutableArray.CreateBuilder<int>(); #else var builder2 = new ImmutableArray<int>.Builder(); #endif builder2.Add(4); builder2.Sort(Comparer<int>.Default); Assert.Equal(resultantArray, builder2); #if NET45PLUS var builder3 = ImmutableArray.CreateBuilder<int>(); #else var builder3 = new ImmutableArray<int>.Builder(); #endif builder3.Add(4); builder3.Sort(0, 1, Comparer<int>.Default); Assert.Equal(resultantArray, builder3); } [Fact] public void SortRange() { #if NET45PLUS var builder = ImmutableArray.CreateBuilder<int>(); #else var builder = new ImmutableArray<int>.Builder(); #endif builder.AddRange(2, 4, 1, 3); Assert.Throws<ArgumentOutOfRangeException>(() => builder.Sort(-1, 2, Comparer<int>.Default)); Assert.Throws<ArgumentOutOfRangeException>(() => builder.Sort(1, 4, Comparer<int>.Default)); Assert.Throws<ArgumentOutOfRangeException>(() => builder.Sort(0, -1, Comparer<int>.Default)); builder.Sort(builder.Count, 0, Comparer<int>.Default); Assert.Equal(new int[] { 2, 4, 1, 3 }, builder); builder.Sort(1, 2, Comparer<int>.Default); Assert.Equal(new[] { 2, 1, 4, 3 }, builder); } [Fact] public void SortComparer() { #if NET45PLUS var builder1 = ImmutableArray.CreateBuilder<string>(); var builder2 = ImmutableArray.CreateBuilder<string>(); #else var builder1 = new ImmutableArray<string>.Builder(); var builder2 = new ImmutableArray<string>.Builder(); #endif builder1.AddRange("c", "B", "a"); builder2.AddRange("c", "B", "a"); builder1.Sort(StringComparer.OrdinalIgnoreCase); builder2.Sort(StringComparer.Ordinal); Assert.Equal(new[] { "a", "B", "c" }, builder1); Assert.Equal(new[] { "B", "a", "c" }, builder2); } [Fact] public void Count() { #if NET45PLUS var builder = ImmutableArray.CreateBuilder<int>(3); #else var builder = new ImmutableArray<int>.Builder(3); #endif // Initial count is at zero, which is less than capacity. Assert.Equal(0, builder.Count); // Expand the accessible region of the array by increasing the count, but still below capacity. builder.Count = 2; Assert.Equal(2, builder.Count); Assert.Equal(2, builder.ToList().Count); Assert.Equal(0, builder[0]); Assert.Equal(0, builder[1]); Assert.Throws<IndexOutOfRangeException>(() => builder[2]); // Expand the accessible region of the array beyond the current capacity. builder.Count = 4; Assert.Equal(4, builder.Count); Assert.Equal(4, builder.ToList().Count); Assert.Equal(0, builder[0]); Assert.Equal(0, builder[1]); Assert.Equal(0, builder[2]); Assert.Equal(0, builder[3]); Assert.Throws<IndexOutOfRangeException>(() => builder[4]); } [Fact] public void CountContract() { #if NET45PLUS var builder = ImmutableArray.CreateBuilder<int>(100); #else var builder = new ImmutableArray<int>.Builder(100); #endif builder.AddRange(Enumerable.Range(1, 100)); builder.Count = 10; Assert.Equal(Enumerable.Range(1, 10), builder); builder.Count = 100; Assert.Equal(Enumerable.Range(1, 10).Concat(new int[90]), builder); } [Fact] public void IndexSetter() { #if NET45PLUS var builder = ImmutableArray.CreateBuilder<int>(); #else var builder = new ImmutableArray<int>.Builder(); #endif Assert.Throws<IndexOutOfRangeException>(() => builder[0] = 1); Assert.Throws<IndexOutOfRangeException>(() => builder[-1] = 1); builder.Count = 1; builder[0] = 2; Assert.Equal(2, builder[0]); builder.Count = 10; builder[9] = 3; Assert.Equal(3, builder[9]); builder.Count = 2; Assert.Equal(2, builder[0]); Assert.Throws<IndexOutOfRangeException>(() => builder[2]); } [Fact] public void ToImmutable() { #if NET45PLUS var builder = ImmutableArray.CreateBuilder<int>(); #else var builder = new ImmutableArray<int>.Builder(); #endif builder.AddRange(1, 2, 3); ImmutableArray<int> array = builder.ToImmutable(); Assert.Equal(1, array[0]); Assert.Equal(2, array[1]); Assert.Equal(3, array[2]); // Make sure that subsequent mutation doesn't impact the immutable array. builder[1] = 5; Assert.Equal(5, builder[1]); Assert.Equal(2, array[1]); builder.Clear(); Assert.True(builder.ToImmutable().IsEmpty); } [Fact] public void Clear() { #if NET45PLUS var builder = ImmutableArray.CreateBuilder<int>(2); #else var builder = new ImmutableArray<int>.Builder(2); #endif builder.Add(1); builder.Add(1); builder.Clear(); Assert.Equal(0, builder.Count); Assert.Throws<IndexOutOfRangeException>(() => builder[0]); } [Fact] public void MutationsSucceedAfterToImmutable() { #if NET45PLUS var builder = ImmutableArray.CreateBuilder<int>(1); #else var builder = new ImmutableArray<int>.Builder(1); #endif builder.Add(1); var immutable = builder.ToImmutable(); builder[0] = 0; Assert.Equal(0, builder[0]); Assert.Equal(1, immutable[0]); } [Fact] public void Enumerator() { #if NET45PLUS var empty = ImmutableArray.CreateBuilder<int>(0); #else var empty = new ImmutableArray<int>.Builder(0); #endif var enumerator = empty.GetEnumerator(); Assert.False(enumerator.MoveNext()); #if NET45PLUS var manyElements = ImmutableArray.CreateBuilder<int>(3); #else var manyElements = new ImmutableArray<int>.Builder(3); #endif manyElements.AddRange(1, 2, 3); enumerator = manyElements.GetEnumerator(); Assert.True(enumerator.MoveNext()); Assert.Equal(1, enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(2, enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(3, enumerator.Current); Assert.False(enumerator.MoveNext()); } [Fact] public void IEnumerator() { #if NET45PLUS var empty = ImmutableArray.CreateBuilder<int>(0); #else var empty = new ImmutableArray<int>.Builder(0); #endif var enumerator = ((IEnumerable<int>)empty).GetEnumerator(); Assert.False(enumerator.MoveNext()); #if NET45PLUS var manyElements = ImmutableArray.CreateBuilder<int>(3); #else var manyElements = new ImmutableArray<int>.Builder(3); #endif manyElements.AddRange(1, 2, 3); enumerator = ((IEnumerable<int>)manyElements).GetEnumerator(); Assert.True(enumerator.MoveNext()); Assert.Equal(1, enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(2, enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(3, enumerator.Current); Assert.False(enumerator.MoveNext()); } [Fact] public void MoveToImmutableNormal() { var builder = CreateBuilderWithCount<string>(2); Assert.Equal(2, builder.Count); Assert.Equal(2, builder.Capacity); builder[1] = "b"; builder[0] = "a"; var array = builder.MoveToImmutable(); Assert.Equal(new[] { "a", "b" }, array); Assert.Equal(0, builder.Count); Assert.Equal(0, builder.Capacity); } [Fact] public void MoveToImmutableRepeat() { var builder = CreateBuilderWithCount<string>(2); builder[0] = "a"; builder[1] = "b"; var array1 = builder.MoveToImmutable(); var array2 = builder.MoveToImmutable(); Assert.Equal(new[] { "a", "b" }, array1); Assert.Equal(0, array2.Length); } [Fact] public void MoveToImmutablePartialFill() { var builder = ImmutableArray.CreateBuilder<int>(4); builder.Add(42); builder.Add(13); Assert.Equal(4, builder.Capacity); Assert.Equal(2, builder.Count); Assert.Throws(typeof(InvalidOperationException), () => builder.MoveToImmutable()); } [Fact] public void MoveToImmutablePartialFillWithCountUpdate() { var builder = ImmutableArray.CreateBuilder<int>(4); builder.Add(42); builder.Add(13); Assert.Equal(4, builder.Capacity); Assert.Equal(2, builder.Count); builder.Count = builder.Capacity; var array = builder.MoveToImmutable(); Assert.Equal(new[] { 42, 13, 0, 0 }, array); } [Fact] public void MoveToImmutableThenUse() { var builder = CreateBuilderWithCount<string>(2); Assert.Equal(2, builder.MoveToImmutable().Length); Assert.Equal(0, builder.Capacity); builder.Add("a"); builder.Add("b"); Assert.Equal(2, builder.Count); Assert.True(builder.Capacity >= 2); Assert.Equal(new[] { "a", "b" }, builder.MoveToImmutable()); } [Fact] public void MoveToImmutableAfterClear() { var builder = CreateBuilderWithCount<string>(2); builder[0] = "a"; builder[1] = "b"; builder.Clear(); Assert.Throws(typeof(InvalidOperationException), () => builder.MoveToImmutable()); } [Fact] public void MoveToImmutableAddToCapacity() { var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 3); for (int i = 0; i < builder.Capacity; i++) { builder.Add(i); } Assert.Equal(new[] { 0, 1, 2 }, builder.MoveToImmutable()); } [Fact] public void MoveToImmutableInsertToCapacity() { var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 3); for (int i = 0; i < builder.Capacity; i++) { builder.Insert(i, i); } Assert.Equal(new[] { 0, 1, 2 }, builder.MoveToImmutable()); } [Fact] public void MoveToImmutableAddRangeToCapcity() { var array = new[] { 1, 2, 3, 4, 5 }; var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: array.Length); builder.AddRange(array); Assert.Equal(array, builder.MoveToImmutable()); } [Fact] public void MoveToImmutableAddRemoveAddToCapacity() { var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 3); for (int i = 0; i < builder.Capacity; i++) { builder.Add(i); builder.RemoveAt(i); builder.Add(i); } Assert.Equal(new[] { 0, 1, 2 }, builder.MoveToImmutable()); } [Fact] public void CapacitySetToZero() { var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 10); builder.Capacity = 0; Assert.Equal(0, builder.Capacity); Assert.Equal(new int[] { }, builder.ToArray()); } [Fact] public void CapacitySetToLessThanCount() { var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 10); builder.Add(1); builder.Add(1); Assert.Throws(typeof(ArgumentException), () => builder.Capacity = 1); } [Fact] public void CapacitySetToCount() { var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 10); builder.Add(1); builder.Add(2); builder.Capacity = builder.Count; Assert.Equal(2, builder.Capacity); Assert.Equal(new[] { 1, 2 }, builder.ToArray()); } [Fact] public void CapacitySetToCapacity() { var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 10); builder.Add(1); builder.Add(2); builder.Capacity = builder.Capacity; Assert.Equal(10, builder.Capacity); Assert.Equal(new[] { 1, 2 }, builder.ToArray()); } [Fact] public void CapacitySetToBiggerCapacity() { var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 10); builder.Add(1); builder.Add(2); builder.Capacity = 20; Assert.Equal(20, builder.Capacity); Assert.Equal(2, builder.Count); Assert.Equal(new[] { 1, 2 }, builder.ToArray()); } [Fact] public void DebuggerAttributesValid() { DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableArray.CreateBuilder<int>()); DebuggerAttributes.ValidateDebuggerTypeProxyProperties(ImmutableArray.CreateBuilder<string>(4)); } private static ImmutableArray<T>.Builder CreateBuilderWithCount<T>(int count) { var builder = ImmutableArray.CreateBuilder<T>(count); builder.Count = count; return builder; } protected override IEnumerable<T> GetEnumerableOf<T>(params T[] contents) { #if NET45PLUS var builder = ImmutableArray.CreateBuilder<T>(contents.Length); #else var builder = new ImmutableArray<T>.Builder(contents.Length); #endif builder.AddRange(contents); return builder; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------ //------------------------------------------------------------ using System.IO; using System.Text; using System.Runtime.Serialization; using System.Security; using System.Threading.Tasks; namespace System.Xml { internal abstract class XmlStreamNodeWriter : XmlNodeWriter { private Stream _stream; private byte[] _buffer; private int _offset; private bool _ownsStream; private const int bufferLength = 512; private const int maxBytesPerChar = 3; private Encoding _encoding; private static UTF8Encoding s_UTF8Encoding = new UTF8Encoding(false, true); protected XmlStreamNodeWriter() { _buffer = new byte[bufferLength]; } protected void SetOutput(Stream stream, bool ownsStream, Encoding encoding) { _stream = stream; _ownsStream = ownsStream; _offset = 0; _encoding = encoding; } // Getting/Setting the Stream exists for fragmenting public Stream Stream { get { return _stream; } set { _stream = value; } } // StreamBuffer/BufferOffset exists only for the BinaryWriter to fix up nodes public byte[] StreamBuffer { get { return _buffer; } } public int BufferOffset { get { return _offset; } } public int Position { get { return (int)_stream.Position + _offset; } } private int GetByteCount(char[] chars) { if (_encoding == null) { return s_UTF8Encoding.GetByteCount(chars); } else { return _encoding.GetByteCount(chars); } } protected byte[] GetBuffer(int count, out int offset) { DiagnosticUtility.DebugAssert(count >= 0 && count <= bufferLength, ""); int bufferOffset = _offset; if (bufferOffset + count <= bufferLength) { offset = bufferOffset; } else { FlushBuffer(); offset = 0; } #if DEBUG DiagnosticUtility.DebugAssert(offset + count <= bufferLength, ""); for (int i = 0; i < count; i++) { _buffer[offset + i] = (byte)'<'; } #endif return _buffer; } protected async Task<BytesWithOffset> GetBufferAsync(int count) { int offset; DiagnosticUtility.DebugAssert(count >= 0 && count <= bufferLength, ""); int bufferOffset = _offset; if (bufferOffset + count <= bufferLength) { offset = bufferOffset; } else { await FlushBufferAsync().ConfigureAwait(false); offset = 0; } #if DEBUG DiagnosticUtility.DebugAssert(offset + count <= bufferLength, ""); for (int i = 0; i < count; i++) { _buffer[offset + i] = (byte)'<'; } #endif return new BytesWithOffset(_buffer, offset); } protected void Advance(int count) { DiagnosticUtility.DebugAssert(_offset + count <= bufferLength, ""); _offset += count; } private void EnsureByte() { if (_offset >= bufferLength) { FlushBuffer(); } } protected void WriteByte(byte b) { EnsureByte(); _buffer[_offset++] = b; } protected Task WriteByteAsync(byte b) { if (_offset >= bufferLength) { return FlushBufferAndWriteByteAsync(b); } else { _buffer[_offset++] = b; return Task.CompletedTask; } } private async Task FlushBufferAndWriteByteAsync(byte b) { await FlushBufferAsync().ConfigureAwait(false); _buffer[_offset++] = b; } protected void WriteByte(char ch) { DiagnosticUtility.DebugAssert(ch < 0x80, ""); WriteByte((byte)ch); } protected Task WriteByteAsync(char ch) { DiagnosticUtility.DebugAssert(ch < 0x80, ""); return WriteByteAsync((byte)ch); } protected void WriteBytes(byte b1, byte b2) { byte[] buffer = _buffer; int offset = _offset; if (offset + 1 >= bufferLength) { FlushBuffer(); offset = 0; } buffer[offset + 0] = b1; buffer[offset + 1] = b2; _offset += 2; } protected Task WriteBytesAsync(byte b1, byte b2) { if (_offset + 1 >= bufferLength) { return FlushAndWriteBytesAsync(b1, b2); } else { _buffer[_offset++] = b1; _buffer[_offset++] = b2; return Task.CompletedTask; } } private async Task FlushAndWriteBytesAsync(byte b1, byte b2) { await FlushBufferAsync().ConfigureAwait(false); _buffer[_offset++] = b1; _buffer[_offset++] = b2; } protected void WriteBytes(char ch1, char ch2) { DiagnosticUtility.DebugAssert(ch1 < 0x80 && ch2 < 0x80, ""); WriteBytes((byte)ch1, (byte)ch2); } protected Task WriteBytesAsync(char ch1, char ch2) { DiagnosticUtility.DebugAssert(ch1 < 0x80 && ch2 < 0x80, ""); return WriteBytesAsync((byte)ch1, (byte)ch2); } public void WriteBytes(byte[] byteBuffer, int byteOffset, int byteCount) { if (byteCount < bufferLength) { int offset; byte[] buffer = GetBuffer(byteCount, out offset); Buffer.BlockCopy(byteBuffer, byteOffset, buffer, offset, byteCount); Advance(byteCount); } else { FlushBuffer(); _stream.Write(byteBuffer, byteOffset, byteCount); } } /// <SecurityNote> /// Critical - contains unsafe code /// caller needs to validate arguments /// </SecurityNote> [SecurityCritical] unsafe protected void UnsafeWriteBytes(byte* bytes, int byteCount) { FlushBuffer(); byte[] buffer = _buffer; while (byteCount >= bufferLength) { for (int i = 0; i < bufferLength; i++) buffer[i] = bytes[i]; _stream.Write(buffer, 0, bufferLength); bytes += bufferLength; byteCount -= bufferLength; } { for (int i = 0; i < byteCount; i++) buffer[i] = bytes[i]; _stream.Write(buffer, 0, byteCount); } } /// <SecurityNote> /// Critical - contains unsafe code /// Safe - unsafe code is effectively encapsulated, all inputs are validated /// </SecurityNote> [SecuritySafeCritical] unsafe protected void WriteUTF8Char(int ch) { if (ch < 0x80) { WriteByte((byte)ch); } else if (ch <= char.MaxValue) { char* chars = stackalloc char[1]; chars[0] = (char)ch; UnsafeWriteUTF8Chars(chars, 1); } else { SurrogateChar surrogateChar = new SurrogateChar(ch); char* chars = stackalloc char[2]; chars[0] = surrogateChar.HighChar; chars[1] = surrogateChar.LowChar; UnsafeWriteUTF8Chars(chars, 2); } } protected void WriteUTF8Chars(byte[] chars, int charOffset, int charCount) { if (charCount < bufferLength) { int offset; byte[] buffer = GetBuffer(charCount, out offset); Buffer.BlockCopy(chars, charOffset, buffer, offset, charCount); Advance(charCount); } else { FlushBuffer(); _stream.Write(chars, charOffset, charCount); } } /// <SecurityNote> /// Critical - contains unsafe code /// Safe - unsafe code is effectively encapsulated, all inputs are validated /// </SecurityNote> [SecuritySafeCritical] unsafe protected void WriteUTF8Chars(string value) { int count = value.Length; if (count > 0) { fixed (char* chars = value) { UnsafeWriteUTF8Chars(chars, count); } } } /// <SecurityNote> /// Critical - contains unsafe code /// caller needs to validate arguments /// </SecurityNote> [SecurityCritical] unsafe protected void UnsafeWriteUTF8Chars(char* chars, int charCount) { const int charChunkSize = bufferLength / maxBytesPerChar; while (charCount > charChunkSize) { int offset; int chunkSize = charChunkSize; if ((int)(chars[chunkSize - 1] & 0xFC00) == 0xD800) // This is a high surrogate chunkSize--; byte[] buffer = GetBuffer(chunkSize * maxBytesPerChar, out offset); Advance(UnsafeGetUTF8Chars(chars, chunkSize, buffer, offset)); charCount -= chunkSize; chars += chunkSize; } if (charCount > 0) { int offset; byte[] buffer = GetBuffer(charCount * maxBytesPerChar, out offset); Advance(UnsafeGetUTF8Chars(chars, charCount, buffer, offset)); } } /// <SecurityNote> /// Critical - contains unsafe code /// caller needs to validate arguments /// </SecurityNote> [SecurityCritical] unsafe protected void UnsafeWriteUnicodeChars(char* chars, int charCount) { const int charChunkSize = bufferLength / 2; while (charCount > charChunkSize) { int offset; int chunkSize = charChunkSize; if ((int)(chars[chunkSize - 1] & 0xFC00) == 0xD800) // This is a high surrogate chunkSize--; byte[] buffer = GetBuffer(chunkSize * 2, out offset); Advance(UnsafeGetUnicodeChars(chars, chunkSize, buffer, offset)); charCount -= chunkSize; chars += chunkSize; } if (charCount > 0) { int offset; byte[] buffer = GetBuffer(charCount * 2, out offset); Advance(UnsafeGetUnicodeChars(chars, charCount, buffer, offset)); } } /// <SecurityNote> /// Critical - contains unsafe code /// caller needs to validate arguments /// </SecurityNote> [SecurityCritical] unsafe protected int UnsafeGetUnicodeChars(char* chars, int charCount, byte[] buffer, int offset) { char* charsMax = chars + charCount; while (chars < charsMax) { char value = *chars++; buffer[offset++] = (byte)value; value >>= 8; buffer[offset++] = (byte)value; } return charCount * 2; } /// <SecurityNote> /// Critical - contains unsafe code /// caller needs to validate arguments /// </SecurityNote> [SecurityCritical] unsafe protected int UnsafeGetUTF8Length(char* chars, int charCount) { char* charsMax = chars + charCount; while (chars < charsMax) { if (*chars >= 0x80) break; chars++; } if (chars == charsMax) return charCount; char[] chArray = new char[charsMax - chars]; for (int i = 0; i < chArray.Length; i++) { chArray[i] = chars[i]; } return (int)(chars - (charsMax - charCount)) + GetByteCount(chArray); } /// <SecurityNote> /// Critical - contains unsafe code /// caller needs to validate arguments /// </SecurityNote> [SecurityCritical] unsafe protected int UnsafeGetUTF8Chars(char* chars, int charCount, byte[] buffer, int offset) { if (charCount > 0) { fixed (byte* _bytes = &buffer[offset]) { byte* bytes = _bytes; byte* bytesMax = &bytes[buffer.Length - offset]; char* charsMax = &chars[charCount]; while (true) { while (chars < charsMax) { char t = *chars; if (t >= 0x80) break; *bytes = (byte)t; bytes++; chars++; } if (chars >= charsMax) break; char* charsStart = chars; while (chars < charsMax && *chars >= 0x80) { chars++; } string tmp = new string(charsStart, 0, (int)(chars - charsStart)); byte[] newBytes = _encoding != null ? _encoding.GetBytes(tmp) : s_UTF8Encoding.GetBytes(tmp); int toCopy = Math.Min(newBytes.Length, (int)(bytesMax - bytes)); Array.Copy(newBytes, 0, buffer, (int)(bytes - _bytes) + offset, toCopy); bytes += toCopy; if (chars >= charsMax) break; } return (int)(bytes - _bytes); } } return 0; } protected virtual void FlushBuffer() { if (_offset != 0) { _stream.Write(_buffer, 0, _offset); _offset = 0; } } protected virtual Task FlushBufferAsync() { if (_offset != 0) { var task = _stream.WriteAsync(_buffer, 0, _offset); _offset = 0; return task; } return Task.CompletedTask; } public override void Flush() { FlushBuffer(); _stream.Flush(); } public override async Task FlushAsync() { await FlushBufferAsync().ConfigureAwait(false); await _stream.FlushAsync().ConfigureAwait(false); } public override void Close() { if (_stream != null) { if (_ownsStream) { _stream.Dispose(); } _stream = null; } } } }
/* * NPlot - A charting library for .NET * * LinePlot.cs * Copyright (C) 2003-2006 Matt Howlett and others. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of NPlot 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. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Windows.Forms; namespace NPlot { /// <summary> /// Encapsulates functionality for plotting data as a line chart. /// </summary> public class LinePlot : IPlot { private readonly LineData m_lineData; /// <summary> /// Gets or sets the data, or column name for the ordinate [y] axis. /// </summary> private IList<double> YData { get; set; } /// <summary> /// Gets or sets the data, or column name for the abscissa [x] axis. /// </summary> private IList<double> XData { get; set; } /// <summary> /// Constructor /// </summary> /// <param name="yData">the ordinate data to associate with this plot.</param> /// <param name="xData">the abscissa data to associate with this plot.</param> public LinePlot(IList<double> yData, IList<double> xData) { YData = yData; XData = xData; m_lineData = new LineData(xData, yData); } /// <summary> /// Draws the line plot on a GDI+ surface against the provided x and y axes. /// </summary> /// <param name="g">The GDI+ surface on which to draw.</param> /// <param name="xAxis">The X-Axis to draw against.</param> /// <param name="yAxis">The Y-Axis to draw against.</param> public void Draw(Graphics g, PhysicalAxis xAxis, PhysicalAxis yAxis) { try { double xVal, yVal; int pointCount = m_lineData.Count; if (pointCount == 0) return; Stopwatch sw = StepTimer.Start("Transform"); Transform2D t = new Transform2D(xAxis, yAxis); // clipping is now handled assigning a clip region in the // graphic object before this call if (pointCount == 1) { m_lineData.Get(0, out xVal, out yVal); PointF physical = t.Transform(xVal, yVal); g.DrawLine(Pen, physical.X - 0.5f, physical.Y, physical.X + 0.5f, physical.Y); } else { int index = 0; PointF[] points = new PointF[pointCount]; PointF lastPoint = new PointF(Single.NaN, Single.NaN); for (int i = 0; i < pointCount; ++i) { // check to see if any values null. If so, then continue. m_lineData.Get(i, out xVal, out yVal); if (!Double.IsNaN(xVal + yVal)) //Adding a NaN with anything yeilds NaN { const float GDIMax = 1000000000f; const float GDIMin = -1000000000f; PointF p1 = t.Transform(xVal, yVal); if (p1.X > GDIMax) p1.X = GDIMax; if (p1.X < GDIMin) p1.X = GDIMin; if (p1.Y > GDIMax) p1.Y = GDIMax; if (p1.Y < GDIMin) p1.Y = GDIMin; if (!float.IsNaN(p1.X) && !float.IsNaN(p1.Y)) { if (p1 != lastPoint) { lastPoint = p1; points[index] = p1; index++; } } } } //System.Drawing.Drawing2D.GraphicsPath graphicsPath = new System.Drawing.Drawing2D.GraphicsPath(); //graphicsPath.AddLines(points.ToArray()); //g.DrawPath(Pen, graphicsPath); //g.CompositingQuality = CompositingQuality.HighQuality; //g.SmoothingMode = SmoothingMode.HighQuality; StepTimer.Stop(sw); sw = StepTimer.Start("GDI+"); if (index == 0) return; else if (index == 1) { PointF physical = points[0]; g.DrawLine(Pen, physical.X - 0.5f, physical.Y, physical.X + 0.5f, physical.Y); return; } if (index == points.Length) { g.DrawLines(Pen, points); } else { PointF[] newArray = new PointF[index]; Array.Copy(points, 0, newArray, 0, index); g.DrawLines(Pen, newArray); } StepTimer.Stop(sw); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); throw; } } /// <summary> /// Returns an x-axis that is suitable for drawing this plot. /// </summary> /// <returns>A suitable x-axis.</returns> public DateTimeAxis SuggestXAxis() { return m_lineData.GetX(); } /// <summary> /// Returns a y-axis that is suitable for drawing this plot. /// </summary> /// <returns>A suitable y-axis.</returns> public LinearAxis SuggestYAxis() { LinearAxis a = m_lineData.GetY(); a.IncreaseRange(0.08); return a; } /// <summary> /// The pen used to draw the plot /// </summary> public Pen Pen { get => pen_; set => pen_ = value; } private Pen pen_ = new Pen(Color.Black); /// <summary> /// The color of the pen used to draw lines in this plot. /// </summary> public Color Color { set { if (pen_ != null) { pen_.Color = value; } else { pen_ = new Pen(value); } } get => pen_.Color; } } }
/* ==================================================================== 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.IO; using NPOI.HSSF.UserModel; using NPOI.OpenXml4Net.OPC; using NPOI.POIFS.FileSystem; using NPOI.Util; using NPOI.XSSF.UserModel; namespace NPOI.SS.UserModel { public enum ImportOption { NONE, /// <summary> /// Only Text and Formulas are imported. Pictures, Drawing, Styles etc. are all ignored. /// </summary> SheetContentOnly, /// <summary> /// Only Text, Comments and Formulas are imported. Pictures, Drawing, Styles etc. are all ignored. /// </summary> TextOnly, /// <summary> /// Everything is imported - this is the same as NONE. /// </summary> All, } /// <summary> /// Factory for creating the appropriate kind of Workbook /// (be it HSSFWorkbook or XSSFWorkbook), from the given input /// </summary> public class WorkbookFactory { /// <summary> /// Creates an HSSFWorkbook from the given POIFSFileSystem /// </summary> public static IWorkbook Create(POIFSFileSystem fs) { return new HSSFWorkbook(fs); } /** * Creates an HSSFWorkbook from the given NPOIFSFileSystem */ public static IWorkbook Create(NPOIFSFileSystem fs) { return new HSSFWorkbook(fs.Root, true); } /// <summary> /// Creates an XSSFWorkbook from the given OOXML Package /// </summary> public static IWorkbook Create(OPCPackage pkg) { return new XSSFWorkbook(pkg); } /// <summary> /// Creates the appropriate HSSFWorkbook / XSSFWorkbook from /// the given InputStream. The Stream is wraped inside a PushbackInputStream. /// </summary> /// <param name="inputStream">Input Stream of .xls or .xlsx file</param> /// <returns>IWorkbook depending on the input HSSFWorkbook or XSSFWorkbook is returned.</returns> // Your input stream MUST either support mark/reset, or // be wrapped as a {@link PushbackInputStream}! public static IWorkbook Create(Stream inputStream) { // If Clearly doesn't do mark/reset, wrap up //if (!inp.MarkSupported()) //{ // inp = new PushbackInputStream(inp, 8); //} inputStream = new PushbackStream(inputStream); if (POIFSFileSystem.HasPOIFSHeader(inputStream)) { return new HSSFWorkbook(inputStream); } inputStream.Position = 0; if (POIXMLDocument.HasOOXMLHeader(inputStream)) { return new XSSFWorkbook(OPCPackage.Open(inputStream)); } throw new ArgumentException("Your stream was neither an OLE2 stream, nor an OOXML stream."); } /** * Creates the appropriate HSSFWorkbook / XSSFWorkbook from * the given File, which must exist and be readable. * <p>Note that for Workbooks opened this way, it is not possible * to explicitly close the underlying File resource. */ public static IWorkbook Create(string file) { if (!File.Exists(file)) { throw new FileNotFoundException(file); } FileStream fStream = null; try { using (fStream = new FileStream(file, FileMode.Open, FileAccess.Read)) { IWorkbook wb = new HSSFWorkbook(fStream); return wb; } } catch (OfficeXmlFileException e) { // opening as .xls failed => try opening as .xlsx OPCPackage pkg = OPCPackage.Open(file); try { return new XSSFWorkbook(pkg); } catch (IOException ioe) { // ensure that file handles are closed (use revert() to not re-write the file) pkg.Revert(); //pkg.close(); // rethrow exception throw ioe; } catch (ArgumentException ioe) { // ensure that file handles are closed (use revert() to not re-write the file) pkg.Revert(); //pkg.close(); // rethrow exception throw ioe; } } } /// <summary> /// Creates the appropriate HSSFWorkbook / XSSFWorkbook from /// the given InputStream. The Stream is wraped inside a PushbackInputStream. /// </summary> /// <param name="inputStream">Input Stream of .xls or .xlsx file</param> /// <param name="importOption">Customize the elements that are processed on the next import</param> /// <returns>IWorkbook depending on the input HSSFWorkbook or XSSFWorkbook is returned.</returns> public static IWorkbook Create(Stream inputStream, ImportOption importOption) { SetImportOption(importOption); IWorkbook workbook = Create(inputStream); return workbook; } /// <summary> /// Creates a specific FormulaEvaluator for the given workbook. /// </summary> public static IFormulaEvaluator CreateFormulaEvaluator(IWorkbook workbook) { if (typeof(HSSFWorkbook) == workbook.GetType()) { return new HSSFFormulaEvaluator(workbook as HSSFWorkbook); } else { return new XSSFFormulaEvaluator(workbook as XSSFWorkbook); } } /// <summary> /// Sets the import option when opening the next workbook. /// Works only for XSSF. For HSSF workbooks this option is ignored. /// </summary> /// <param name="importOption">Customize the elements that are processed on the next import</param> public static void SetImportOption(ImportOption importOption) { if (ImportOption.SheetContentOnly == importOption) { // Add XSSFRelation.AddRelation(XSSFRelation.WORKSHEET); XSSFRelation.AddRelation(XSSFRelation.SHARED_STRINGS); // Remove XSSFRelation.RemoveRelation(XSSFRelation.WORKBOOK); XSSFRelation.RemoveRelation(XSSFRelation.MACROS_WORKBOOK); XSSFRelation.RemoveRelation(XSSFRelation.TEMPLATE_WORKBOOK); XSSFRelation.RemoveRelation(XSSFRelation.MACRO_TEMPLATE_WORKBOOK); XSSFRelation.RemoveRelation(XSSFRelation.MACRO_ADDIN_WORKBOOK); XSSFRelation.RemoveRelation(XSSFRelation.CHARTSHEET); XSSFRelation.RemoveRelation(XSSFRelation.STYLES); XSSFRelation.RemoveRelation(XSSFRelation.DRAWINGS); XSSFRelation.RemoveRelation(XSSFRelation.CHART); XSSFRelation.RemoveRelation(XSSFRelation.VML_DRAWINGS); XSSFRelation.RemoveRelation(XSSFRelation.CUSTOM_XML_MAPPINGS); XSSFRelation.RemoveRelation(XSSFRelation.TABLE); XSSFRelation.RemoveRelation(XSSFRelation.IMAGES); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_EMF); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_WMF); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_PICT); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_JPEG); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_PNG); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_DIB); XSSFRelation.RemoveRelation(XSSFRelation.SHEET_COMMENTS); XSSFRelation.RemoveRelation(XSSFRelation.SHEET_HYPERLINKS); XSSFRelation.RemoveRelation(XSSFRelation.OLEEMBEDDINGS); XSSFRelation.RemoveRelation(XSSFRelation.PACKEMBEDDINGS); XSSFRelation.RemoveRelation(XSSFRelation.VBA_MACROS); XSSFRelation.RemoveRelation(XSSFRelation.ACTIVEX_CONTROLS); XSSFRelation.RemoveRelation(XSSFRelation.ACTIVEX_BINS); XSSFRelation.RemoveRelation(XSSFRelation.THEME); XSSFRelation.RemoveRelation(XSSFRelation.CALC_CHAIN); XSSFRelation.RemoveRelation(XSSFRelation.PRINTER_SETTINGS); } else if (ImportOption.TextOnly == importOption) { // Add XSSFRelation.AddRelation(XSSFRelation.WORKSHEET); XSSFRelation.AddRelation(XSSFRelation.SHARED_STRINGS); XSSFRelation.AddRelation(XSSFRelation.SHEET_COMMENTS); // Remove XSSFRelation.RemoveRelation(XSSFRelation.WORKBOOK); XSSFRelation.RemoveRelation(XSSFRelation.MACROS_WORKBOOK); XSSFRelation.RemoveRelation(XSSFRelation.TEMPLATE_WORKBOOK); XSSFRelation.RemoveRelation(XSSFRelation.MACRO_TEMPLATE_WORKBOOK); XSSFRelation.RemoveRelation(XSSFRelation.MACRO_ADDIN_WORKBOOK); XSSFRelation.RemoveRelation(XSSFRelation.CHARTSHEET); XSSFRelation.RemoveRelation(XSSFRelation.STYLES); XSSFRelation.RemoveRelation(XSSFRelation.DRAWINGS); XSSFRelation.RemoveRelation(XSSFRelation.CHART); XSSFRelation.RemoveRelation(XSSFRelation.VML_DRAWINGS); XSSFRelation.RemoveRelation(XSSFRelation.CUSTOM_XML_MAPPINGS); XSSFRelation.RemoveRelation(XSSFRelation.TABLE); XSSFRelation.RemoveRelation(XSSFRelation.IMAGES); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_EMF); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_WMF); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_PICT); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_JPEG); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_PNG); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_DIB); XSSFRelation.RemoveRelation(XSSFRelation.SHEET_HYPERLINKS); XSSFRelation.RemoveRelation(XSSFRelation.OLEEMBEDDINGS); XSSFRelation.RemoveRelation(XSSFRelation.PACKEMBEDDINGS); XSSFRelation.RemoveRelation(XSSFRelation.VBA_MACROS); XSSFRelation.RemoveRelation(XSSFRelation.ACTIVEX_CONTROLS); XSSFRelation.RemoveRelation(XSSFRelation.ACTIVEX_BINS); XSSFRelation.RemoveRelation(XSSFRelation.THEME); XSSFRelation.RemoveRelation(XSSFRelation.CALC_CHAIN); XSSFRelation.RemoveRelation(XSSFRelation.PRINTER_SETTINGS); } else { // NONE/All XSSFRelation.AddRelation(XSSFRelation.WORKBOOK); XSSFRelation.AddRelation(XSSFRelation.MACROS_WORKBOOK); XSSFRelation.AddRelation(XSSFRelation.TEMPLATE_WORKBOOK); XSSFRelation.AddRelation(XSSFRelation.MACRO_TEMPLATE_WORKBOOK); XSSFRelation.AddRelation(XSSFRelation.MACRO_ADDIN_WORKBOOK); XSSFRelation.AddRelation(XSSFRelation.WORKSHEET); XSSFRelation.AddRelation(XSSFRelation.CHARTSHEET); XSSFRelation.AddRelation(XSSFRelation.SHARED_STRINGS); XSSFRelation.AddRelation(XSSFRelation.STYLES); XSSFRelation.AddRelation(XSSFRelation.DRAWINGS); XSSFRelation.AddRelation(XSSFRelation.CHART); XSSFRelation.AddRelation(XSSFRelation.VML_DRAWINGS); XSSFRelation.AddRelation(XSSFRelation.CUSTOM_XML_MAPPINGS); XSSFRelation.AddRelation(XSSFRelation.TABLE); XSSFRelation.AddRelation(XSSFRelation.IMAGES); XSSFRelation.AddRelation(XSSFRelation.IMAGE_EMF); XSSFRelation.AddRelation(XSSFRelation.IMAGE_WMF); XSSFRelation.AddRelation(XSSFRelation.IMAGE_PICT); XSSFRelation.AddRelation(XSSFRelation.IMAGE_JPEG); XSSFRelation.AddRelation(XSSFRelation.IMAGE_PNG); XSSFRelation.AddRelation(XSSFRelation.IMAGE_DIB); XSSFRelation.AddRelation(XSSFRelation.SHEET_COMMENTS); XSSFRelation.AddRelation(XSSFRelation.SHEET_HYPERLINKS); XSSFRelation.AddRelation(XSSFRelation.OLEEMBEDDINGS); XSSFRelation.AddRelation(XSSFRelation.PACKEMBEDDINGS); XSSFRelation.AddRelation(XSSFRelation.VBA_MACROS); XSSFRelation.AddRelation(XSSFRelation.ACTIVEX_CONTROLS); XSSFRelation.AddRelation(XSSFRelation.ACTIVEX_BINS); XSSFRelation.AddRelation(XSSFRelation.THEME); XSSFRelation.AddRelation(XSSFRelation.CALC_CHAIN); XSSFRelation.AddRelation(XSSFRelation.PRINTER_SETTINGS); } } } }
// 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 gagvr = Google.Ads.GoogleAds.V8.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V8.Services { /// <summary>Settings for <see cref="ExpandedLandingPageViewServiceClient"/> instances.</summary> public sealed partial class ExpandedLandingPageViewServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="ExpandedLandingPageViewServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="ExpandedLandingPageViewServiceSettings"/>.</returns> public static ExpandedLandingPageViewServiceSettings GetDefault() => new ExpandedLandingPageViewServiceSettings(); /// <summary> /// Constructs a new <see cref="ExpandedLandingPageViewServiceSettings"/> object with default settings. /// </summary> public ExpandedLandingPageViewServiceSettings() { } private ExpandedLandingPageViewServiceSettings(ExpandedLandingPageViewServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetExpandedLandingPageViewSettings = existing.GetExpandedLandingPageViewSettings; OnCopy(existing); } partial void OnCopy(ExpandedLandingPageViewServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>ExpandedLandingPageViewServiceClient.GetExpandedLandingPageView</c> and /// <c>ExpandedLandingPageViewServiceClient.GetExpandedLandingPageViewAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetExpandedLandingPageViewSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="ExpandedLandingPageViewServiceSettings"/> object.</returns> public ExpandedLandingPageViewServiceSettings Clone() => new ExpandedLandingPageViewServiceSettings(this); } /// <summary> /// Builder class for <see cref="ExpandedLandingPageViewServiceClient"/> to provide simple configuration of /// credentials, endpoint etc. /// </summary> internal sealed partial class ExpandedLandingPageViewServiceClientBuilder : gaxgrpc::ClientBuilderBase<ExpandedLandingPageViewServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public ExpandedLandingPageViewServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public ExpandedLandingPageViewServiceClientBuilder() { UseJwtAccessWithScopes = ExpandedLandingPageViewServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref ExpandedLandingPageViewServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<ExpandedLandingPageViewServiceClient> task); /// <summary>Builds the resulting client.</summary> public override ExpandedLandingPageViewServiceClient Build() { ExpandedLandingPageViewServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<ExpandedLandingPageViewServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<ExpandedLandingPageViewServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private ExpandedLandingPageViewServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return ExpandedLandingPageViewServiceClient.Create(callInvoker, Settings); } private async stt::Task<ExpandedLandingPageViewServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return ExpandedLandingPageViewServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => ExpandedLandingPageViewServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => ExpandedLandingPageViewServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => ExpandedLandingPageViewServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>ExpandedLandingPageViewService client wrapper, for convenient use.</summary> /// <remarks> /// Service to fetch expanded landing page views. /// </remarks> public abstract partial class ExpandedLandingPageViewServiceClient { /// <summary> /// The default endpoint for the ExpandedLandingPageViewService service, which is a host of /// "googleads.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default ExpandedLandingPageViewService scopes.</summary> /// <remarks> /// The default ExpandedLandingPageViewService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="ExpandedLandingPageViewServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="ExpandedLandingPageViewServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="ExpandedLandingPageViewServiceClient"/>.</returns> public static stt::Task<ExpandedLandingPageViewServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new ExpandedLandingPageViewServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="ExpandedLandingPageViewServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="ExpandedLandingPageViewServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="ExpandedLandingPageViewServiceClient"/>.</returns> public static ExpandedLandingPageViewServiceClient Create() => new ExpandedLandingPageViewServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="ExpandedLandingPageViewServiceClient"/> which uses the specified call invoker for /// remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="ExpandedLandingPageViewServiceSettings"/>.</param> /// <returns>The created <see cref="ExpandedLandingPageViewServiceClient"/>.</returns> internal static ExpandedLandingPageViewServiceClient Create(grpccore::CallInvoker callInvoker, ExpandedLandingPageViewServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } ExpandedLandingPageViewService.ExpandedLandingPageViewServiceClient grpcClient = new ExpandedLandingPageViewService.ExpandedLandingPageViewServiceClient(callInvoker); return new ExpandedLandingPageViewServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC ExpandedLandingPageViewService client</summary> public virtual ExpandedLandingPageViewService.ExpandedLandingPageViewServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested expanded landing page view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::ExpandedLandingPageView GetExpandedLandingPageView(GetExpandedLandingPageViewRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested expanded landing page view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ExpandedLandingPageView> GetExpandedLandingPageViewAsync(GetExpandedLandingPageViewRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested expanded landing page view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ExpandedLandingPageView> GetExpandedLandingPageViewAsync(GetExpandedLandingPageViewRequest request, st::CancellationToken cancellationToken) => GetExpandedLandingPageViewAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested expanded landing page view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the expanded landing page view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::ExpandedLandingPageView GetExpandedLandingPageView(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetExpandedLandingPageView(new GetExpandedLandingPageViewRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested expanded landing page view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the expanded landing page view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ExpandedLandingPageView> GetExpandedLandingPageViewAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetExpandedLandingPageViewAsync(new GetExpandedLandingPageViewRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested expanded landing page view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the expanded landing page view to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ExpandedLandingPageView> GetExpandedLandingPageViewAsync(string resourceName, st::CancellationToken cancellationToken) => GetExpandedLandingPageViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested expanded landing page view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the expanded landing page view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::ExpandedLandingPageView GetExpandedLandingPageView(gagvr::ExpandedLandingPageViewName resourceName, gaxgrpc::CallSettings callSettings = null) => GetExpandedLandingPageView(new GetExpandedLandingPageViewRequest { ResourceNameAsExpandedLandingPageViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested expanded landing page view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the expanded landing page view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ExpandedLandingPageView> GetExpandedLandingPageViewAsync(gagvr::ExpandedLandingPageViewName resourceName, gaxgrpc::CallSettings callSettings = null) => GetExpandedLandingPageViewAsync(new GetExpandedLandingPageViewRequest { ResourceNameAsExpandedLandingPageViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested expanded landing page view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the expanded landing page view to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ExpandedLandingPageView> GetExpandedLandingPageViewAsync(gagvr::ExpandedLandingPageViewName resourceName, st::CancellationToken cancellationToken) => GetExpandedLandingPageViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>ExpandedLandingPageViewService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to fetch expanded landing page views. /// </remarks> public sealed partial class ExpandedLandingPageViewServiceClientImpl : ExpandedLandingPageViewServiceClient { private readonly gaxgrpc::ApiCall<GetExpandedLandingPageViewRequest, gagvr::ExpandedLandingPageView> _callGetExpandedLandingPageView; /// <summary> /// Constructs a client wrapper for the ExpandedLandingPageViewService service, with the specified gRPC client /// and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="ExpandedLandingPageViewServiceSettings"/> used within this client. /// </param> public ExpandedLandingPageViewServiceClientImpl(ExpandedLandingPageViewService.ExpandedLandingPageViewServiceClient grpcClient, ExpandedLandingPageViewServiceSettings settings) { GrpcClient = grpcClient; ExpandedLandingPageViewServiceSettings effectiveSettings = settings ?? ExpandedLandingPageViewServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetExpandedLandingPageView = clientHelper.BuildApiCall<GetExpandedLandingPageViewRequest, gagvr::ExpandedLandingPageView>(grpcClient.GetExpandedLandingPageViewAsync, grpcClient.GetExpandedLandingPageView, effectiveSettings.GetExpandedLandingPageViewSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetExpandedLandingPageView); Modify_GetExpandedLandingPageViewApiCall(ref _callGetExpandedLandingPageView); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_GetExpandedLandingPageViewApiCall(ref gaxgrpc::ApiCall<GetExpandedLandingPageViewRequest, gagvr::ExpandedLandingPageView> call); partial void OnConstruction(ExpandedLandingPageViewService.ExpandedLandingPageViewServiceClient grpcClient, ExpandedLandingPageViewServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC ExpandedLandingPageViewService client</summary> public override ExpandedLandingPageViewService.ExpandedLandingPageViewServiceClient GrpcClient { get; } partial void Modify_GetExpandedLandingPageViewRequest(ref GetExpandedLandingPageViewRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested expanded landing page view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::ExpandedLandingPageView GetExpandedLandingPageView(GetExpandedLandingPageViewRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetExpandedLandingPageViewRequest(ref request, ref callSettings); return _callGetExpandedLandingPageView.Sync(request, callSettings); } /// <summary> /// Returns the requested expanded landing page view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::ExpandedLandingPageView> GetExpandedLandingPageViewAsync(GetExpandedLandingPageViewRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetExpandedLandingPageViewRequest(ref request, ref callSettings); return _callGetExpandedLandingPageView.Async(request, callSettings); } } }
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 DependencySummary.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 2020 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 // // 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 Debugger.SbDebuggerRpc; using DebuggerApi; using Grpc.Core; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; namespace DebuggerGrpcClient { /// <summary> /// Creates SBDebugger objects. /// </summary> public class GrpcDebuggerFactory { public virtual SbDebugger Create( GrpcConnection connection, bool sourceInitFiles, TimeSpan retryWaitTime) { if (connection == null) { throw new ArgumentNullException(nameof(connection));} if (retryWaitTime == null) { throw new ArgumentNullException(nameof(retryWaitTime)); } var instance = new SbDebuggerImpl(connection); if (instance.Create(sourceInitFiles, retryWaitTime)) { return instance; } return null; } } /// <summary> /// Implementation of the SBDebugger interface that uses GRPC to make RPCs to a remote endpoint. /// </summary> class SbDebuggerImpl : SbDebugger { readonly SbDebuggerRpcService.SbDebuggerRpcServiceClient client; readonly GrpcConnection connection; readonly GrpcTargetFactory sbTargetFactory; readonly GrpcPlatformFactory sbPlatformFactory; readonly GrpcSbCommandInterpreterFactory sbCommandInterpreterFactory; internal SbDebuggerImpl(GrpcConnection connection) : this(connection, new GrpcTargetFactory(), new GrpcPlatformFactory(), new GrpcSbCommandInterpreterFactory(), new SbDebuggerRpcService.SbDebuggerRpcServiceClient(connection.CallInvoker)) {} // Constructor that can be used by tests to pass in mock objects. internal SbDebuggerImpl(GrpcConnection connection, GrpcTargetFactory sbTargetFactory, GrpcPlatformFactory sbPlatformFactory, GrpcSbCommandInterpreterFactory sbCommandInterpreterFactory, SbDebuggerRpcService.SbDebuggerRpcServiceClient client) { this.connection = connection; this.sbTargetFactory = sbTargetFactory; this.sbPlatformFactory = sbPlatformFactory; this.sbCommandInterpreterFactory = sbCommandInterpreterFactory; this.client = client; } internal bool Create(bool sourceInitFiles, TimeSpan retryWaitTime) { return connection.InvokeRpc(() => { client.Create( new CreateRequest { SourceInitFiles = sourceInitFiles }, new CallOptions() .WithDeadline(DateTime.UtcNow.Add(retryWaitTime)) .WithWaitForReady()); }); } #region SbDebugger public void SetAsync(bool async) { connection.InvokeRpc(() => { client.SetAsync(new SetAsyncRequest { Async = async }); }); } public void SkipLLDBInitFiles(bool skip) { connection.InvokeRpc(() => { client.SkipLLDBInitFiles( new SkipLLDBInitFilesRequest { Skip = skip }); }); } public SbCommandInterpreter GetCommandInterpreter() { GetCommandInterpreterResponse response = null; if (connection.InvokeRpc(() => { response = client.GetCommandInterpreter( new GetCommandInterpreterRequest()); })) { if (response.Interpreter != null && response.Interpreter.Id != 0) { return sbCommandInterpreterFactory.Create(connection, response.Interpreter); } } return null; } public RemoteTarget CreateTarget(string filename) { CreateTargetResponse response = null; if (connection.InvokeRpc(() => { response = client.CreateTarget( new CreateTargetRequest { Filename = filename }); })) { return sbTargetFactory.Create(connection, response.GrpcSbTarget); } return null; } public void SetSelectedPlatform(SbPlatform platform) { // We only support a single platform, so don't bother passing a platform here as the // server just assumes which platform to use. connection.InvokeRpc(() => { client.SetSelectedPlatform(new SetSelectedPlatformRequest()); }); } public SbPlatform GetSelectedPlatform() { var request = new GetSelectedPlatformRequest(); if (connection.InvokeRpc(() => { client.GetSelectedPlatform(request); })) { // Create a new platform without telling the server to create a new one. Since we // only support a single platform on the server, there is no need to identify which // platform to call the RPCs on (its assumed). So just create a default platform // and start calling RPCs. return sbPlatformFactory.Create(connection); } return null; } public bool EnableLog(string channel, IEnumerable<string> types) { var request = new EnableLogRequest { Channel = channel }; request.Types_.Add(types); EnableLogResponse response = null; if (connection.InvokeRpc(() => { response = client.EnableLog(request); })) { return response.Result; } return false; } public bool IsPlatformAvailable(string platformName) { var request = new IsPlatformAvailableRequest() { PlatformName = platformName }; IsPlatformAvailableResponse response = null; if (connection.InvokeRpc(() => { response = client.IsPlatformAvailable(request); })) { return response.Result; } return false; } public bool DeleteTarget(RemoteTarget target) { // Not needed as the external process shutdown will take care of cleanup. return true; } #endregion } /// <summary> /// Extension methods for SbDebugger commands. /// These are extension methods, instead of being added directly to SbDebugger as there is no /// corresponding API, and SbDebugger is meant to be a very simple wrapper. /// </summary> public static class SbDebuggerExtensions { public const string FastExpressionEvaluationCommand = "settings set target.experimental.inject-local-vars false"; static string CreateSetLibrarySearchPathCommand(string path) => $"settings append target.exec-search-paths \"{path}\""; static string[] DefaultLLDBSettings = { // Do not auto apply fixits because they could cause unintended // side-effects. For example, a fixit on function name 'f' is // a call to function f, i.e. 'f()'. "settings set target.auto-apply-fixits false", // Replace the default memory chunk size 512 with a higher one // so that we decrease the number of roundtrips to the remote // machine. "settings set target.process.memory-cache-line-size 4096", // Turn on template instantiation in expressions. "settings set target.experimental.infer-class-templates true", // Set gdb-remote packet timeout to 5s so that big messages // have enough time to get through on slower networks. "settings set plugin.process.gdb-remote.packet-timeout 5", // Enable the dynamic loader plugin for debugging Wine. "settings set plugin.process.wine-dyld.use-wine-dynamic-loader true", // Set the correct path to llvm-objdump on the target. "settings set plugin.process.wine-dyld.remote-objdump-path \"" + YetiCommon.YetiConstants.RemoteLlvmObjDumpPath + "\"", }; public static string GetLLDBInitPath() { var homeDir = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); return Path.Combine(homeDir, ".lldbinit"); } public static void EnableFastExpressionEvaluation(this SbDebugger debugger) { Trace.WriteLine("Enabling fast expression evaluation."); debugger.GetCommandInterpreter().HandleAndLogCommand(FastExpressionEvaluationCommand); } public static void SetLibrarySearchPath(this SbDebugger debugger, string path) { debugger.GetCommandInterpreter().HandleAndLogCommand( CreateSetLibrarySearchPathCommand(path)); } public static void SetDefaultLLDBSettings(this SbDebugger debugger) { foreach (string s in DefaultLLDBSettings) { debugger.GetCommandInterpreter().HandleAndLogCommand(s); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using CocosSharp; using System.Diagnostics; using Microsoft.Xna.Framework.Graphics; namespace tests { public class ParticleMainScene : CCScene { public ParticleMainScene() : base(AppDelegate.SharedWindow, AppDelegate.SharedViewport) { } public virtual void initWithSubTest(int asubtest, int particles) { //srandom(0); subtestNumber = asubtest; CCSize s = Layer.VisibleBoundsWorldspace.Size; lastRenderedCount = 0; quantityParticles = particles; CCMenuItemFont.FontSize = 64; CCMenuItemFont.FontName = "arial"; CCMenuItemFont decrease = new CCMenuItemFont(" - ", onDecrease); decrease.Color = new CCColor3B(0, 200, 20); CCMenuItemFont increase = new CCMenuItemFont(" + ", onIncrease); increase.Color = new CCColor3B(0, 200, 20); CCMenu menu = new CCMenu(decrease, increase); menu.AlignItemsHorizontally(); menu.Position = new CCPoint(s.Width / 2, s.Height / 2 + 15); AddChild(menu, 1); CCLabelTtf infoLabel = new CCLabelTtf("0 nodes", "Marker Felt", 30); infoLabel.Color = new CCColor3B(0, 200, 20); infoLabel.Position = new CCPoint(s.Width / 2, s.Height - 90); AddChild(infoLabel, 1, PerformanceParticleTest.kTagInfoLayer); // particles on stage CCLabelAtlas labelAtlas = new CCLabelAtlas("0000", "Images/fps_Images", 12, 32, '.'); AddChild(labelAtlas, 0, PerformanceParticleTest.kTagLabelAtlas); labelAtlas.Position = new CCPoint(s.Width - 66, 50); // Next Prev Test ParticleMenuLayer pMenu = new ParticleMenuLayer(true, PerformanceParticleTest.TEST_COUNT, PerformanceParticleTest.s_nParCurIdx); AddChild(pMenu, 1, PerformanceParticleTest.kTagMenuLayer); // Sub Tests CCMenuItemFont.FontSize = 38; CCMenuItemFont.FontName = "arial"; CCMenu pSubMenu = new CCMenu(null); for (int i = 1; i <= 6; ++i) { //char str[10] = {0}; string str; //sprintf(str, "%d ", i); str = string.Format("{0:G}", i); CCMenuItemFont itemFont = new CCMenuItemFont(str, testNCallback); itemFont.Tag = i; pSubMenu.AddChild(itemFont, 10); if (i <= 3) { itemFont.Color = new CCColor3B(200, 20, 20); } else { itemFont.Color = new CCColor3B(0, 200, 20); } } pSubMenu.AlignItemsHorizontally(); pSubMenu.Position = new CCPoint(s.Width / 2, 80); AddChild(pSubMenu, 2); CCLabelTtf label = new CCLabelTtf(title(), "arial", 38); AddChild(label, 1); label.Position = new CCPoint(s.Width / 2, s.Height - 32); label.Color = new CCColor3B(255, 255, 40); updateQuantityLabel(); createParticleSystem(); Schedule(step); } public virtual string title() { return "No title"; } public void step(float dt) { CCLabelAtlas atlas = (CCLabelAtlas)GetChildByTag(PerformanceParticleTest.kTagLabelAtlas); CCParticleSystem emitter = (CCParticleSystem)GetChildByTag(PerformanceParticleTest.kTagParticleSystem); var str = string.Format("{0:0000}", emitter.ParticleCount); atlas.Text = (str); } public void createParticleSystem() { CCParticleSystem particleSystem = null; /* * Tests: * 1: Point Particle System using 32-bit textures (PNG) * 2: Point Particle System using 16-bit textures (PNG) * 3: Point Particle System using 8-bit textures (PNG) * 4: Point Particle System using 4-bit textures (PVRTC) * 5: Quad Particle System using 32-bit textures (PNG) * 6: Quad Particle System using 16-bit textures (PNG) * 7: Quad Particle System using 8-bit textures (PNG) * 8: Quad Particle System using 4-bit textures (PVRTC) */ RemoveChildByTag(PerformanceParticleTest.kTagParticleSystem, true); // remove the "fire.png" from the TextureCache cache. CCTexture2D texture = CCTextureCache.SharedTextureCache.AddImage("Images/fire"); CCTextureCache.SharedTextureCache.RemoveTexture(texture); particleSystem = new CCParticleSystemQuad(quantityParticles); switch (subtestNumber) { case 1: CCTexture2D.DefaultAlphaPixelFormat = CCSurfaceFormat.Color; particleSystem.Texture = CCTextureCache.SharedTextureCache.AddImage("Images/fire"); break; case 2: CCTexture2D.DefaultAlphaPixelFormat = CCSurfaceFormat.Bgra4444; particleSystem.Texture = CCTextureCache.SharedTextureCache.AddImage("Images/fire"); break; case 3: CCTexture2D.DefaultAlphaPixelFormat = CCSurfaceFormat.Alpha8; particleSystem.Texture = CCTextureCache.SharedTextureCache.AddImage("Images/fire"); break; // case 4: // particleSystem->initWithTotalParticles(quantityParticles); // ////---- particleSystem.texture = [[CCTextureCache sharedTextureCache] addImage:@"fire.pvr"]; // particleSystem->setTexture(CCTextureCache::sharedTextureCache()->addImage("Images/fire.png")); // break; case 4: CCTexture2D.DefaultAlphaPixelFormat = CCSurfaceFormat.Color; particleSystem.Texture = CCTextureCache.SharedTextureCache.AddImage("Images/fire"); break; case 5: CCTexture2D.DefaultAlphaPixelFormat = CCSurfaceFormat.Bgra4444; particleSystem.Texture = CCTextureCache.SharedTextureCache.AddImage("Images/fire"); break; case 6: CCTexture2D.DefaultAlphaPixelFormat = CCSurfaceFormat.Alpha8; particleSystem.Texture = CCTextureCache.SharedTextureCache.AddImage("Images/fire"); break; // case 8: // particleSystem->initWithTotalParticles(quantityParticles); // ////---- particleSystem.texture = [[CCTextureCache sharedTextureCache] addImage:@"fire.pvr"]; // particleSystem->setTexture(CCTextureCache::sharedTextureCache()->addImage("Images/fire.png")); // break; default: particleSystem = null; CCLog.Log("Shall not happen!"); break; } AddChild(particleSystem, 0, PerformanceParticleTest.kTagParticleSystem); doTest(); // restore the default pixel format CCTexture2D.DefaultAlphaPixelFormat = CCSurfaceFormat.Color; } public void onDecrease(object pSender) { quantityParticles -= PerformanceParticleTest.kNodesIncrease; if (quantityParticles < 0) quantityParticles = 0; updateQuantityLabel(); createParticleSystem(); } public void onIncrease(object pSender) { quantityParticles += PerformanceParticleTest.kNodesIncrease; if (quantityParticles > PerformanceParticleTest.kMaxParticles) quantityParticles = PerformanceParticleTest.kMaxParticles; updateQuantityLabel(); createParticleSystem(); } public void testNCallback(object pSender) { subtestNumber = ((CCNode)pSender).Tag; ParticleMenuLayer pMenu = (ParticleMenuLayer)GetChildByTag(PerformanceParticleTest.kTagMenuLayer); pMenu.restartCallback(pSender); } public void updateQuantityLabel() { if (quantityParticles != lastRenderedCount) { CCLabelTtf infoLabel = (CCLabelTtf)GetChildByTag(PerformanceParticleTest.kTagInfoLayer); string str = string.Format("{0} particles", quantityParticles); infoLabel.Text = (str); lastRenderedCount = quantityParticles; } } public int getSubTestNum() { return subtestNumber; } public int getParticlesNum() { return quantityParticles; } public virtual void doTest() { throw new NotFiniteNumberException(); } protected int lastRenderedCount; protected int quantityParticles; protected int subtestNumber; } }
using System; using System.Net; using System.Net.Sockets; using System.Threading; namespace HBus.Ports { /// <summary> /// Tcp implementation /// Parameters: /// hostip: host ip node (for hub configurations) /// listenport: ip port that receives HBus messages /// sendport: ip port that transmits HBus messages /// portnumber: HBus port index /// asyncmessages: transmit asyncrously /// </summary> public class PortTcp : Port { private readonly string _hostIp; private readonly int _tcpListenPort; private readonly int _tcpSendPort; private string _lastIp; private bool _listen; private NetworkStream _stream; private TcpListener _tcpListener; public PortTcp(string hostip, int listenport, int sendport, int portnumber, bool asyncmessages = false) : base(portnumber, asyncmessages) { //Store host address _hostIp = hostip; _tcpListenPort = listenport; _tcpSendPort = sendport; IsMulticast = true; IsFullDuplex = true; HasRoutes = true; Log.Debug("PortTcp(...) done."); } #region Implementation of IDisposable public override void Dispose() { Stop(); base.Dispose(); } #endregion /// <summary> /// Start listening on tcp port /// </summary> public override void Start() { Log.Debug("PortTcp.start"); try { // Set the listener on the local IP address // and specify the port. _tcpListener = new TcpListener(IPAddress.Any, _tcpListenPort); _listen = true; _tcpListener.Start(); Log.Debug("Start waiting for a connection..."); var thread = new Thread(CreateListener); thread.Start(); base.Start(); } catch (Exception e) { Log.Error("PortTcp.CreateListener error", e); } } public override void Stop() { _listen = false; if (_tcpListener != null) _tcpListener.Stop(); base.Stop(); } #region Rx routines /// <summary> /// Create rx listener for tcp connections /// </summary> private void CreateListener() { while (_listen) { // Always use a Sleep call in a while(true) loop // to avoid locking up your CPU. Thread.Sleep(10); try { // Create a TCP socket. // If you ran this server on the desktop, you could use // Socket socket = tcpListener.AcceptSocket() // for greater flexibility. using (var tcpClient = _tcpListener.AcceptTcpClient()) { // Read the data stream from the client. var data = new byte[tcpClient.ReceiveBufferSize]; _stream = tcpClient.GetStream(); var bytesRead = _stream.Read(data, 0, data.Length); if (bytesRead > 0) { var ip = (IPEndPoint) tcpClient.Client.RemoteEndPoint; var ipvalue = ip.ToString(); ipvalue = ipvalue.IndexOf(':') > 0 ? ipvalue.Substring(0, ipvalue.IndexOf(':')) : ipvalue; _lastIp = ipvalue; //Process received data if (!ProcessData(data, bytesRead, ipvalue)) Log.Error("ProcessData from TcpPort failed"); } //Close client tcpClient.Close(); } } catch (Exception ex) { Log.Error("CreateListener: unexpected socket end", ex); } } Log.Debug("CreateListener stop"); } #endregion #region Tx routines protected override void WritePort(byte[] buffer, int i, int length, string hwaddress) { try { if ((buffer == null) || (buffer.Length < i + length)) { //Status = Status.Error; Log.Error("PortTcp: message size error."); return; } if ((_stream != null) && _stream.CanWrite && ((hwaddress == _lastIp) || string.IsNullOrEmpty(hwaddress))) { _stream.Write(buffer, i, length); _stream.Flush(); _stream.Close(); _stream = null; _lastIp = string.Empty; } else { var ip = !string.IsNullOrEmpty(hwaddress) ? hwaddress : _hostIp; WriteData(ip, buffer); Log.Debug(string.Format("PortTcp.WritePort: " + buffer.Length + " bytes sent to tcp address " + ip)); } } catch (Exception ex) { Log.Error("PortTcp.WritePort: Something wrong while sending buffer", ex); throw; } } private void WriteData(string ipAddress, byte[] buffer) { Socket socket = null; try { socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.SendTimeout = 5000; socket.Connect(ipAddress, _tcpSendPort); socket.Send(buffer); Thread.Sleep(500); if (socket.Available > 0) { var buf = new byte[socket.Available]; socket.Receive(buf); ProcessData(buf, buf.Length, ipAddress); } socket.Close(); } catch (Exception ex) { if (socket != null) socket.Close(); Log.Error("PortTcp.SendData: Unexpected error", ex); } } #endregion } }
// Copyright 2021 Esri. // // 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 Android.App; using Android.Content; using Android.OS; using Android.Views; using Android.Widget; using Esri.ArcGISRuntime.Data; using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Ogc; using Esri.ArcGISRuntime.Symbology; using Esri.ArcGISRuntime.UI.Controls; using System; using System.Drawing; namespace ArcGISRuntimeXamarin.Samples.BrowseOAFeatureService { [Activity(ConfigurationChanges = Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)] [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Browse OGC API feature service", category: "Layers", description: "Browse an OGC API feature service for layers and add them to the map.", instructions: "Select a layer to display from the list of layers shown in an OGC API service.", tags: new[] { "OGC", "OGC API", "browse", "catalog", "feature", "layers", "service", "web" })] public class BrowseOAFeatureService : Activity { // Hold references to the UI controls. private MapView _myMapView; private ProgressBar _loadingProgressBar; private Button _loadLayerButton; private Button _loadServiceButton; private EditText _urlEntry; // URL for the OGC feature service. private const string _serviceUrl = "https://demo.ldproxy.net/daraa"; private OgcFeatureServiceInfo _serviceInfo; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); Title = "Browse OGC API feature service"; CreateLayout(); Initialize(); } private void Initialize() { // Create the map with topographic basemap. _myMapView.Map = new Map(BasemapStyle.ArcGISTopographic); LoadService(_serviceUrl); } private async void LoadService(string serviceUrl) { try { _loadingProgressBar.Visibility = ViewStates.Visible; _loadLayerButton.Enabled = false; _loadServiceButton.Enabled = false; // Create the OGC API - Features service using the landing URL. OgcFeatureService service = new OgcFeatureService(new Uri(serviceUrl)); // Load the service. await service.LoadAsync(); // Get the service metadata. _serviceInfo = service.ServiceInfo; } catch (Exception ex) { new AlertDialog.Builder(this).SetMessage(ex.Message).SetTitle("Error loading service").Show(); } finally { // Update the UI. _loadingProgressBar.Visibility = ViewStates.Gone; _loadLayerButton.Enabled = true; _loadServiceButton.Enabled = true; } } private async void LayerMenu_LayerSelected(object sender, PopupMenu.MenuItemClickEventArgs e) { // Show the progress bar. _loadingProgressBar.Visibility = ViewStates.Visible; // Clear the existing layers. _myMapView.Map.OperationalLayers.Clear(); try { // Get the selected collection. OgcFeatureCollectionInfo selectedCollectionInfo = _serviceInfo.FeatureCollectionInfos[e.Item.Order]; // Create the OGC feature collection table. OgcFeatureCollectionTable table = new OgcFeatureCollectionTable(selectedCollectionInfo); // Set the feature request mode to manual (only manual is currently supported). // In this mode, you must manually populate the table - panning and zooming won't request features automatically. table.FeatureRequestMode = FeatureRequestMode.ManualCache; // Populate the OGC feature collection table. QueryParameters queryParamaters = new QueryParameters(); queryParamaters.MaxFeatures = 1000; await table.PopulateFromServiceAsync(queryParamaters, false, null); // Create a feature layer from the OGC feature collection table. FeatureLayer ogcFeatureLayer = new FeatureLayer(table); // Choose a renderer for the layer based on the table. ogcFeatureLayer.Renderer = GetRendererForTable(table) ?? ogcFeatureLayer.Renderer; // Add the layer to the map. _myMapView.Map.OperationalLayers.Add(ogcFeatureLayer); // Zoom to the extent of the selected collection. if (selectedCollectionInfo.Extent is Envelope collectionExtent && !collectionExtent.IsEmpty) { await _myMapView.SetViewpointGeometryAsync(collectionExtent, 100); } } catch (Exception exception) { System.Diagnostics.Debug.WriteLine(exception); new AlertDialog.Builder(this).SetMessage(exception.ToString()).SetTitle("Couldn't load layer.").Show(); } finally { // Hide the progress bar. _loadingProgressBar.Visibility = ViewStates.Gone; } } private void ChooseLayer_Clicked(object sender, EventArgs e) { // Get a reference to the button. Button loadButton = (Button)sender; // Create menu to show layer options. PopupMenu layerMenu = new PopupMenu(this, loadButton); layerMenu.MenuItemClick += LayerMenu_LayerSelected; // Create menu options. int index = 0; foreach (OgcFeatureCollectionInfo layerInfo in _serviceInfo.FeatureCollectionInfos) { layerMenu.Menu.Add(0, index, index, layerInfo.Title); index++; } // Show menu in the view. layerMenu.Show(); } private void ServiceClicked(object sender, EventArgs e) { // Create a text-entry prompt for changing the WFS url. AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.SetTitle("Set OGC API service URL"); // Create the text entry. _urlEntry = new EditText(this); _urlEntry.Text = string.Empty; _urlEntry.InputType = Android.Text.InputTypes.TextVariationUri; builder.SetView(_urlEntry); // Finish building the dialog and display it. builder.SetPositiveButton("Load", ServicePressed); builder.SetCancelable(true); builder.Show(); } private void ServicePressed(object sender, DialogClickEventArgs e) { LoadService(_urlEntry.Text); } private Renderer GetRendererForTable(FeatureTable table) { switch (table.GeometryType) { case GeometryType.Point: case GeometryType.Multipoint: return new SimpleRenderer(new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, Color.Blue, 4)); case GeometryType.Polygon: case GeometryType.Envelope: return new SimpleRenderer(new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, Color.Blue, null)); case GeometryType.Polyline: return new SimpleRenderer(new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Blue, 1)); } return null; } private void CreateLayout() { // Create a new vertical layout for the app. var layout = new LinearLayout(this) { Orientation = Orientation.Vertical }; // Add the button. _loadServiceButton = new Button(this); _loadServiceButton.Text = "Load service"; _loadServiceButton.Click += ServiceClicked; _loadServiceButton.Enabled = false; layout.AddView(_loadServiceButton); // Add the button. _loadLayerButton = new Button(this); _loadLayerButton.Text = "Choose a layer"; _loadLayerButton.Click += ChooseLayer_Clicked; _loadLayerButton.Enabled = false; layout.AddView(_loadLayerButton); // Add the loading indicator. _loadingProgressBar = new ProgressBar(this); _loadingProgressBar.Indeterminate = true; _loadingProgressBar.Visibility = ViewStates.Gone; layout.AddView(_loadingProgressBar); // Add the map view to the layout. _myMapView = new MapView(this); layout.AddView(_myMapView); // Show the layout in the app. SetContentView(layout); } } }
/* Copyright (c) 2017 Marcin Szeniak (https://github.com/Klocman/) Apache License Version 2.0 */ using System; using System.IO; using System.Linq; using System.Text; using Ionic.Zip; using Klocman.Tools; using TextToScreen.Misc; using TextToScreen.Properties; namespace TextToScreen.SongFile { public sealed class SongFileEntry : IDisposable { private string _comment; private string _contents; private string _group; private string _name; private bool _savedToDisk; internal SongFileCollection ParentCollection; private DateTime _creationTime; private DateTime _lastModified; public SongFileEntry(string filename, string fileGroup, string fileContents, string fileComment, DateTime lastModifiedDate, DateTime creationDate) { _name = filename; _group = fileGroup; Contents = fileContents; _comment = fileComment ?? string.Empty; LastModified = lastModifiedDate; CreationTime = creationDate; SavedToDisk = true; } /// <summary> /// Copy constructor /// </summary> public SongFileEntry(SongFileEntry source) { CopyValuesFromSource(source); } public SongFileEntry(ZipEntry entry) { if (entry == null) throw new ArgumentNullException(); var fn = entry.FileName; _name = Path.GetFileNameWithoutExtension(fn); _group = Path.GetDirectoryName(fn); using (var memoryStream = new MemoryStream()) { entry.Extract(memoryStream); using (var reader = new StreamReader(memoryStream)) { memoryStream.Position = 0; Contents = reader.ReadToEnd(); } } _comment = entry.Comment ?? string.Empty; LastModified = entry.LastModified; CreationTime = entry.CreationTime; SavedToDisk = true; } public static string NewVerse { get; } = "\r\n@"; public string Comment { get { return _comment; } set { if (_comment.Equals(value)) return; _comment = value; SavedToDisk = false; } } public string Contents { get { return _contents; } set { if (ReferenceEquals(_contents, value)) return; _contents = value?.Replace("\r", string.Empty).Replace("\n", "\r\n") ?? string.Empty; SavedToDisk = false; } } public DateTime CreationTime { get { return GetFileDateSafe(_creationTime); } private set { _creationTime = GetFileDateSafe(value); } } private static DateTime GetFileDateSafe(DateTime value) { return Math.Abs(value.Year - 2000) > 1500 ? new DateTime(2000, 1, 1) : value; } public string Group { get { return _group; } set { if (!_group.Equals(value)) { _group = value; SavedToDisk = false; } } } public DateTime LastModified { get { return GetFileDateSafe(_lastModified); } private set { _lastModified = GetFileDateSafe(value); } } /// <summary> /// Will throw ArgumentExceptions if name contains invalid filename chars /// or if it's already taken in the parent collection (if its set). /// </summary> public string Name { get { return _name; } set { if (_name.Equals(value)) return; switch (CheckName(value)) { case NameChangeResult.Empty: throw new ArgumentException(Localisation.NameIsEmpty); case NameChangeResult.AlreadyTaken: throw new ArgumentException(Localisation.NameIsAlreadyTaken); case NameChangeResult.InvalidChars: throw new ArgumentException(Localisation.NameContainsInvalidChars); } _name = value; SavedToDisk = false; } } public bool SavedToDisk { get { return _savedToDisk; } set { _savedToDisk = value; if (value) return; LastModified = DateTime.Now; ParentCollection?.OnItemModified(this); } } public void Dispose() { ParentCollection = null; } public void AddToArchive(ZipFile archive) { if (archive == null) throw new ArgumentNullException(); var sb = new StringBuilder(); if (!string.IsNullOrEmpty(_group)) { sb.Append(_group); sb.Append(Path.DirectorySeparatorChar); } sb.Append(_name); sb.Append(Resources.SongFileExtension); var ze = archive.AddEntry(sb.ToString(), Contents, Encoding.UTF8); ze.Comment = _comment; ze.CreationTime = CreationTime; ze.LastModified = LastModified; } public NameChangeResult CheckName(string nameToCheck) { if (string.IsNullOrEmpty(nameToCheck)) return NameChangeResult.Empty; if (nameToCheck.Any(x => StringTools.InvalidFileNameChars.Contains(x))) return NameChangeResult.InvalidChars; if (ParentCollection != null && ParentCollection.Names.Contains(nameToCheck)) return NameChangeResult.AlreadyTaken; return NameChangeResult.Ok; } public void CopyValuesFromSource(SongFileEntry source) { if (source == null) throw new ArgumentNullException(); _name = source.Name; _group = source.Group; Contents = source.Contents; _comment = source.Comment ?? string.Empty; LastModified = source.LastModified; CreationTime = source.CreationTime; SavedToDisk = source.SavedToDisk; } public override string ToString() { return string.Format(Localisation.SongFileArchive_ToString_Format, Name, LastModified, CreationTime, string.IsNullOrEmpty(Comment) ? Localisation.SongFileArchive_ToString_MissingComment : Comment) + Environment.NewLine + Environment.NewLine + Contents.Trim().Replace(NewVerse, Environment.NewLine + Environment.NewLine); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using System.Threading; using static Tax_Informer.MyGlobal; namespace Tax_Informer.Core { //TODO: Find a way to localize the currentWebsite into IAnalysisModule interface IAnalysisModule { void ReadIndexPage(string uid, string websiteKey, string indexPageLink, IUiArticalOverviewResponseHandler responseHandler, bool isForced = false); void ReadArtical(string uid, string websiteKey, ArticalOverview overview, IUiArticalResponseHandler responseHandler, bool isForced = false); void ReadAuthor(string uid, string websiteKey, Author author, IUiArticalOverviewResponseHandler responseHandler, bool isForced = false); void ReadCategory(string uid, string websiteKey, Category category, IUiArticalOverviewResponseHandler responseHandler, bool isForced = false); void CancleRequest(List<string> UId); } class AnalysisModule : IAnalysisModule, IResponseHandler { private Queue<RequestPacket> pendingRequest = new Queue<RequestPacket>(); private Queue<RequestPacket> pendingResponse = new Queue<RequestPacket>(); private Queue<RequestPacket> cancleRequest = new Queue<RequestPacket>(); public void RequestProcessingError(RequestPacket requestPacket) { throw new NotImplementedException(); } public void CancleRequest(List<string> UId) { RequestPacket packet = new RequestPacket(); packet.DataInStringList = UId; cancleRequest.Enqueue(packet); } public void RequestProcessedCallback(RequestPacket requestPacket) { pendingResponse.Enqueue(requestPacket); } private void originalResponse(RequestPacket packet) { MyLog.Log(this, nameof(originalResponse) + packet.Url + "..."); var data = packet.DataInString; HtmlAgilityPack.HtmlDocument doc = null; if (!string.IsNullOrEmpty(data)) { MyLog.Log(this, "Loading HTML data" + "..."); doc = new HtmlAgilityPack.HtmlDocument(); doc.LoadHtml(data); MyLog.Log(this, "Loading HTML data" + "...Done"); } var currentWebsite = Config.GetWebsite(packet.WebsiteKey); var overviewType = packet.OverviewType; if (overviewType == OverviewType.Null) { //Artical Artical artical = null; MyLog.Log(this, "Reading artical" + "..."); if (doc != null) artical = currentWebsite.ReadArtical(packet.Tag as ArticalOverview, doc); else artical = currentWebsite.ReadArticalExtrnal(packet.Tag as ArticalOverview, packet.ExtrnalLink); MyLog.Log(this, "Reading artical" + "...Done"); MyLog.Log(this, "Making callback on artical" + "..."); packet.AnalisisModuleResponseUiArtical .ArticalProcessedCallback (packet.Uid, packet.Url, artical); MyLog.Log(this, "Making callback on artical" + "...Done"); } else { string nextPage = string.Empty; switch (overviewType) { case OverviewType.Null: break; case OverviewType.UNKNOWN: break; case OverviewType.IndexPage: MyLog.Log(this, "Reading index page data" + "..."); var iData = currentWebsite.ReadIndexPage(packet.Url, doc, out nextPage); MyLog.Log(this, "Reading index page data" + "...Done"); MyLog.Log(this, "Making index page callback" + "..."); packet.AnalisisModuleResponseUiArticalOverview .ArticalOverviewProcessedCallback (packet.Uid, packet.Url, iData, overviewType, nextPage); MyLog.Log(this, "Making index page callback" + "...Done"); break; case OverviewType.Author: MyLog.Log(this, "Reading author page data" + "..."); var aData = currentWebsite.ReadAuthor(packet.Tag as Author, doc, out nextPage); MyLog.Log(this, "Reading author page data" + "...Done"); MyLog.Log(this, "Making author page callback" + "..."); packet.AnalisisModuleResponseUiArticalOverview .ArticalOverviewProcessedCallback (packet.Uid, packet.Url, aData, overviewType, nextPage); MyLog.Log(this, "Making author page callback" + "...Done"); break; case OverviewType.Category: MyLog.Log(this, "Reading category page data" + "..."); var cData = currentWebsite.ReadCategory(packet.Tag as Category, doc, out nextPage); MyLog.Log(this, "Reading category page data" + "...Done"); MyLog.Log(this, "Making category page callback" + "..."); packet.AnalisisModuleResponseUiArticalOverview .ArticalOverviewProcessedCallback (packet.Uid, packet.Url, cData, overviewType, nextPage); MyLog.Log(this, "Making category page callback" + "...Done"); break; default: break; } if (nextPage != null && nextPage != string.Empty) { //TODO: Think how to hold the next page info } } MyLog.Log(this, nameof(originalResponse) + packet.Url + "...Done"); } private void processData() { while (IsRunning) { try { if (cancleRequest.Count > 0) { offlineModule.CancleRequest(cancleRequest.Dequeue()); } if (pendingRequest.Count > 0) { var reqObj = pendingRequest.Dequeue(); MyLog.Log(this, $"Passing request packet {reqObj.Url}" + "..."); offlineModule.RequestData(reqObj, this); MyLog.Log(this, $"Passing request packet {reqObj.Url}" + "...Done"); } if (pendingResponse.Count > 0) { var responsePacket = pendingResponse.Dequeue(); MyLog.Log(this, $"Response received on packet {responsePacket.Url}" + "..."); originalResponse(responsePacket); MyLog.Log(this, $"Response received on packet {responsePacket.Url}" + "...Done"); responsePacket.Dispose(); } } catch (Exception ex) { MyLog.Log(this, "--Error " + ex.Message); } Thread.Sleep(1); } } public void ReadIndexPage(string uid, string websiteKey, string indexPageLink, IUiArticalOverviewResponseHandler responseHandler, bool isForced = false) { MyLog.Log(this, nameof(ReadIndexPage) + "..."); pendingRequest.Enqueue( RequestPacket.CreatePacket(uid, websiteKey, indexPageLink, isForced, RequestPacketOwners.AnalysisModule, OverviewType.IndexPage, responseHandler)); MyLog.Log(this, nameof(ReadIndexPage) + "...Done"); } public void ReadArtical(string uid, string websiteKey, ArticalOverview overview, IUiArticalResponseHandler responseHandler, bool isForced = false) { MyLog.Log(this, nameof(ReadArtical) + "..."); pendingRequest.Enqueue( RequestPacket.CreatePacket(uid, websiteKey, overview.LinkOfActualArtical, isForced, RequestPacketOwners.AnalysisModule, responseHandler).AddTag(overview)); MyLog.Log(this, nameof(ReadArtical) + "...Done"); } public void ReadAuthor(string uid, string websiteKey, Author author, IUiArticalOverviewResponseHandler responseHandler, bool isForced = false) { MyLog.Log(this, nameof(ReadAuthor) + "..."); pendingRequest.Enqueue( RequestPacket.CreatePacket(uid, websiteKey, author.Link, isForced, RequestPacketOwners.AnalysisModule, OverviewType.Author, responseHandler).AddTag(author)); MyLog.Log(this, nameof(ReadAuthor) + "...Done"); } public void ReadCategory(string uid, string websiteKey, Category category, IUiArticalOverviewResponseHandler responseHandler, bool isForced = false) { MyLog.Log(this, nameof(ReadCategory) + "..."); pendingRequest.Enqueue( RequestPacket.CreatePacket(uid, websiteKey, category.Link, isForced, RequestPacketOwners.AnalysisModule, OverviewType.Category, responseHandler).AddTag(category)); MyLog.Log(this, nameof(ReadCategory) + "...Done"); } public AnalysisModule() { Thread th = new Thread(processData); th.Name = "Analysis Processing Thread"; th.Priority = System.Threading.ThreadPriority.Highest; th.Start(); } } }
using System; using UIKit; using CoreGraphics; namespace IQAudioRecorderController { public class SCSiriWaveformView : UIView { #region Fields private nuint _NumberOfWaves; private UIColor _WaveColor; private nfloat _PrimaryWaveLineWidth; private nfloat _SecondaryWaveLineWidth; private nfloat _IdleAmplitude; private nfloat _Frequency; private nfloat _Amplitude; private float _Density; private nfloat _PhaseShift; private nfloat _Phase; #endregion #region Constructors public SCSiriWaveformView() : base() { Setup(); } public SCSiriWaveformView(CGRect frame) : base(frame) { Setup(); } #endregion #region Properties public nuint NumberOfWaves { get { return this._NumberOfWaves; } set { this._NumberOfWaves = value; } } public UIColor WaveColor { get { return this._WaveColor; } set { this._WaveColor = value; } } public nfloat PrimaryWaveLineWidth { get { return this._PrimaryWaveLineWidth; } set { this._PrimaryWaveLineWidth = value; } } public nfloat SecondaryWaveLineWidth { get { return this._SecondaryWaveLineWidth; } set { this._SecondaryWaveLineWidth = value; } } public nfloat IdleAmplitude { get { return this._IdleAmplitude; } set { this._IdleAmplitude = value; } } public nfloat Frequency { get { return this._Frequency; } set { this._Frequency = value; } } public nfloat Amplitude { get { return this._Amplitude; } } public float Density { get { return this._Density; } set { this._Density = value; } } public nfloat PhaseShift { get { return this._PhaseShift; } set { this._PhaseShift = value; } } private nfloat Phase { get { return this._Phase; } set { this._Phase = value; } } #endregion #region Methods public override void AwakeFromNib() { Setup(); } private void Setup() { this.Frequency = 1.5f; this._Amplitude = 1.0f; this.IdleAmplitude = 0.01f; this.NumberOfWaves = 5; this.PhaseShift = -0.15f; this.Density = 5.0f; this.WaveColor = UIColor.White; this.PrimaryWaveLineWidth = 3.0f; this.SecondaryWaveLineWidth = 1.0f; } /// <summary> /// Updates the with level. /// </summary> /// <param name="level">Level.</param> public void UpdateWithLevel(nfloat level) { this.Phase += this.PhaseShift; this._Amplitude = (nfloat)Math.Max( level, this.IdleAmplitude); SetNeedsDisplay(); } public override void Draw(CGRect rect) { base.Draw(rect); var context = UIGraphics.GetCurrentContext(); context.ClearRect(this.Bounds); BackgroundColor.SetFill(); context.FillRect(rect); for(nuint i=0; i < this.NumberOfWaves; i++) { context = UIGraphics.GetCurrentContext(); context.SetLineWidth(i == 0 ? this.PrimaryWaveLineWidth : this.SecondaryWaveLineWidth); var halfHeight = this.Bounds.Height / 2.0f; var width = this.Bounds.Width; var mid = width / 2.0f; var maxAmplitude = halfHeight - 4.0f; // 4 corresponds to twice the stroke width // Progress is a value between 1.0 and -0.5, determined by the current wave idx, which is used to alter the wave's amplitude. var progress = 1.0f - ((float)i / (float)this.NumberOfWaves); var normedAmplitude = (1.5f * progress - 0.5f) * this.Amplitude; var multiplier = Math.Min(1.0, (progress / 3.0f * 2.0f) + (1.0f / 3.0f)); this.WaveColor.ColorWithAlpha ((nfloat)multiplier * this.WaveColor.CGColor.Alpha).SetStroke (); for(float x = 0; x < width + this.Density; x += this.Density) { // We use a parable to scale the sinus wave, that has its peak in the middle of the view. var scaling = -Math.Pow(1.0f / mid * (x - mid), 2.0f) + 1.0f; var y = scaling * maxAmplitude * normedAmplitude * Math.Sin(2 * Math.PI * (x / width) * this.Frequency + this.Phase) + halfHeight; y = y+i; if (x == 0) { context.MoveTo( (nfloat)x, (nfloat)y); } else { context.AddLineToPoint((nfloat)x, (nfloat)y); } } context.StrokePath(); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle; namespace System.Net.Http { internal class WinHttpRequestStream : Stream { private static byte[] s_crLfTerminator = new byte[] { 0x0d, 0x0a }; // "\r\n" private static byte[] s_endChunk = new byte[] { 0x30, 0x0d, 0x0a, 0x0d, 0x0a }; // "0\r\n\r\n" private volatile bool _disposed; private WinHttpRequestState _state; private bool _chunkedMode; // TODO (Issue 2505): temporary pinned buffer caches of 1 item. Will be replaced by PinnableBufferCache. private GCHandle _cachedSendPinnedBuffer; internal WinHttpRequestStream(WinHttpRequestState state, bool chunkedMode) { _state = state; _chunkedMode = chunkedMode; } public override bool CanRead { get { return false; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return !_disposed; } } public override long Length { get { CheckDisposed(); throw new NotSupportedException(); } } public override long Position { get { CheckDisposed(); throw new NotSupportedException(); } set { CheckDisposed(); throw new NotSupportedException(); } } public override void Flush() { // Nothing to do. } public override Task FlushAsync(CancellationToken cancellationToken) { return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : Task.CompletedTask; } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken token) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (count > buffer.Length - offset) { throw new ArgumentException(nameof(buffer)); } if (token.IsCancellationRequested) { var tcs = new TaskCompletionSource<int>(); tcs.TrySetCanceled(token); return tcs.Task; } CheckDisposed(); if (_state.TcsInternalWriteDataToRequestStream != null && !_state.TcsInternalWriteDataToRequestStream.Task.IsCompleted) { throw new InvalidOperationException(SR.net_http_no_concurrent_io_allowed); } return InternalWriteAsync(buffer, offset, count, token); } public override void Write(byte[] buffer, int offset, int count) { WriteAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult(); } public override long Seek(long offset, SeekOrigin origin) { CheckDisposed(); throw new NotSupportedException(); } public override void SetLength(long value) { CheckDisposed(); throw new NotSupportedException(); } public override int Read(byte[] buffer, int offset, int count) { CheckDisposed(); throw new NotSupportedException(); } internal async Task EndUploadAsync(CancellationToken token) { if (_chunkedMode) { await InternalWriteDataAsync(s_endChunk, 0, s_endChunk.Length, token).ConfigureAwait(false); } } protected override void Dispose(bool disposing) { if (!_disposed) { _disposed = true; // TODO (Issue 2508): Pinned buffers must be released in the callback, when it is guaranteed no further // operations will be made to the send/receive buffers. if (_cachedSendPinnedBuffer.IsAllocated) { _cachedSendPinnedBuffer.Free(); } } base.Dispose(disposing); } private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(this.GetType().FullName); } } private Task InternalWriteAsync(byte[] buffer, int offset, int count, CancellationToken token) { return _chunkedMode ? InternalWriteChunkedModeAsync(buffer, offset, count, token) : InternalWriteDataAsync(buffer, offset, count, token); } private async Task InternalWriteChunkedModeAsync(byte[] buffer, int offset, int count, CancellationToken token) { // WinHTTP does not fully support chunked uploads. It simply allows one to omit the 'Content-Length' header // and instead use the 'Transfer-Encoding: chunked' header. The caller is still required to encode the // request body according to chunking rules. Debug.Assert(_chunkedMode); string chunkSizeString = String.Format("{0:x}\r\n", count); byte[] chunkSize = Encoding.UTF8.GetBytes(chunkSizeString); await InternalWriteDataAsync(chunkSize, 0, chunkSize.Length, token).ConfigureAwait(false); await InternalWriteDataAsync(buffer, offset, count, token).ConfigureAwait(false); await InternalWriteDataAsync(s_crLfTerminator, 0, s_crLfTerminator.Length, token).ConfigureAwait(false); } private Task<bool> InternalWriteDataAsync(byte[] buffer, int offset, int count, CancellationToken token) { Debug.Assert(count >= 0); if (count == 0) { return Task.FromResult<bool>(true); } // TODO (Issue 2505): replace with PinnableBufferCache. if (!_cachedSendPinnedBuffer.IsAllocated || _cachedSendPinnedBuffer.Target != buffer) { if (_cachedSendPinnedBuffer.IsAllocated) { _cachedSendPinnedBuffer.Free(); } _cachedSendPinnedBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned); } _state.TcsInternalWriteDataToRequestStream = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); lock (_state.Lock) { if (!Interop.WinHttp.WinHttpWriteData( _state.RequestHandle, Marshal.UnsafeAddrOfPinnedArrayElement(buffer, offset), (uint)count, IntPtr.Zero)) { _state.TcsInternalWriteDataToRequestStream.TrySetException( new IOException(SR.net_http_io_write, WinHttpException.CreateExceptionUsingLastError())); } } // TODO: Issue #2165. Register callback on cancellation token to cancel WinHTTP operation. return _state.TcsInternalWriteDataToRequestStream.Task; } } }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Archiver.Codecs { public class StopReplicationRequestEncoder { public const ushort BLOCK_LENGTH = 24; public const ushort TEMPLATE_ID = 51; public const ushort SCHEMA_ID = 101; public const ushort SCHEMA_VERSION = 6; private StopReplicationRequestEncoder _parentMessage; private IMutableDirectBuffer _buffer; protected int _offset; protected int _limit; public StopReplicationRequestEncoder() { _parentMessage = this; } public ushort SbeBlockLength() { return BLOCK_LENGTH; } public ushort SbeTemplateId() { return TEMPLATE_ID; } public ushort SbeSchemaId() { return SCHEMA_ID; } public ushort SbeSchemaVersion() { return SCHEMA_VERSION; } public string SbeSemanticType() { return ""; } public IMutableDirectBuffer Buffer() { return _buffer; } public int Offset() { return _offset; } public StopReplicationRequestEncoder Wrap(IMutableDirectBuffer buffer, int offset) { this._buffer = buffer; this._offset = offset; Limit(offset + BLOCK_LENGTH); return this; } public StopReplicationRequestEncoder WrapAndApplyHeader( IMutableDirectBuffer buffer, int offset, MessageHeaderEncoder headerEncoder) { headerEncoder .Wrap(buffer, offset) .BlockLength(BLOCK_LENGTH) .TemplateId(TEMPLATE_ID) .SchemaId(SCHEMA_ID) .Version(SCHEMA_VERSION); return Wrap(buffer, offset + MessageHeaderEncoder.ENCODED_LENGTH); } public int EncodedLength() { return _limit - _offset; } public int Limit() { return _limit; } public void Limit(int limit) { this._limit = limit; } public static int ControlSessionIdEncodingOffset() { return 0; } public static int ControlSessionIdEncodingLength() { return 8; } public static long ControlSessionIdNullValue() { return -9223372036854775808L; } public static long ControlSessionIdMinValue() { return -9223372036854775807L; } public static long ControlSessionIdMaxValue() { return 9223372036854775807L; } public StopReplicationRequestEncoder ControlSessionId(long value) { _buffer.PutLong(_offset + 0, value, ByteOrder.LittleEndian); return this; } public static int CorrelationIdEncodingOffset() { return 8; } public static int CorrelationIdEncodingLength() { return 8; } public static long CorrelationIdNullValue() { return -9223372036854775808L; } public static long CorrelationIdMinValue() { return -9223372036854775807L; } public static long CorrelationIdMaxValue() { return 9223372036854775807L; } public StopReplicationRequestEncoder CorrelationId(long value) { _buffer.PutLong(_offset + 8, value, ByteOrder.LittleEndian); return this; } public static int ReplicationIdEncodingOffset() { return 16; } public static int ReplicationIdEncodingLength() { return 8; } public static long ReplicationIdNullValue() { return -9223372036854775808L; } public static long ReplicationIdMinValue() { return -9223372036854775807L; } public static long ReplicationIdMaxValue() { return 9223372036854775807L; } public StopReplicationRequestEncoder ReplicationId(long value) { _buffer.PutLong(_offset + 16, value, ByteOrder.LittleEndian); return this; } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { StopReplicationRequestDecoder writer = new StopReplicationRequestDecoder(); writer.Wrap(_buffer, _offset, BLOCK_LENGTH, SCHEMA_VERSION); return writer.AppendTo(builder); } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace EduHub.Data.Entities { /// <summary> /// Asset Depreciation Methods /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class KADM : EduHubEntity { #region Foreign Navigation Properties private IReadOnlyList<AKC> Cache_KADMKEY_AKC_DEPN_AMETHOD; private IReadOnlyList<AKC> Cache_KADMKEY_AKC_DEPN_TMETHOD; private IReadOnlyList<AKCT> Cache_KADMKEY_AKCT_DEPN_TMETHOD; private IReadOnlyList<AR> Cache_KADMKEY_AR_AMETHOD; private IReadOnlyList<AR> Cache_KADMKEY_AR_TMETHOD; private IReadOnlyList<ARF> Cache_KADMKEY_ARF_AMETHOD; private IReadOnlyList<ARF> Cache_KADMKEY_ARF_TMETHOD; #endregion /// <inheritdoc /> public override DateTime? EntityLastModified { get { return LW_DATE; } } #region Field Properties /// <summary> /// Method Code /// [Uppercase Alphanumeric (1)] /// </summary> public string KADMKEY { get; internal set; } /// <summary> /// Method Description /// [Alphanumeric (30)] /// </summary> public string DESCRIPTION { get; internal set; } /// <summary> /// Detail description of calculation, /// eg. calculation examples /// [Memo] /// </summary> public string DETAIL { get; internal set; } /// <summary> /// Date-Based method Y/N? /// [Uppercase Alphanumeric (1)] /// </summary> public string DATE_BASED { get; internal set; } /// <summary> /// Is this method used for tax depreciation Y/N? /// [Uppercase Alphanumeric (1)] /// </summary> public string TAX { get; internal set; } /// <summary> /// Last write date /// </summary> public DateTime? LW_DATE { get; internal set; } /// <summary> /// Last write time /// </summary> public short? LW_TIME { get; internal set; } /// <summary> /// Last operator /// [Uppercase Alphanumeric (128)] /// </summary> public string LW_USER { get; internal set; } #endregion #region Foreign Navigation Properties /// <summary> /// AKC (Assets - Categories) related entities by [KADM.KADMKEY]-&gt;[AKC.DEPN_AMETHOD] /// Method Code /// </summary> public IReadOnlyList<AKC> KADMKEY_AKC_DEPN_AMETHOD { get { if (Cache_KADMKEY_AKC_DEPN_AMETHOD == null && !Context.AKC.TryFindByDEPN_AMETHOD(KADMKEY, out Cache_KADMKEY_AKC_DEPN_AMETHOD)) { Cache_KADMKEY_AKC_DEPN_AMETHOD = new List<AKC>().AsReadOnly(); } return Cache_KADMKEY_AKC_DEPN_AMETHOD; } } /// <summary> /// AKC (Assets - Categories) related entities by [KADM.KADMKEY]-&gt;[AKC.DEPN_TMETHOD] /// Method Code /// </summary> public IReadOnlyList<AKC> KADMKEY_AKC_DEPN_TMETHOD { get { if (Cache_KADMKEY_AKC_DEPN_TMETHOD == null && !Context.AKC.TryFindByDEPN_TMETHOD(KADMKEY, out Cache_KADMKEY_AKC_DEPN_TMETHOD)) { Cache_KADMKEY_AKC_DEPN_TMETHOD = new List<AKC>().AsReadOnly(); } return Cache_KADMKEY_AKC_DEPN_TMETHOD; } } /// <summary> /// AKCT (Assets - Categories Tax) related entities by [KADM.KADMKEY]-&gt;[AKCT.DEPN_TMETHOD] /// Method Code /// </summary> public IReadOnlyList<AKCT> KADMKEY_AKCT_DEPN_TMETHOD { get { if (Cache_KADMKEY_AKCT_DEPN_TMETHOD == null && !Context.AKCT.TryFindByDEPN_TMETHOD(KADMKEY, out Cache_KADMKEY_AKCT_DEPN_TMETHOD)) { Cache_KADMKEY_AKCT_DEPN_TMETHOD = new List<AKCT>().AsReadOnly(); } return Cache_KADMKEY_AKCT_DEPN_TMETHOD; } } /// <summary> /// AR (Assets) related entities by [KADM.KADMKEY]-&gt;[AR.AMETHOD] /// Method Code /// </summary> public IReadOnlyList<AR> KADMKEY_AR_AMETHOD { get { if (Cache_KADMKEY_AR_AMETHOD == null && !Context.AR.TryFindByAMETHOD(KADMKEY, out Cache_KADMKEY_AR_AMETHOD)) { Cache_KADMKEY_AR_AMETHOD = new List<AR>().AsReadOnly(); } return Cache_KADMKEY_AR_AMETHOD; } } /// <summary> /// AR (Assets) related entities by [KADM.KADMKEY]-&gt;[AR.TMETHOD] /// Method Code /// </summary> public IReadOnlyList<AR> KADMKEY_AR_TMETHOD { get { if (Cache_KADMKEY_AR_TMETHOD == null && !Context.AR.TryFindByTMETHOD(KADMKEY, out Cache_KADMKEY_AR_TMETHOD)) { Cache_KADMKEY_AR_TMETHOD = new List<AR>().AsReadOnly(); } return Cache_KADMKEY_AR_TMETHOD; } } /// <summary> /// ARF (Asset Financial Transactions) related entities by [KADM.KADMKEY]-&gt;[ARF.AMETHOD] /// Method Code /// </summary> public IReadOnlyList<ARF> KADMKEY_ARF_AMETHOD { get { if (Cache_KADMKEY_ARF_AMETHOD == null && !Context.ARF.TryFindByAMETHOD(KADMKEY, out Cache_KADMKEY_ARF_AMETHOD)) { Cache_KADMKEY_ARF_AMETHOD = new List<ARF>().AsReadOnly(); } return Cache_KADMKEY_ARF_AMETHOD; } } /// <summary> /// ARF (Asset Financial Transactions) related entities by [KADM.KADMKEY]-&gt;[ARF.TMETHOD] /// Method Code /// </summary> public IReadOnlyList<ARF> KADMKEY_ARF_TMETHOD { get { if (Cache_KADMKEY_ARF_TMETHOD == null && !Context.ARF.TryFindByTMETHOD(KADMKEY, out Cache_KADMKEY_ARF_TMETHOD)) { Cache_KADMKEY_ARF_TMETHOD = new List<ARF>().AsReadOnly(); } return Cache_KADMKEY_ARF_TMETHOD; } } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsAzureCompositeModelClient { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// Composite Swagger Client that represents merging body complex and /// complex model swagger clients /// </summary> public partial class AzureCompositeModel : ServiceClient<AzureCompositeModel>, IAzureCompositeModel, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Gets Azure subscription credentials. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Subscription ID. /// </summary> public string SubscriptionId { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IBasicOperations. /// </summary> public virtual IBasicOperations Basic { get; private set; } /// <summary> /// Gets the IPrimitiveOperations. /// </summary> public virtual IPrimitiveOperations Primitive { get; private set; } /// <summary> /// Gets the IArrayOperations. /// </summary> public virtual IArrayOperations Array { get; private set; } /// <summary> /// Gets the IDictionaryOperations. /// </summary> public virtual IDictionaryOperations Dictionary { get; private set; } /// <summary> /// Gets the IInheritanceOperations. /// </summary> public virtual IInheritanceOperations Inheritance { get; private set; } /// <summary> /// Gets the IPolymorphismOperations. /// </summary> public virtual IPolymorphismOperations Polymorphism { get; private set; } /// <summary> /// Gets the IPolymorphicrecursiveOperations. /// </summary> public virtual IPolymorphicrecursiveOperations Polymorphicrecursive { get; private set; } /// <summary> /// Gets the IReadonlypropertyOperations. /// </summary> public virtual IReadonlypropertyOperations Readonlyproperty { get; private set; } /// <summary> /// Initializes a new instance of the AzureCompositeModel class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AzureCompositeModel(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AzureCompositeModel class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AzureCompositeModel(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AzureCompositeModel class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AzureCompositeModel(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AzureCompositeModel class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AzureCompositeModel(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AzureCompositeModel class. /// </summary> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AzureCompositeModel(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AzureCompositeModel class. /// </summary> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AzureCompositeModel(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AzureCompositeModel class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AzureCompositeModel(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AzureCompositeModel class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AzureCompositeModel(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.Basic = new BasicOperations(this); this.Primitive = new PrimitiveOperations(this); this.Array = new ArrayOperations(this); this.Dictionary = new DictionaryOperations(this); this.Inheritance = new InheritanceOperations(this); this.Polymorphism = new PolymorphismOperations(this); this.Polymorphicrecursive = new PolymorphicrecursiveOperations(this); this.Readonlyproperty = new ReadonlypropertyOperations(this); this.BaseUri = new Uri("http://localhost"); this.SubscriptionId = "123456"; this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<Fish>("fishtype")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<Fish>("fishtype")); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } /// <summary> /// Product Types /// </summary> /// The Products endpoint returns information about the Uber products offered /// at a given location. The response includes the display name and other /// details about each product, and lists the products in the proper display /// order. /// <param name='resourceGroupName'> /// Resource Group ID. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<CatalogArray>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } string apiVersion = "2014-04-01-preview"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/Microsoft.Cache/Redis").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<CatalogArray>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<CatalogArray>(_responseContent, this.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Create products /// </summary> /// Resets products. /// <param name='subscriptionId'> /// Subscription ID. /// </param> /// <param name='resourceGroupName'> /// Resource Group ID. /// </param> /// <param name='productDictionaryOfArray'> /// Dictionary of Array of product /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<CatalogDictionary>> CreateWithHttpMessagesAsync(string subscriptionId, string resourceGroupName, IDictionary<string, IList<Product>> productDictionaryOfArray = default(IDictionary<string, IList<Product>>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (subscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } string apiVersion = "2014-04-01-preview"; CatalogDictionaryOfArray bodyParameter = new CatalogDictionaryOfArray(); if (productDictionaryOfArray != null) { bodyParameter.ProductDictionaryOfArray = productDictionaryOfArray; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("subscriptionId", subscriptionId); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("bodyParameter", bodyParameter); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/Microsoft.Cache/Redis").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(subscriptionId)); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(bodyParameter != null) { _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<CatalogDictionary>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<CatalogDictionary>(_responseContent, this.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Update products /// </summary> /// Resets products. /// <param name='subscriptionId'> /// Subscription ID. /// </param> /// <param name='resourceGroupName'> /// Resource Group ID. /// </param> /// <param name='productArrayOfDictionary'> /// Array of dictionary of products /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<CatalogArray>> UpdateWithHttpMessagesAsync(string subscriptionId, string resourceGroupName, IList<IDictionary<string, Product>> productArrayOfDictionary = default(IList<IDictionary<string, Product>>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (subscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } string apiVersion = "2014-04-01-preview"; CatalogArrayOfDictionary bodyParameter = new CatalogArrayOfDictionary(); if (productArrayOfDictionary != null) { bodyParameter.ProductArrayOfDictionary = productArrayOfDictionary; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("subscriptionId", subscriptionId); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("bodyParameter", bodyParameter); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/Microsoft.Cache/Redis").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(subscriptionId)); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(bodyParameter != null) { _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<CatalogArray>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<CatalogArray>(_responseContent, this.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; using Xunit; namespace System.Security.Cryptography.Cng.Tests { public static class SymmetricCngTestHelpers { // The ephemeral key has already been validated by the AesCipherTests suite. // Therefore we can use the ephemeral key to validate the persisted key. internal static void VerifyPersistedKey( CngAlgorithm algorithm, int keySize, int plainBytesCount, Func<string, SymmetricAlgorithm> persistedFunc, Func<SymmetricAlgorithm> ephemeralFunc, CipherMode cipherMode, PaddingMode paddingMode) { string keyName = Guid.NewGuid().ToString(); CngKeyCreationParameters creationParameters = new CngKeyCreationParameters { Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider, ExportPolicy = CngExportPolicies.AllowPlaintextExport, Parameters = { new CngProperty("Length", BitConverter.GetBytes(keySize), CngPropertyOptions.None), } }; CngKey cngKey = CngKey.Create(algorithm, keyName, creationParameters); try { VerifyPersistedKey( keyName, plainBytesCount, persistedFunc, ephemeralFunc, cipherMode, paddingMode); } finally { // Delete also Disposes the key, no using should be added here. cngKey.Delete(); } } internal static void VerifyPersistedKey( string keyName, int plainBytesCount, Func<string, SymmetricAlgorithm> persistedFunc, Func<SymmetricAlgorithm> ephemeralFunc, CipherMode cipherMode, PaddingMode paddingMode) { byte[] plainBytes = GenerateRandom(plainBytesCount); using (SymmetricAlgorithm persisted = persistedFunc(keyName)) using (SymmetricAlgorithm ephemeral = ephemeralFunc()) { persisted.Mode = ephemeral.Mode = cipherMode; persisted.Padding = ephemeral.Padding = paddingMode; ephemeral.Key = persisted.Key; ephemeral.GenerateIV(); persisted.IV = ephemeral.IV; using (ICryptoTransform persistedEncryptor = persisted.CreateEncryptor()) using (ICryptoTransform persistedDecryptor = persisted.CreateDecryptor()) using (ICryptoTransform ephemeralEncryptor = ephemeral.CreateEncryptor()) { Assert.True( persistedEncryptor.CanTransformMultipleBlocks, "Pre-condition: persistedEncryptor.CanTransformMultipleBlocks"); byte[] persistedEncrypted = persistedEncryptor.TransformFinalBlock(plainBytes, 0, plainBytesCount); byte[] ephemeralEncrypted = ephemeralEncryptor.TransformFinalBlock(plainBytes, 0, plainBytesCount); Assert.Equal(ephemeralEncrypted, persistedEncrypted); byte[] cipherBytes = persistedEncrypted; byte[] persistedDecrypted = persistedDecryptor.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length); byte[] expectedBytes = plainBytes; if (persistedDecrypted.Length > plainBytes.Length) { // This should only ever happen in Assert.Equal(PaddingMode.Zeros, paddingMode); expectedBytes = new byte[persistedDecrypted.Length]; Buffer.BlockCopy(plainBytes, 0, expectedBytes, 0, plainBytesCount); } Assert.Equal(expectedBytes, persistedDecrypted); } } } public static void GetKey_NonExportable( CngAlgorithm algorithm, Func<string, SymmetricAlgorithm> persistedFunc) { string keyName = Guid.NewGuid().ToString(); CngKey cngKey = CngKey.Create(algorithm, keyName); try { using (SymmetricAlgorithm persisted = persistedFunc(keyName)) { Assert.ThrowsAny<CryptographicException>(() => persisted.Key); } } finally { // Delete also Disposes the key, no using should be added here. cngKey.Delete(); } } public static void SetKey_DetachesFromPersistedKey( CngAlgorithm algorithm, Func<string, SymmetricAlgorithm> persistedFunc) { // This test verifies that: // * [Algorithm]Cng.set_Key does not change the persisted key value // * [Algorithm]Cng.GenerateKey is "the same" as set_Key // * ICryptoTransform objects opened before the change do not react to it string keyName = Guid.NewGuid().ToString(); CngKey cngKey = CngKey.Create(algorithm, keyName); try { using (SymmetricAlgorithm replaceKey = persistedFunc(keyName)) using (SymmetricAlgorithm regenKey = persistedFunc(keyName)) using (SymmetricAlgorithm stable = persistedFunc(keyName)) { // Ensure that we get no padding violations on decrypting with a bad key replaceKey.Padding = regenKey.Padding = stable.Padding = PaddingMode.None; stable.GenerateIV(); // Generate (4 * 8) = 32 blocks of plaintext byte[] plainTextBytes = GenerateRandom(4 * stable.BlockSize); byte[] iv = stable.IV; regenKey.IV = replaceKey.IV = iv; byte[] encryptedBytes; using (ICryptoTransform encryptor = replaceKey.CreateEncryptor()) { encryptedBytes = encryptor.TransformFinalBlock(plainTextBytes, 0, plainTextBytes.Length); } using (ICryptoTransform replaceBefore = replaceKey.CreateDecryptor()) using (ICryptoTransform replaceBeforeDelayed = replaceKey.CreateDecryptor()) using (ICryptoTransform regenBefore = regenKey.CreateDecryptor()) using (ICryptoTransform regenBeforeDelayed = regenKey.CreateDecryptor()) using (ICryptoTransform stableBefore = stable.CreateDecryptor()) using (ICryptoTransform stableBeforeDelayed = stable.CreateDecryptor()) { // Before we regenerate the regen key it should validly decrypt AssertTransformsEqual(plainTextBytes, regenBefore, encryptedBytes); // Before we regenerate the replace key it should validly decrypt AssertTransformsEqual(plainTextBytes, replaceBefore, encryptedBytes); // The stable handle definitely should validly read before. AssertTransformsEqual(plainTextBytes, stableBefore, encryptedBytes); regenKey.GenerateKey(); replaceKey.Key = regenKey.Key; using (ICryptoTransform replaceAfter = replaceKey.CreateDecryptor()) using (ICryptoTransform regenAfter = regenKey.CreateDecryptor()) using (ICryptoTransform stableAfter = stable.CreateDecryptor()) { // All of the Befores, and the BeforeDelayed (which have not accessed their key material) // should still decrypt correctly. And so should stableAfter. AssertTransformsEqual(plainTextBytes, regenBefore, encryptedBytes); AssertTransformsEqual(plainTextBytes, regenBeforeDelayed, encryptedBytes); AssertTransformsEqual(plainTextBytes, replaceBefore, encryptedBytes); AssertTransformsEqual(plainTextBytes, replaceBeforeDelayed, encryptedBytes); AssertTransformsEqual(plainTextBytes, stableBefore, encryptedBytes); AssertTransformsEqual(plainTextBytes, stableBeforeDelayed, encryptedBytes); AssertTransformsEqual(plainTextBytes, stableAfter, encryptedBytes); // There's a 1 in 2^128 chance that the regenerated key matched the original generated key. byte[] badDecrypt = replaceAfter.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length); Assert.NotEqual(plainTextBytes, badDecrypt); // Regen and replace should come up with the same bad value, since they have the same // key value. AssertTransformsEqual(badDecrypt, regenAfter, encryptedBytes); } } // And, finally, a newly opened handle to the key is also unaffected. using (SymmetricAlgorithm openedAfter = persistedFunc(keyName)) { openedAfter.Padding = PaddingMode.None; openedAfter.IV = iv; using (ICryptoTransform decryptor = openedAfter.CreateDecryptor()) { AssertTransformsEqual(plainTextBytes, decryptor, encryptedBytes); } } } } finally { // Delete also Disposes the key, no using should be added here. cngKey.Delete(); } } public static void VerifyMachineKey( CngAlgorithm algorithm, int plainBytesCount, Func<string, SymmetricAlgorithm> persistedFunc, Func<SymmetricAlgorithm> ephemeralFunc) { string keyName = Guid.NewGuid().ToString(); CngKeyCreationParameters creationParameters = new CngKeyCreationParameters { Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider, ExportPolicy = CngExportPolicies.AllowPlaintextExport, KeyCreationOptions = CngKeyCreationOptions.MachineKey, }; CngKey cngKey = CngKey.Create(algorithm, keyName, creationParameters); try { VerifyPersistedKey( keyName, plainBytesCount, persistedFunc, ephemeralFunc, CipherMode.CBC, PaddingMode.PKCS7); } finally { // Delete also Disposes the key, no using should be added here. cngKey.Delete(); } } private static bool? s_supportsPersistedSymmetricKeys; internal static bool SupportsPersistedSymmetricKeys { get { if (!s_supportsPersistedSymmetricKeys.HasValue) { // Windows 7 (Microsoft Windows 6.1) does not support persisted symmetric keys // in the Microsoft Software KSP s_supportsPersistedSymmetricKeys = !RuntimeInformation.OSDescription.Contains("Windows 6.1"); } return s_supportsPersistedSymmetricKeys.Value; } } internal static byte[] GenerateRandom(int count) { byte[] buffer = new byte[count]; using (RandomNumberGenerator rng = RandomNumberGenerator.Create()) { rng.GetBytes(buffer); } return buffer; } internal static void AssertTransformsEqual(byte[] plainTextBytes, ICryptoTransform decryptor, byte[] encryptedBytes) { byte[] decrypted = decryptor.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length); Assert.Equal(plainTextBytes, decrypted); } } }
// jQuery.cs // Script#/Libraries/jQuery/Core // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Html; using System.Net; using System.Runtime.CompilerServices; using System.Xml; namespace jQueryApi { /// <summary> /// The global jQuery object. /// </summary> [IgnoreNamespace] [Imported] [ScriptName("$")] public static class jQuery { /// <summary> /// Gets or sets the rate (in milliseconds) at which animations fire. /// </summary> [ScriptAlias("$.fx.interval")] [IntrinsicProperty] public static int AnimationInterval { get { return 0; } set { } } /// <summary> /// Gets or sets whether animations are disabled or not. /// </summary> [ScriptAlias("$.fx.off")] [IntrinsicProperty] public static bool AnimationsDisabled { get { return false; } set { } } /// <summary> /// Gets information about the current browser and its version. /// </summary> [IntrinsicProperty] public static jQueryBrowser Browser { get { return null; } } /// <summary> /// Gets the current jQueryObject against which a plugin method is invoked. /// </summary> /// <returns>The jQueryObject represented by 'this' within a plugin.</returns> [ScriptAlias("this")] [IntrinsicProperty] [Obsolete("jQuery.Current is fragile. Migrate your code to use the methods that supply the context as a parameter.")] public static jQueryObject Current { get { return null; } } /// <summary> /// Gets the current document object wrapped into a jQuery object. /// </summary> [ScriptAlias("$(document)")] [IntrinsicProperty] public static jQueryObject Document { get { return null; } } /// <summary> /// Gets the element passed in as 'this' within a jQuery callback function. /// </summary> /// <returns>The element represented by 'this' in a callback.</returns> [ScriptAlias("this")] [IntrinsicProperty] [Obsolete("jQuery.Element is fragile. Migrate your code to use the methods that supply the context as a parameter.")] public static Element Element { get { return null; } } /// <summary> /// Gets the instance of the global jQuery object. /// </summary> [ScriptAlias("$")] [IntrinsicProperty] public static dynamic Instance { get { return null; } } /// <summary> /// Gets information about supported features and browser capabilities. /// </summary> [IntrinsicProperty] public static jQuerySupport Support { get { return null; } } /// <summary> /// Gets the element passed in as 'this' within a jQuery callback function, /// wrapped into a jQueryObject. /// </summary> /// <returns>The jQueryObject for the element represented by 'this' in a callback.</returns> [ScriptAlias("$(this)")] [IntrinsicProperty] [Obsolete("jQuery.This is fragile. Migrate your code to use the methods that supply the context as a parameter.")] public static jQueryObject This { get { return null; } } /// <summary> /// Gets the current window object wrapped into a jQuery object. /// </summary> [ScriptAlias("$(window)")] [IntrinsicProperty] public static jQueryObject Window { get { return null; } } /// <summary> /// Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax(). /// </summary> /// <param name="handler">A handler to set default values for future Ajax requests.</param> public static void AjaxPrefilter<T>(AjaxPrefilterCallback<T> handler) { } /// <summary> /// Issues an Ajax request. /// </summary> /// <param name="url">The endpoint to which the request is issued.</param> /// <returns>The jQueryXmlHttpRequest object.</returns> [ScriptName("ajax")] public static jQueryXmlHttpRequest<TData> Ajax<TData>(string url) { return null; } /// <summary> /// Issues an Ajax request. /// </summary> /// <param name="url">The endpoint to which the request is issued.</param> /// <param name="options">The options and settings for the request to invoke.</param> /// <returns>The jQueryXmlHttpRequest object.</returns> [ScriptName("ajax")] public static jQueryXmlHttpRequest<TData> Ajax<TData>(string url, jQueryAjaxOptions<TData> options) { return null; } /// <summary> /// Issues an Ajax request. /// </summary> /// <param name="options">The options and settings for the request to invoke.</param> /// <returns>The jQueryXmlHttpRequest object.</returns> [ScriptName("ajax")] public static jQueryXmlHttpRequest<TData> Ajax<TData>(jQueryAjaxOptions<TData> options) { return null; } /// <summary> /// Sets up defaults for future Ajax requests. /// </summary> /// <param name="options">The options and settings for Ajax requests.</param> public static void AjaxSetup<TData>(jQueryAjaxOptions<TData> options) { } /// <summary> /// Creates an instance of a custom jQueryEvent object that contains custom /// data members. /// </summary> /// <param name="eventName">The name of the event.</param> /// <typeparam name="TEvent">The type of the event to create.</typeparam> /// <returns>A new jQueryEvent object.</returns> [ScriptName("event")] public static TEvent CustomEvent<TEvent>(string eventName) where TEvent : jQueryEvent { return null; } /// <summary> /// Creates a new instance of a deferred object. /// </summary> [PreserveCase] [ScriptName("Deferred")] public static IjQueryDeferred<TData> Deferred<TData>() { return null; } /// <summary> /// Creates a new instance of a deferred object. /// </summary> /// <param name="initializer">An initializer callback to initialize the new deferred object.</param> [PreserveCase] [ScriptName("Deferred")] public static IjQueryDeferred<TData> Deferred<TData>(jQueryDeferredInitializer<TData> initializer) { return null; } /// <summary> /// Iterates over items in the specified array and calls the callback /// for each item in the array. /// </summary> /// <param name="items">The array to iterate over.</param> /// <param name="callback">The callback to invoke for each item.</param> public static void Each(Array items, ArrayIterationCallback callback) { } /// <summary> /// Iterates over items in the specified array and calls the callback /// for each item in the array. /// </summary> /// <param name="items">The array to iterate over.</param> /// <param name="callback">The callback to invoke for each item.</param> public static void Each<T>(List<T> items, ArrayIterationCallback<T> callback) { } /// <summary> /// Iterates over items in the specified array and calls the callback /// for each item in the array. The callback can return false to /// break the iteration. /// </summary> /// <param name="items">The array to iterate over.</param> /// <param name="callback">The callback to invoke for each item.</param> public static void Each(Array items, ArrayInterruptableIterationCallback callback) { } /// <summary> /// Iterates over items in the specified array and calls the callback /// for each item in the array. The callback can return false to /// break the iteration. /// </summary> /// <param name="items">The array to iterate over.</param> /// <param name="callback">The callback to invoke for each item.</param> public static void Each<T>(List<T> items, ArrayInterruptableIterationCallback<T> callback) { } /// <summary> /// Iterates over properties of the specified object and calls the callback /// for each property/value of the object. /// </summary> /// <param name="obj">The object whose properties are to be iterated over..</param> /// <param name="callback">The callback to invoke for each property.</param> public static void Each(Object obj, ObjectIterationCallback callback) { } /// <summary> /// Iterates over properties of the specified object and calls the callback /// for each property/value of the object. The callback can return false to /// break the iteration. /// </summary> /// <param name="obj">The object whose properties are to be iterated over..</param> /// <param name="callback">The callback to invoke for each property.</param> public static void Each(Object obj, ObjectInterruptableIterationCallback callback) { } /// <summary> /// Raises an error using the specified error message. /// </summary> /// <param name="message">The error message.</param> public static void Error(string message) { } /// <summary> /// Creates an instance of a jQueryEvent object. /// </summary> /// <param name="eventName">The name of the event.</param> /// <returns>A new jQueryEvent object.</returns> public static jQueryEvent Event(string eventName) { return null; } /// <summary> /// Merge the properties of one or more objects into the target object. /// </summary> /// <param name="target">The object that will contain the merged values.</param> /// <param name="objects">The objects to merge.</param> /// <returns>The merged object.</returns> [ExpandParams] public static object Extend(object target, params object[] objects) { return null; } /// <summary> /// Merge the properties of one or more objects into the target object. /// </summary> /// <param name="deep">True if a deep copy is to be performed.</param> /// <param name="target">The object that will contain the merged values.</param> /// <param name="objects">The objects to merge.</param> /// <returns>The merged object.</returns> [ExpandParams] public static object Extend(bool deep, object target, params object[] objects) { return null; } /// <summary> /// Merge the properties of one or more objects into the target object. /// </summary> /// <param name="target">The dictionary that will contain the merged values.</param> /// <param name="dictionaries">The dictionary to merge.</param> /// <typeparam name="TKey">The type of keys within the dictionary.</typeparam> /// <typeparam name="TValue">The type of values within the dictionary.</typeparam> /// <returns>The merged dictionary.</returns> [ScriptName("extend")] [ExpandParams] public static JsDictionary<TKey, TValue> ExtendDictionary<TKey, TValue>(JsDictionary<TKey, TValue> target, params JsDictionary<TKey, TValue>[] dictionaries) { return null; } /// <summary> /// Merge the properties of one or more objects into the target object. /// </summary> /// <param name="deep">True if a deep copy is to be performed.</param> /// <param name="target">The dictionary that will contain the merged values.</param> /// <param name="dictionaries">The dictionaries to merge.</param> /// <typeparam name="TKey">The type of keys within the dictionary.</typeparam> /// <typeparam name="TValue">The type of values within the dictionary.</typeparam> /// <returns>The merged dictionary.</returns> [ScriptName("extend")] [ExpandParams] public static JsDictionary<TKey, TValue> ExtendDictionary<TKey, TValue>(bool deep, JsDictionary<TKey, TValue> target, params JsDictionary<TKey, TValue>[] dictionaries) { return null; } /// <summary> /// Merge the properties of one or more objects into the target object. /// </summary> /// <param name="target">The object that will contain the merged values.</param> /// <param name="objects">The objects to merge.</param> /// <returns>The merged object.</returns> [ScriptName("extend")] [ExpandParams] public static T ExtendObject<T>(T target, params T[] objects) { return default(T); } /// <summary> /// Merge the properties of one or more objects into the target object. /// </summary> /// <param name="deep">True if a deep copy is to be performed.</param> /// <param name="target">The object that will contain the merged values.</param> /// <param name="objects">The objects to merge.</param> /// <returns>The merged object.</returns> [ScriptName("extend")] [ExpandParams] public static T ExtendObject<T>(bool deep, T target, params T[] objects) { return default(T); } /// <summary> /// Wraps an instance of a <see cref="jQueryObject"/> around the specified element. /// </summary> /// <param name="element">The element to wrap.</param> /// <returns>The resulting jQueryObject instance.</returns> [ScriptAlias("$")] public static jQueryObject FromElement(Element element) { return null; } /// <summary> /// Wraps an instance of a <see cref="jQueryObject"/> around the specified elements. /// </summary> /// <param name="elements">The elements to wrap.</param> /// <returns>The resulting jQueryObject instance.</returns> [ScriptAlias("$")] [ExpandParams] public static jQueryObject FromElements(params Element[] elements) { return null; } /// <summary> /// Create DOM elements on-the-fly from the provided string of raw HTML and wraps /// them into a <see cref="jQueryObject"/>. /// </summary> /// <param name="html">The HTML to parse.</param> /// <returns>The resulting jQueryObject instance.</returns> [ScriptAlias("$")] public static jQueryObject FromHtml(string html) { return null; } /// <summary> /// Create DOM elements on-the-fly from the provided string of raw HTML and wraps /// them into a <see cref="jQueryObject"/>. /// </summary> /// <param name="html">The HTML to parse.</param> /// <param name="document">The document in which the elements will be created.</param> /// <returns>The resulting jQueryObject instance.</returns> [ScriptAlias("$")] public static jQueryObject FromHtml(string html, DocumentInstance document) { return null; } /// <summary> /// Creates a DOM element from the provided string defining a single tag and wraps /// it into a <see cref="jQueryObject"/>. /// </summary> /// <param name="html">The HTML to parse.</param> /// <param name="properties">The attributes and events to set on the element.</param> /// <returns>The resulting jQueryObject instance.</returns> [ScriptAlias("$")] public static jQueryObject FromHtml(string html, JsDictionary properties) { return null; } /// <summary> /// Creates a jQueryObject from the specified object. /// </summary> /// <param name="o">The object to wrap.</param> /// <returns>The resulting jQueryObject instance.</returns> [ScriptAlias("$")] public static jQueryObject FromObject(object o) { return null; } /// <summary> /// Load data from the server using a HTTP GET request. /// </summary> /// <param name="url">The URL to request.</param> /// <returns>The jQueryXmlHttpRequest object.</returns> [ScriptName("get")] public static jQueryXmlHttpRequest<TData> Get<TData>(string url) { return null; } /// <summary> /// Load data from the server using a HTTP GET request. /// </summary> /// <param name="url">The URL to request.</param> /// <param name="callback">The callback to invoke with the response.</param> /// <returns>The jQueryXmlHttpRequest object.</returns> [ScriptName("get")] public static jQueryXmlHttpRequest<TData> Get<TData>(string url, AjaxCallback<TData> callback) { return null; } /// <summary> /// Load data from the server using a HTTP GET request. /// </summary> /// <param name="url">The URL to request.</param> /// <param name="data">A string or dictionary containing the data sent with the request.</param> /// <param name="callback">The callback to invoke with the response.</param> /// <returns>The jQueryXmlHttpRequest object.</returns> [ScriptName("get")] public static jQueryXmlHttpRequest<TData> Get<TData>(string url, object data, AjaxCallback<TData> callback) { return null; } /// <summary> /// Load data from the server using a HTTP GET request. /// </summary> /// <param name="url">The URL to request.</param> /// <param name="data">A string or dictionary containing the data sent with the request.</param> /// <param name="callback">The callback to invoke with the response.</param> /// <returns>The jQueryXmlHttpRequest object.</returns> [ScriptName("get")] public static jQueryXmlHttpRequest<TData> Get<TData>(string url, object data, AjaxRequestCallback<TData> callback) { return null; } /// <summary> /// Load data from the server using a HTTP GET request. /// </summary> /// <param name="url">The URL to request.</param> /// <param name="data">A string or dictionary containing the data sent with the request.</param> /// <param name="callback">The callback to invoke with the response.</param> /// <param name="dataType">The type of data expected in the response.</param> /// <returns>The jQueryXmlHttpRequest object.</returns> [ScriptName("get")] public static jQueryXmlHttpRequest<TData> Get<TData>(string url, object data, AjaxCallback<TData> callback, string dataType) { return null; } /// <summary> /// Load data from the server using a HTTP GET request. /// </summary> /// <param name="url">The URL to request.</param> /// <param name="data">A string or dictionary containing the data sent with the request.</param> /// <param name="callback">The callback to invoke with the response.</param> /// <param name="dataType">The type of data expected in the response.</param> /// <returns>The jQueryXmlHttpRequest object.</returns> [ScriptName("get")] public static jQueryXmlHttpRequest<TData> Get<TData>(string url, object data, AjaxRequestCallback<TData> callback, string dataType) { return null; } /// <summary> /// Load JSON data from the server using a HTTP GET request. /// </summary> /// <param name="url">The URL to request.</param> /// <returns>The jQueryXmlHttpRequest object.</returns> [ScriptName("getJSON")] public static jQueryXmlHttpRequest<TData> GetJson<TData>(string url) { return null; } /// <summary> /// Load JSON data from the server using a HTTP GET request. /// </summary> /// <param name="url">The URL to request.</param> /// <param name="callback">The callback to invoke with the response.</param> /// <returns>The jQueryXmlHttpRequest object.</returns> [ScriptName("getJSON")] public static jQueryXmlHttpRequest<TData> GetJson<TData>(string url, AjaxCallback<TData> callback) { return null; } /// <summary> /// Load JSON data from the server using a HTTP GET request. /// </summary> /// <param name="url">The URL to request.</param> /// <param name="data">A string or dictionary containing the data sent with the request.</param> /// <param name="callback">The callback to invoke with the response.</param> /// <returns>The jQueryXmlHttpRequest object.</returns> [ScriptName("getJSON")] public static jQueryXmlHttpRequest<TData> GetJson<TData>(string url, object data, AjaxCallback<TData> callback) { return null; } /// <summary> /// Load script from the server using a HTTP GET request and execute it. /// </summary> /// <param name="url">The URL to request.</param> /// <returns>The jQueryXmlHttpRequest object.</returns> public static jQueryXmlHttpRequest<string> GetScript(string url) { return null; } /// <summary> /// Load script from the server using a HTTP GET request and execute it. /// </summary> /// <param name="url">The URL to request.</param> /// <param name="callback">The callback to invoke with the response.</param> /// <returns>The jQueryXmlHttpRequest object.</returns> public static jQueryXmlHttpRequest<string> GetScript(string url, AjaxCallback<object> callback) { return null; } /// <summary> /// Filters the specified array using the provided callback, and returns the /// matching items. /// </summary> /// <param name="a">The array to be filtered.</param> /// <param name="callback">The callback to filter the items.</param> /// <returns>The matching items.</returns> public static Array Grep(Array a, ArrayFilterCallback callback) { return null; } /// <summary> /// Filters the specified array using the provided callback, and returns the /// matching items. /// </summary> /// <param name="a">The array to be filtered.</param> /// <param name="callback">The callback to filter the items.</param> /// <param name="invert">If true, the items not matching are returned.</param> /// <returns>The matching items.</returns> public static Array Grep(Array a, ArrayFilterCallback callback, bool invert) { return null; } // TODO: Add generic version of Grep /// <summary> /// Holds or releases the execution of jQuery's ready event. /// </summary> /// <param name="hold">Indicates whether the ready hold is being requested or released.</param> public static void HoldReady(bool hold) { } /// <summary> /// Gets the index of the specified value within the specified array. /// </summary> /// <param name="value">The value to look for.</param> /// <param name="a">The array to look in.</param> /// <returns>The index of value if it is found; -1 if it is not.</returns> public static int InArray(object value, Array a) { return 0; } /// <summary> /// Gets the index of the specified value within the specified list. /// </summary> /// <param name="value">The value to look for.</param> /// <param name="list">The list to look in.</param> /// <returns>The index of value if it is found; -1 if it is not.</returns> [ScriptName("inArray")] public static int InList<T>(T value, List<T> list) { return 0; } /// <summary> /// Checks if the specified object is an array. /// </summary> /// <param name="o">The object to check.</param> /// <returns>True if the object is an array; false otherwise.</returns> public static bool IsArray(object o) { return false; } /// <summary> /// Checks if the specified object is a function. /// </summary> /// <param name="o">The object to check.</param> /// <returns>True if the object is a function; false otherwise.</returns> public static bool IsFunction(object o) { return false; } /// <summary> /// Checks if the specified object is a window. /// </summary> /// <param name="o">The object to check.</param> /// <returns>True if the object is a window instance; false otherwise.</returns> public static bool IsWindow(object o) { return false; } /// <summary> /// Turns anything into a true array. /// </summary> /// <param name="o">The object to turn into an array.</param> /// <returns>The resulting array.</returns> public static Array MakeArray(object o) { return null; } /// <summary> /// Returns a new object by mapping each item in the specified object /// using the provided callback. /// </summary> /// <param name="o">The object to map.</param> /// <param name="callback">The function that performs the mapping.</param> /// <returns>The array of mapped values.</returns> public static object Map(object o, ObjectMapCallback callback) { return null; } /// <summary> /// Returns a new array by mapping each item in the specified array /// using the provided callback. /// </summary> /// <param name="a">The array of items to map.</param> /// <param name="callback">The function that performs the mapping.</param> /// <returns>The array of mapped values.</returns> public static Array Map(Array a, ArrayMapCallback callback) { return null; } /* TODO /// <summary> /// Returns a new list by mapping each item in the specified list /// using the provided callback. /// </summary> /// <param name="list">The list of items to map.</param> /// <param name="callback">The function that performs the mapping.</param> /// <returns>The list of mapped values.</returns> [ScriptName("map")] public static List<TTarget> MapList<TSource, TTarget>(List<TSource> list, ListMapCallback<TSource, TTarget> callback) { return null; } */ /// <summary> /// Merges the specified arrays into a single array. /// </summary> /// <param name="firstArray">The first array to merge.</param> /// <param name="secondArray">The second array to merge.</param> /// <returns>The new array containing merged set of items.</returns> public static Array Merge(Array firstArray, Array secondArray) { return null; } /// <summary> /// Merges the specified lists into a single list. /// </summary> /// <param name="firstList">The first list to merge.</param> /// <param name="secondList">The second list to merge.</param> /// <returns>The new list containing merged set of items.</returns> [ScriptName("merge")] public static List<T> MergeLists<T>(List<T> firstList, List<T> secondList) { return null; } /// <summary> /// Calls the specified function when the document is ready. This is equivalent to /// jQuery(document).ready(callback). /// </summary> /// <param name="callback">The callback to invoke.</param> /// <returns>The resulting jQueryObject instance.</returns> [ScriptAlias("$")] public static jQueryObject OnDocumentReady(Action callback) { return null; } /// <summary> /// Serializes an object for use in URL query string for an Ajax request. /// </summary> /// <param name="o">The object to serialize.</param> /// <returns>The serialized representation of the object.</returns> public static string Param(object o) { return null; } /// <summary> /// Parses the specified well-formed json string into an object. /// </summary> /// <param name="json">The json string.</param> /// <returns>The parsed document.</returns> [ScriptName("parseJSON")] public static object ParseJson(string json) { return null; } /// <summary> /// Parses the specified well-formed json string into an object. /// </summary> /// <param name="json">The json string.</param> /// <returns>The parsed document.</returns> [ScriptName("parseJSON")] public static TData ParseJsonData<TData>(string json) { return default(TData); } /// <summary> /// Parses the specified well-formed xml data into an XML document. /// </summary> /// <param name="data">The xml markup.</param> /// <returns>The parsed document.</returns> [ScriptName("parseXML")] public static XmlDocument ParseXml(string data) { return null; } /// <summary> /// Post data to the server using a HTTP POST request. /// </summary> /// <param name="url">The URL to request.</param> /// <returns>The jQueryXmlHttpRequest object.</returns> [ScriptName("post")] public static jQueryXmlHttpRequest<TData> Post<TData>(string url) { return null; } /// <summary> /// Post data to the server using a HTTP POST request. /// </summary> /// <param name="url">The URL to request.</param> /// <param name="callback">The callback to invoke with the response.</param> /// <returns>The jQueryXmlHttpRequest object.</returns> [ScriptName("post")] public static jQueryXmlHttpRequest<TData> Post<TData>(string url, AjaxCallback<TData> callback) { return null; } /// <summary> /// Post data to the server using a HTTP POST request. /// </summary> /// <param name="url">The URL to request.</param> /// <param name="data">A string or dictionary containing the data sent with the request.</param> /// <param name="callback">The callback to invoke with the response.</param> /// <returns>The jQueryXmlHttpRequest object.</returns> [ScriptName("post")] public static jQueryXmlHttpRequest<TData> Post<TData>(string url, object data, AjaxCallback<TData> callback) { return null; } /// <summary> /// Post data to the server using a HTTP POST request. /// </summary> /// <param name="url">The URL to request.</param> /// <param name="data">A string or dictionary containing the data sent with the request.</param> /// <param name="callback">The callback to invoke with the response.</param> /// <returns>The jQueryXmlHttpRequest object.</returns> [ScriptName("post")] public static jQueryXmlHttpRequest<TData> Post<TData>(string url, object data, AjaxRequestCallback<TData> callback) { return null; } /// <summary> /// Post data to the server using a HTTP POST request. /// </summary> /// <param name="url">The URL to request.</param> /// <param name="data">A string or dictionary containing the data sent with the request.</param> /// <param name="callback">The callback to invoke with the response.</param> /// <param name="dataType">The type of data expected in the response.</param> /// <returns>The jQueryXmlHttpRequest object.</returns> [ScriptName("post")] public static jQueryXmlHttpRequest<TData> Post<TData>(string url, object data, AjaxCallback<TData> callback, string dataType) { return null; } /// <summary> /// Post data to the server using a HTTP POST request. /// </summary> /// <param name="url">The URL to request.</param> /// <param name="data">A string or dictionary containing the data sent with the request.</param> /// <param name="callback">The callback to invoke with the response.</param> /// <param name="dataType">The type of data expected in the response.</param> /// <returns>The jQueryXmlHttpRequest object.</returns> [ScriptName("post")] public static jQueryXmlHttpRequest<TData> Post<TData>(string url, object data, AjaxRequestCallback<TData> callback, string dataType) { return null; } /// <summary> /// Wraps a DOM Element in a jQuery object /// </summary> /// <param name="element">The element to wrap.</param> /// <returns>The resulting jQueryObject instance.</returns> [ScriptAlias("$")] public static jQueryObject Select(Element element) { return null; } /// <summary> /// Finds one or more DOM elements matching a CSS selector and wraps them into a /// <see cref="jQueryObject"/> instance. /// </summary> /// <param name="selector">The selector to match elements.</param> /// <returns>The resulting jQueryObject instance.</returns> [ScriptAlias("$")] public static jQueryObject Select([SyntaxValidation("cssSelector")] string selector) { return null; } /// <summary> /// Finds one or more DOM elements matching a CSS selector and wraps them into a /// <see cref="jQueryObject"/> instance. The elements are scoped to those contained /// within the specified document. /// </summary> /// <param name="selector">The selector to match elements.</param> /// <param name="document">The document to search within.</param> /// <returns>The resulting jQueryObject instance.</returns> [ScriptAlias("$")] public static jQueryObject Select([SyntaxValidation("cssSelector")] string selector, DocumentInstance document) { return null; } /// <summary> /// Finds one or more DOM elements matching a CSS selector and wraps them into a /// <see cref="jQueryObject"/> instance. The elements are scoped to those contained /// within the specified root element. /// </summary> /// <param name="selector">The selector to match elements.</param> /// <param name="rootElement">The root element to begin the search at.</param> /// <returns>The resulting jQueryObject instance.</returns> [ScriptAlias("$")] public static jQueryObject Select([SyntaxValidation("cssSelector")] string selector, Element rootElement) { return null; } /// <summary> /// Finds one or more DOM elements matching a CSS selector and wraps them into a /// <see cref="jQueryObject"/> instance. The elements are scoped to those contained /// within the specified jQueryObject context. /// </summary> /// <param name="selector">The selector to match elements.</param> /// <param name="context">The context to scope the selection.</param> /// <returns>The resulting jQueryObject instance.</returns> [ScriptAlias("$")] public static jQueryObject Select([SyntaxValidation("cssSelector")] string selector, jQueryObject context) { return null; } /// <summary> /// Removes whitespace from the beginning and end of the string. /// </summary> /// <param name="s">The string to trim.</param> /// <returns>The trimmed string.</returns> public static string Trim(string s) { return null; } /// <summary> /// Gets the type of the specified object. /// </summary> /// <param name="o">The object whose type is to be looked up.</param> /// <returns>The type name of the object.</returns> public static string Type(object o) { return null; } /// <summary> /// Creates a deferred object representing the aggregate of the specified /// deferred objects. /// </summary> /// <param name="deferreds">The set of deferred objects.</param> /// <returns>A deferred object representing the individual deferred objects.</returns> [ExpandParams] public static IjQueryPromise<object> When(params IjQueryPromise<object>[] deferreds) { return null; } /// <summary> /// Creates a deferred object representing the aggregate of the specified /// deferred objects. If any of the objects are not deferred objects, then they /// are considered as pre-resolved deferred objects. /// </summary> /// <param name="deferreds">The set of deferred objects.</param> /// <returns>A deferred object representing the individual deferred objects.</returns> [ExpandParams] public static IjQueryPromise<object> When(params object[] deferreds) { return null; } /// <summary> /// Creates a deferred object representing the aggregate of the specified /// deferred objects. /// </summary> /// <param name="deferreds">The set of deferred objects.</param> /// <returns>A deferred object representing the individual deferred objects.</returns> [ExpandParams] [ScriptName("when")] public static IjQueryPromise<TData> WhenData<TData>(params IjQueryPromise<TData>[] deferreds) { return null; } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.IO; using DiscUtils.Internal; using DiscUtils.Streams; namespace DiscUtils.Ntfs { internal class File { private readonly List<NtfsAttribute> _attributes; protected INtfsContext _context; private readonly ObjectCache<string, Index> _indexCache; private readonly MasterFileTable _mft; private readonly List<FileRecord> _records; public File(INtfsContext context, FileRecord baseRecord) { _context = context; _mft = _context.Mft; _records = new List<FileRecord>(); _records.Add(baseRecord); _indexCache = new ObjectCache<string, Index>(); _attributes = new List<NtfsAttribute>(); LoadAttributes(); } /// <summary> /// Gets an enumeration of all the attributes. /// </summary> internal IEnumerable<NtfsAttribute> AllAttributes { get { return _attributes; } } public IEnumerable<NtfsStream> AllStreams { get { foreach (NtfsAttribute attr in _attributes) { yield return new NtfsStream(this, attr); } } } public string BestName { get { NtfsAttribute[] attrs = GetAttributes(AttributeType.FileName); string bestName = null; if (attrs != null && attrs.Length != 0) { bestName = attrs[0].ToString(); for (int i = 1; i < attrs.Length; ++i) { string name = attrs[i].ToString(); if (Utilities.Is8Dot3(bestName)) { bestName = name; } } } return bestName; } } internal INtfsContext Context { get { return _context; } } public DirectoryEntry DirectoryEntry { get { if (_context.GetDirectoryByRef == null) { return null; } NtfsStream stream = GetStream(AttributeType.FileName, null); if (stream == null) { return null; } FileNameRecord record = stream.GetContent<FileNameRecord>(); // Root dir is stored without root directory flag set in FileNameRecord, simulate it. if (_records[0].MasterFileTableIndex == MasterFileTable.RootDirIndex) { record.Flags |= FileAttributeFlags.Directory; } return new DirectoryEntry(_context.GetDirectoryByRef(record.ParentDirectory), MftReference, record); } } public ushort HardLinkCount { get { return _records[0].HardLinkCount; } set { _records[0].HardLinkCount = value; } } public bool HasWin32OrDosName { get { foreach (StructuredNtfsAttribute<FileNameRecord> attr in GetAttributes(AttributeType.FileName)) { FileNameRecord fnr = attr.Content; if (fnr.FileNameNamespace != FileNameNamespace.Posix) { return true; } } return false; } } public uint IndexInMft { get { return _records[0].MasterFileTableIndex; } } public bool IsDirectory { get { return (_records[0].Flags & FileRecordFlags.IsDirectory) != 0; } } public uint MaxMftRecordSize { get { return _records[0].AllocatedSize; } } public bool MftRecordIsDirty { get; private set; } public FileRecordReference MftReference { get { return _records[0].Reference; } } public List<string> Names { get { List<string> result = new List<string>(); if (IndexInMft == MasterFileTable.RootDirIndex) { result.Add(string.Empty); } else { foreach (StructuredNtfsAttribute<FileNameRecord> attr in GetAttributes(AttributeType.FileName)) { string name = attr.Content.FileName; Directory parentDir = _context.GetDirectoryByRef(attr.Content.ParentDirectory); if (parentDir != null) { foreach (string dirName in parentDir.Names) { result.Add(Utilities.CombinePaths(dirName, name)); } } } } return result; } } public StandardInformation StandardInformation { get { return GetStream(AttributeType.StandardInformation, null).GetContent<StandardInformation>(); } } public static File CreateNew(INtfsContext context, FileAttributeFlags dirFlags) { return CreateNew(context, FileRecordFlags.None, dirFlags); } public static File CreateNew(INtfsContext context, FileRecordFlags flags, FileAttributeFlags dirFlags) { File newFile = context.AllocateFile(flags); FileAttributeFlags fileFlags = FileAttributeFlags.Archive | FileRecord.ConvertFlags(flags) | (dirFlags & FileAttributeFlags.Compressed); AttributeFlags dataAttrFlags = AttributeFlags.None; if ((dirFlags & FileAttributeFlags.Compressed) != 0) { dataAttrFlags |= AttributeFlags.Compressed; } StandardInformation.InitializeNewFile(newFile, fileFlags); if (context.ObjectIds != null) { Guid newId = CreateNewGuid(context); NtfsStream stream = newFile.CreateStream(AttributeType.ObjectId, null); ObjectId objId = new ObjectId(); objId.Id = newId; stream.SetContent(objId); context.ObjectIds.Add(newId, newFile.MftReference, newId, Guid.Empty, Guid.Empty); } newFile.CreateAttribute(AttributeType.Data, dataAttrFlags); newFile.UpdateRecordInMft(); return newFile; } public int MftRecordFreeSpace(AttributeType attrType, string attrName) { foreach (FileRecord record in _records) { if (record.GetAttribute(attrType, attrName) != null) { return _mft.RecordSize - record.Size; } } throw new IOException("Attempt to determine free space for non-existent attribute"); } public void Modified() { DateTime now = DateTime.UtcNow; NtfsStream siStream = GetStream(AttributeType.StandardInformation, null); StandardInformation si = siStream.GetContent<StandardInformation>(); si.LastAccessTime = now; si.ModificationTime = now; siStream.SetContent(si); MarkMftRecordDirty(); } public void Accessed() { DateTime now = DateTime.UtcNow; NtfsStream siStream = GetStream(AttributeType.StandardInformation, null); StandardInformation si = siStream.GetContent<StandardInformation>(); si.LastAccessTime = now; siStream.SetContent(si); MarkMftRecordDirty(); } public void MarkMftRecordDirty() { MftRecordIsDirty = true; } public void UpdateRecordInMft() { if (MftRecordIsDirty) { if (NtfsTransaction.Current != null) { NtfsStream stream = GetStream(AttributeType.StandardInformation, null); StandardInformation si = stream.GetContent<StandardInformation>(); si.MftChangedTime = NtfsTransaction.Current.Timestamp; stream.SetContent(si); } bool fixesApplied = true; while (fixesApplied) { fixesApplied = false; for (int i = 0; i < _records.Count; ++i) { FileRecord record = _records[i]; bool fixedAttribute = true; while (record.Size > _mft.RecordSize && fixedAttribute) { fixedAttribute = false; if (!fixedAttribute && !record.IsMftRecord) { foreach (AttributeRecord attr in record.Attributes) { if (!attr.IsNonResident && !_context.AttributeDefinitions.MustBeResident(attr.AttributeType)) { MakeAttributeNonResident( new AttributeReference(record.Reference, attr.AttributeId), (int)attr.DataLength); fixedAttribute = true; break; } } } if (!fixedAttribute) { foreach (AttributeRecord attr in record.Attributes) { if (attr.AttributeType == AttributeType.IndexRoot && ShrinkIndexRoot(attr.Name)) { fixedAttribute = true; break; } } } if (!fixedAttribute) { if (record.Attributes.Count == 1) { fixedAttribute = SplitAttribute(record); } else { if (_records.Count == 1) { CreateAttributeList(); } fixedAttribute = ExpelAttribute(record); } } fixesApplied |= fixedAttribute; } } } MftRecordIsDirty = false; foreach (FileRecord record in _records) { _mft.WriteRecord(record); } } } public Index CreateIndex(string name, AttributeType attrType, AttributeCollationRule collRule) { Index.Create(attrType, collRule, this, name); return GetIndex(name); } public Index GetIndex(string name) { Index idx = _indexCache[name]; if (idx == null) { idx = new Index(this, name, _context.BiosParameterBlock, _context.UpperCase); _indexCache[name] = idx; } return idx; } public void Delete() { if (_records[0].HardLinkCount != 0) { throw new InvalidOperationException("Attempt to delete in-use file: " + ToString()); } _context.ForgetFile(this); NtfsStream objIdStream = GetStream(AttributeType.ObjectId, null); if (objIdStream != null) { ObjectId objId = objIdStream.GetContent<ObjectId>(); Context.ObjectIds.Remove(objId.Id); } // Truncate attributes, allowing for truncation silently removing the AttributeList attribute // in some cases (large file with all attributes first extent in the first MFT record). This // releases all allocated clusters in most cases. List<NtfsAttribute> truncateAttrs = new List<NtfsAttribute>(_attributes.Count); foreach (NtfsAttribute attr in _attributes) { if (attr.Type != AttributeType.AttributeList) { truncateAttrs.Add(attr); } } foreach (NtfsAttribute attr in truncateAttrs) { attr.GetDataBuffer().SetCapacity(0); } // If the attribute list record remains, free any possible clusters it owns. We've now freed // all clusters. NtfsAttribute attrList = GetAttribute(AttributeType.AttributeList, null); if (attrList != null) { attrList.GetDataBuffer().SetCapacity(0); } // Now go through the MFT records, freeing them up foreach (FileRecord mftRecord in _records) { _context.Mft.RemoveRecord(mftRecord.Reference); } _attributes.Clear(); _records.Clear(); } public bool StreamExists(AttributeType attrType, string name) { return GetStream(attrType, name) != null; } public NtfsStream GetStream(AttributeType attrType, string name) { foreach (NtfsStream stream in GetStreams(attrType, name)) { return stream; } return null; } public IEnumerable<NtfsStream> GetStreams(AttributeType attrType, string name) { foreach (NtfsAttribute attr in _attributes) { if (attr.Type == attrType && attr.Name == name) { yield return new NtfsStream(this, attr); } } } public NtfsStream CreateStream(AttributeType attrType, string name) { return new NtfsStream(this, CreateAttribute(attrType, name, AttributeFlags.None)); } public NtfsStream CreateStream(AttributeType attrType, string name, long firstCluster, ulong numClusters, uint bytesPerCluster) { return new NtfsStream(this, CreateAttribute(attrType, name, AttributeFlags.None, firstCluster, numClusters, bytesPerCluster)); } public SparseStream OpenStream(AttributeType attrType, string name, FileAccess access) { NtfsAttribute attr = GetAttribute(attrType, name); if (attr != null) { return new FileStream(this, attr, access); } return null; } public void RemoveStream(NtfsStream stream) { RemoveAttribute(stream.Attribute); } public FileNameRecord GetFileNameRecord(string name, bool freshened) { NtfsAttribute[] attrs = GetAttributes(AttributeType.FileName); StructuredNtfsAttribute<FileNameRecord> attr = null; if (string.IsNullOrEmpty(name)) { if (attrs.Length != 0) { attr = (StructuredNtfsAttribute<FileNameRecord>)attrs[0]; } } else { foreach (StructuredNtfsAttribute<FileNameRecord> a in attrs) { if (_context.UpperCase.Compare(a.Content.FileName, name) == 0) { attr = a; } } if (attr == null) { throw new FileNotFoundException("File name not found on file", name); } } FileNameRecord fnr = attr == null ? new FileNameRecord() : new FileNameRecord(attr.Content); if (freshened) { FreshenFileName(fnr, false); } return fnr; } public virtual void Dump(TextWriter writer, string indent) { writer.WriteLine(indent + "FILE (" + ToString() + ")"); writer.WriteLine(indent + " File Number: " + _records[0].MasterFileTableIndex); _records[0].Dump(writer, indent + " "); foreach (AttributeRecord attrRec in _records[0].Attributes) { NtfsAttribute.FromRecord(this, MftReference, attrRec).Dump(writer, indent + " "); } } public override string ToString() { string bestName = BestName; if (bestName == null) { return "?????"; } return bestName; } internal void RemoveAttributeExtents(NtfsAttribute attr) { attr.GetDataBuffer().SetCapacity(0); foreach (AttributeReference extentRef in attr.Extents.Keys) { RemoveAttributeExtent(extentRef); } } internal void RemoveAttributeExtent(AttributeReference extentRef) { FileRecord fileRec = GetFileRecord(extentRef.File); if (fileRec != null) { fileRec.RemoveAttribute(extentRef.AttributeId); // Remove empty non-primary MFT records if (fileRec.Attributes.Count == 0 && fileRec.BaseFile.Value != 0) { RemoveFileRecord(extentRef.File); } } } /// <summary> /// Gets an attribute by reference. /// </summary> /// <param name="attrRef">Reference to the attribute.</param> /// <returns>The attribute.</returns> internal NtfsAttribute GetAttribute(AttributeReference attrRef) { foreach (NtfsAttribute attr in _attributes) { if (attr.Reference.Equals(attrRef)) { return attr; } } return null; } /// <summary> /// Gets the first (if more than one) instance of a named attribute. /// </summary> /// <param name="type">The attribute type.</param> /// <param name="name">The attribute's name.</param> /// <returns>The attribute of <c>null</c>.</returns> internal NtfsAttribute GetAttribute(AttributeType type, string name) { foreach (NtfsAttribute attr in _attributes) { if (attr.PrimaryRecord.AttributeType == type && attr.Name == name) { return attr; } } return null; } /// <summary> /// Gets all instances of an unnamed attribute. /// </summary> /// <param name="type">The attribute type.</param> /// <returns>The attributes.</returns> internal NtfsAttribute[] GetAttributes(AttributeType type) { List<NtfsAttribute> matches = new List<NtfsAttribute>(); foreach (NtfsAttribute attr in _attributes) { if (attr.PrimaryRecord.AttributeType == type && string.IsNullOrEmpty(attr.Name)) { matches.Add(attr); } } return matches.ToArray(); } internal void MakeAttributeNonResident(AttributeReference attrRef, int maxData) { NtfsAttribute attr = GetAttribute(attrRef); if (attr.IsNonResident) { throw new InvalidOperationException("Attribute is already non-resident"); } ushort id = _records[0].CreateNonResidentAttribute(attr.Type, attr.Name, attr.Flags); AttributeRecord newAttrRecord = _records[0].GetAttribute(id); IBuffer attrBuffer = attr.GetDataBuffer(); byte[] tempData = StreamUtilities.ReadExact(attrBuffer, 0, (int)Math.Min(maxData, attrBuffer.Capacity)); RemoveAttributeExtents(attr); attr.SetExtent(_records[0].Reference, newAttrRecord); attr.GetDataBuffer().Write(0, tempData, 0, tempData.Length); UpdateAttributeList(); } internal void FreshenFileName(FileNameRecord fileName, bool updateMftRecord) { // // Freshen the record from the definitive info in the other attributes // StandardInformation si = StandardInformation; NtfsAttribute anonDataAttr = GetAttribute(AttributeType.Data, null); fileName.CreationTime = si.CreationTime; fileName.ModificationTime = si.ModificationTime; fileName.MftChangedTime = si.MftChangedTime; fileName.LastAccessTime = si.LastAccessTime; fileName.Flags = si.FileAttributes; if (MftRecordIsDirty && NtfsTransaction.Current != null) { fileName.MftChangedTime = NtfsTransaction.Current.Timestamp; } // Directories don't have directory flag set in StandardInformation, so set from MFT record if ((_records[0].Flags & FileRecordFlags.IsDirectory) != 0) { fileName.Flags |= FileAttributeFlags.Directory; } if (anonDataAttr != null) { fileName.RealSize = (ulong)anonDataAttr.PrimaryRecord.DataLength; fileName.AllocatedSize = (ulong)anonDataAttr.PrimaryRecord.AllocatedLength; } if (updateMftRecord) { foreach (NtfsStream stream in GetStreams(AttributeType.FileName, null)) { FileNameRecord fnr = stream.GetContent<FileNameRecord>(); if (fnr.Equals(fileName)) { fnr = new FileNameRecord(fileName); fnr.Flags &= ~FileAttributeFlags.ReparsePoint; stream.SetContent(fnr); } } } } internal long GetAttributeOffset(AttributeReference attrRef) { long recordOffset = _mft.GetRecordOffset(attrRef.File); FileRecord frs = GetFileRecord(attrRef.File); return recordOffset + frs.GetAttributeOffset(attrRef.AttributeId); } private static Guid CreateNewGuid(INtfsContext context) { Random rng = context.Options.RandomNumberGenerator; if (rng != null) { byte[] buffer = new byte[16]; rng.NextBytes(buffer); return new Guid(buffer); } return Guid.NewGuid(); } private void LoadAttributes() { Dictionary<long, FileRecord> extraFileRecords = new Dictionary<long, FileRecord>(); AttributeRecord attrListRec = _records[0].GetAttribute(AttributeType.AttributeList); if (attrListRec != null) { NtfsAttribute lastAttr = null; StructuredNtfsAttribute<AttributeList> attrListAttr = (StructuredNtfsAttribute<AttributeList>)NtfsAttribute.FromRecord(this, MftReference, attrListRec); AttributeList attrList = attrListAttr.Content; _attributes.Add(attrListAttr); foreach (AttributeListRecord record in attrList) { FileRecord attrFileRecord = _records[0]; if (record.BaseFileReference.MftIndex != _records[0].MasterFileTableIndex) { if (!extraFileRecords.TryGetValue(record.BaseFileReference.MftIndex, out attrFileRecord)) { attrFileRecord = _context.Mft.GetRecord(record.BaseFileReference); if (attrFileRecord != null) { extraFileRecords[attrFileRecord.MasterFileTableIndex] = attrFileRecord; } } } if (attrFileRecord != null) { AttributeRecord attrRec = attrFileRecord.GetAttribute(record.AttributeId); if (attrRec != null) { if (record.StartVcn == 0) { lastAttr = NtfsAttribute.FromRecord(this, record.BaseFileReference, attrRec); _attributes.Add(lastAttr); } else { lastAttr.AddExtent(record.BaseFileReference, attrRec); } } } } foreach (KeyValuePair<long, FileRecord> extraFileRecord in extraFileRecords) { _records.Add(extraFileRecord.Value); } } else { foreach (AttributeRecord record in _records[0].Attributes) { _attributes.Add(NtfsAttribute.FromRecord(this, MftReference, record)); } } } private bool SplitAttribute(FileRecord record) { if (record.Attributes.Count != 1) { throw new InvalidOperationException( "Attempting to split attribute in MFT record containing multiple attributes"); } return SplitAttribute(record, (NonResidentAttributeRecord)record.FirstAttribute, false); } private bool SplitAttribute(FileRecord record, NonResidentAttributeRecord targetAttr, bool atStart) { if (targetAttr.DataRuns.Count <= 1) { return false; } int splitIndex = 1; if (!atStart) { List<DataRun> runs = targetAttr.DataRuns; splitIndex = runs.Count - 1; int saved = runs[splitIndex].Size; while (splitIndex > 1 && record.Size - saved > record.AllocatedSize) { --splitIndex; saved += runs[splitIndex].Size; } } AttributeRecord newAttr = targetAttr.Split(splitIndex); // Find a home for the new attribute record FileRecord newAttrHome = null; foreach (FileRecord targetRecord in _records) { if (!targetRecord.IsMftRecord && _mft.RecordSize - targetRecord.Size >= newAttr.Size) { targetRecord.AddAttribute(newAttr); newAttrHome = targetRecord; } } if (newAttrHome == null) { newAttrHome = _mft.AllocateRecord(_records[0].Flags & ~FileRecordFlags.InUse, record.IsMftRecord); newAttrHome.BaseFile = record.BaseFile.IsNull ? record.Reference : record.BaseFile; _records.Add(newAttrHome); newAttrHome.AddAttribute(newAttr); } // Add the new attribute record as an extent on the attribute it split from bool added = false; foreach (NtfsAttribute attr in _attributes) { foreach (KeyValuePair<AttributeReference, AttributeRecord> existingRecord in attr.Extents) { if (existingRecord.Key.File == record.Reference && existingRecord.Key.AttributeId == targetAttr.AttributeId) { attr.AddExtent(newAttrHome.Reference, newAttr); added = true; break; } } if (added) { break; } } UpdateAttributeList(); return true; } private bool ExpelAttribute(FileRecord record) { if (record.MasterFileTableIndex == MasterFileTable.MftIndex) { // Special case for MFT - can't fully expel attributes, instead split most of the data runs off. List<AttributeRecord> attrs = record.Attributes; for (int i = attrs.Count - 1; i >= 0; --i) { AttributeRecord attr = attrs[i]; if (attr.AttributeType == AttributeType.Data) { if (SplitAttribute(record, (NonResidentAttributeRecord)attr, true)) { return true; } } } } else { List<AttributeRecord> attrs = record.Attributes; for (int i = attrs.Count - 1; i >= 0; --i) { AttributeRecord attr = attrs[i]; if (attr.AttributeType > AttributeType.AttributeList) { foreach (FileRecord targetRecord in _records) { if (_mft.RecordSize - targetRecord.Size >= attr.Size) { MoveAttribute(record, attr, targetRecord); return true; } } FileRecord newFileRecord = _mft.AllocateRecord(FileRecordFlags.None, record.IsMftRecord); newFileRecord.BaseFile = record.Reference; _records.Add(newFileRecord); MoveAttribute(record, attr, newFileRecord); return true; } } } return false; } private void MoveAttribute(FileRecord record, AttributeRecord attrRec, FileRecord targetRecord) { AttributeReference oldRef = new AttributeReference(record.Reference, attrRec.AttributeId); record.RemoveAttribute(attrRec.AttributeId); targetRecord.AddAttribute(attrRec); AttributeReference newRef = new AttributeReference(targetRecord.Reference, attrRec.AttributeId); foreach (NtfsAttribute attr in _attributes) { attr.ReplaceExtent(oldRef, newRef, attrRec); } UpdateAttributeList(); } private void CreateAttributeList() { ushort id = _records[0].CreateAttribute(AttributeType.AttributeList, null, false, AttributeFlags.None); StructuredNtfsAttribute<AttributeList> newAttr = (StructuredNtfsAttribute<AttributeList>) NtfsAttribute.FromRecord(this, MftReference, _records[0].GetAttribute(id)); _attributes.Add(newAttr); UpdateAttributeList(); } private void UpdateAttributeList() { if (_records.Count > 1) { AttributeList attrList = new AttributeList(); foreach (NtfsAttribute attr in _attributes) { if (attr.Type != AttributeType.AttributeList) { foreach (KeyValuePair<AttributeReference, AttributeRecord> extent in attr.Extents) { attrList.Add(AttributeListRecord.FromAttribute(extent.Value, extent.Key.File)); } } } StructuredNtfsAttribute<AttributeList> alAttr; alAttr = (StructuredNtfsAttribute<AttributeList>)GetAttribute(AttributeType.AttributeList, null); alAttr.Content = attrList; alAttr.Save(); } } /// <summary> /// Creates a new unnamed attribute. /// </summary> /// <param name="type">The type of the new attribute.</param> /// <param name="flags">The flags of the new attribute.</param> /// <returns>The new attribute.</returns> private NtfsAttribute CreateAttribute(AttributeType type, AttributeFlags flags) { return CreateAttribute(type, null, flags); } /// <summary> /// Creates a new attribute. /// </summary> /// <param name="type">The type of the new attribute.</param> /// <param name="name">The name of the new attribute.</param> /// <param name="flags">The flags of the new attribute.</param> /// <returns>The new attribute.</returns> private NtfsAttribute CreateAttribute(AttributeType type, string name, AttributeFlags flags) { bool indexed = _context.AttributeDefinitions.IsIndexed(type); ushort id = _records[0].CreateAttribute(type, name, indexed, flags); AttributeRecord newAttrRecord = _records[0].GetAttribute(id); NtfsAttribute newAttr = NtfsAttribute.FromRecord(this, MftReference, newAttrRecord); _attributes.Add(newAttr); UpdateAttributeList(); MarkMftRecordDirty(); return newAttr; } /// <summary> /// Creates a new attribute at a fixed cluster. /// </summary> /// <param name="type">The type of the new attribute.</param> /// <param name="name">The name of the new attribute.</param> /// <param name="flags">The flags of the new attribute.</param> /// <param name="firstCluster">The first cluster to assign to the attribute.</param> /// <param name="numClusters">The number of sequential clusters to assign to the attribute.</param> /// <param name="bytesPerCluster">The number of bytes in each cluster.</param> /// <returns>The new attribute.</returns> private NtfsAttribute CreateAttribute(AttributeType type, string name, AttributeFlags flags, long firstCluster, ulong numClusters, uint bytesPerCluster) { bool indexed = _context.AttributeDefinitions.IsIndexed(type); ushort id = _records[0].CreateNonResidentAttribute(type, name, flags, firstCluster, numClusters, bytesPerCluster); AttributeRecord newAttrRecord = _records[0].GetAttribute(id); NtfsAttribute newAttr = NtfsAttribute.FromRecord(this, MftReference, newAttrRecord); _attributes.Add(newAttr); UpdateAttributeList(); MarkMftRecordDirty(); return newAttr; } private void RemoveAttribute(NtfsAttribute attr) { if (attr != null) { if (attr.PrimaryRecord.AttributeType == AttributeType.IndexRoot) { _indexCache.Remove(attr.PrimaryRecord.Name); } RemoveAttributeExtents(attr); _attributes.Remove(attr); UpdateAttributeList(); } } private bool ShrinkIndexRoot(string indexName) { NtfsAttribute attr = GetAttribute(AttributeType.IndexRoot, indexName); // Nothing to win, can't make IndexRoot smaller than this // 8 = min size of entry that points to IndexAllocation... if (attr.Length <= IndexRoot.HeaderOffset + IndexHeader.Size + 8) { return false; } Index idx = GetIndex(indexName); return idx.ShrinkRoot(); } private void MakeAttributeResident(AttributeReference attrRef, int maxData) { NtfsAttribute attr = GetAttribute(attrRef); if (!attr.IsNonResident) { throw new InvalidOperationException("Attribute is already resident"); } ushort id = _records[0].CreateAttribute(attr.Type, attr.Name, _context.AttributeDefinitions.IsIndexed(attr.Type), attr.Flags); AttributeRecord newAttrRecord = _records[0].GetAttribute(id); IBuffer attrBuffer = attr.GetDataBuffer(); byte[] tempData = StreamUtilities.ReadExact(attrBuffer, 0, (int)Math.Min(maxData, attrBuffer.Capacity)); RemoveAttributeExtents(attr); attr.SetExtent(_records[0].Reference, newAttrRecord); attr.GetDataBuffer().Write(0, tempData, 0, tempData.Length); UpdateAttributeList(); } private FileRecord GetFileRecord(FileRecordReference fileReference) { foreach (FileRecord record in _records) { if (record.MasterFileTableIndex == fileReference.MftIndex) { return record; } } return null; } private void RemoveFileRecord(FileRecordReference fileReference) { for (int i = 0; i < _records.Count; ++i) { if (_records[i].MasterFileTableIndex == fileReference.MftIndex) { FileRecord record = _records[i]; if (record.Attributes.Count > 0) { throw new IOException("Attempting to remove non-empty MFT record"); } _context.Mft.RemoveRecord(fileReference); _records.Remove(record); if (_records.Count == 1) { NtfsAttribute attrListAttr = GetAttribute(AttributeType.AttributeList, null); if (attrListAttr != null) { RemoveAttribute(attrListAttr); } } } } } /// <summary> /// Wrapper for Resident/Non-Resident attribute streams, that remains valid /// despite the attribute oscillating between resident and not. /// </summary> private class FileStream : SparseStream { private readonly NtfsAttribute _attr; private readonly File _file; private readonly SparseStream _wrapped; public FileStream(File file, NtfsAttribute attr, FileAccess access) { _file = file; _attr = attr; _wrapped = attr.Open(access); } public override bool CanRead { get { return _wrapped.CanRead; } } public override bool CanSeek { get { return _wrapped.CanSeek; } } public override bool CanWrite { get { return _wrapped.CanWrite; } } public override IEnumerable<StreamExtent> Extents { get { return _wrapped.Extents; } } public override long Length { get { return _wrapped.Length; } } public override long Position { get { return _wrapped.Position; } set { _wrapped.Position = value; } } protected override void Dispose(bool disposing) { base.Dispose(disposing); _wrapped.Dispose(); } public override void Flush() { _wrapped.Flush(); } public override int Read(byte[] buffer, int offset, int count) { return _wrapped.Read(buffer, offset, count); } public override long Seek(long offset, SeekOrigin origin) { return _wrapped.Seek(offset, origin); } public override void SetLength(long value) { ChangeAttributeResidencyByLength(value); _wrapped.SetLength(value); } public override void Write(byte[] buffer, int offset, int count) { if (_wrapped.Position + count > Length) { ChangeAttributeResidencyByLength(_wrapped.Position + count); } _wrapped.Write(buffer, offset, count); } public override void Clear(int count) { if (_wrapped.Position + count > Length) { ChangeAttributeResidencyByLength(_wrapped.Position + count); } _wrapped.Clear(count); } public override string ToString() { return _file + ".attr[" + _attr.Id + "]"; } /// <summary> /// Change attribute residency if it gets too big (or small). /// </summary> /// <param name="value">The new (anticipated) length of the stream.</param> /// <remarks>Has hysteresis - the decision is based on the input and the current /// state, not the current state alone.</remarks> private void ChangeAttributeResidencyByLength(long value) { // This is a bit of a hack - but it's really important the bitmap file remains non-resident if (_file._records[0].MasterFileTableIndex == MasterFileTable.BitmapIndex) { return; } if (!_attr.IsNonResident && value >= _file.MaxMftRecordSize) { _file.MakeAttributeNonResident(_attr.Reference, (int)Math.Min(value, _wrapped.Length)); } else if (_attr.IsNonResident && value <= _file.MaxMftRecordSize / 4) { // Use of 1/4 of record size here is just a heuristic - the important thing is not to end up with // zero-length non-resident attributes _file.MakeAttributeResident(_attr.Reference, (int)value); } } } } }
using Lucene.Net.Support; using Lucene.Net.Util; using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Runtime.CompilerServices; using System.Threading; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Allocator = Lucene.Net.Util.ByteBlockPool.Allocator; using Analyzer = Lucene.Net.Analysis.Analyzer; using Codec = Lucene.Net.Codecs.Codec; using Constants = Lucene.Net.Util.Constants; using Counter = Lucene.Net.Util.Counter; using DeleteSlice = Lucene.Net.Index.DocumentsWriterDeleteQueue.DeleteSlice; using Directory = Lucene.Net.Store.Directory; using DirectTrackingAllocator = Lucene.Net.Util.ByteBlockPool.DirectTrackingAllocator; using FlushInfo = Lucene.Net.Store.FlushInfo; using InfoStream = Lucene.Net.Util.InfoStream; using Int32BlockPool = Lucene.Net.Util.Int32BlockPool; using IOContext = Lucene.Net.Store.IOContext; using IMutableBits = Lucene.Net.Util.IMutableBits; using RamUsageEstimator = Lucene.Net.Util.RamUsageEstimator; using Similarity = Lucene.Net.Search.Similarities.Similarity; using TrackingDirectoryWrapper = Lucene.Net.Store.TrackingDirectoryWrapper; internal class DocumentsWriterPerThread { /// <summary> /// The <see cref="IndexingChain"/> must define the <see cref="GetChain(DocumentsWriterPerThread)"/> method /// which returns the <see cref="DocConsumer"/> that the <see cref="DocumentsWriter"/> calls to process the /// documents. /// </summary> internal abstract class IndexingChain { internal abstract DocConsumer GetChain(DocumentsWriterPerThread documentsWriterPerThread); } private static readonly IndexingChain defaultIndexingChain = new IndexingChainAnonymousInnerClassHelper(); public static IndexingChain DefaultIndexingChain { get { return defaultIndexingChain; } } private class IndexingChainAnonymousInnerClassHelper : IndexingChain { public IndexingChainAnonymousInnerClassHelper() { } internal override DocConsumer GetChain(DocumentsWriterPerThread documentsWriterPerThread) { /* this is the current indexing chain: DocConsumer / DocConsumerPerThread --> code: DocFieldProcessor --> DocFieldConsumer / DocFieldConsumerPerField --> code: DocFieldConsumers / DocFieldConsumersPerField --> code: DocInverter / DocInverterPerField --> InvertedDocConsumer / InvertedDocConsumerPerField --> code: TermsHash / TermsHashPerField --> TermsHashConsumer / TermsHashConsumerPerField --> code: FreqProxTermsWriter / FreqProxTermsWriterPerField --> code: TermVectorsTermsWriter / TermVectorsTermsWriterPerField --> InvertedDocEndConsumer / InvertedDocConsumerPerField --> code: NormsConsumer / NormsConsumerPerField --> StoredFieldsConsumer --> TwoStoredFieldConsumers -> code: StoredFieldsProcessor -> code: DocValuesProcessor */ // Build up indexing chain: TermsHashConsumer termVectorsWriter = new TermVectorsConsumer(documentsWriterPerThread); TermsHashConsumer freqProxWriter = new FreqProxTermsWriter(); InvertedDocConsumer termsHash = new TermsHash(documentsWriterPerThread, freqProxWriter, true, new TermsHash(documentsWriterPerThread, termVectorsWriter, false, null)); NormsConsumer normsWriter = new NormsConsumer(); DocInverter docInverter = new DocInverter(documentsWriterPerThread.docState, termsHash, normsWriter); StoredFieldsConsumer storedFields = new TwoStoredFieldsConsumers( new StoredFieldsProcessor(documentsWriterPerThread), new DocValuesProcessor(documentsWriterPerThread.bytesUsed)); return new DocFieldProcessor(documentsWriterPerThread, docInverter, storedFields); } } public class DocState { internal readonly DocumentsWriterPerThread docWriter; internal Analyzer analyzer; internal InfoStream infoStream; internal Similarity similarity; internal int docID; internal IEnumerable<IIndexableField> doc; internal string maxTermPrefix; internal DocState(DocumentsWriterPerThread docWriter, InfoStream infoStream) { this.docWriter = docWriter; this.infoStream = infoStream; } // Only called by asserts public virtual bool TestPoint(string name) { return docWriter.TestPoint(name); } public virtual void Clear() { // don't hold onto doc nor analyzer, in case it is // largish: doc = null; analyzer = null; } } internal class FlushedSegment { internal readonly SegmentCommitInfo segmentInfo; internal readonly FieldInfos fieldInfos; internal readonly FrozenBufferedUpdates segmentUpdates; internal readonly IMutableBits liveDocs; internal readonly int delCount; internal FlushedSegment(SegmentCommitInfo segmentInfo, FieldInfos fieldInfos, BufferedUpdates segmentUpdates, IMutableBits liveDocs, int delCount) { this.segmentInfo = segmentInfo; this.fieldInfos = fieldInfos; this.segmentUpdates = segmentUpdates != null && segmentUpdates.Any() ? new FrozenBufferedUpdates(segmentUpdates, true) : null; this.liveDocs = liveDocs; this.delCount = delCount; } } /// <summary> /// Called if we hit an exception at a bad time (when /// updating the index files) and must discard all /// currently buffered docs. this resets our state, /// discarding any docs added since last flush. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] internal virtual void Abort(ISet<string> createdFiles) { //System.out.println(Thread.currentThread().getName() + ": now abort seg=" + segmentInfo.name); hasAborted = aborting = true; try { if (infoStream.IsEnabled("DWPT")) { infoStream.Message("DWPT", "now abort"); } try { consumer.Abort(); } #pragma warning disable 168 catch (Exception t) #pragma warning restore 168 { } pendingUpdates.Clear(); Collections.AddAll(createdFiles, directory.CreatedFiles); } finally { aborting = false; if (infoStream.IsEnabled("DWPT")) { infoStream.Message("DWPT", "done abort"); } } } private const bool INFO_VERBOSE = false; internal readonly Codec codec; internal readonly TrackingDirectoryWrapper directory; internal readonly Directory directoryOrig; internal readonly DocState docState; internal readonly DocConsumer consumer; internal readonly Counter bytesUsed; internal SegmentWriteState flushState; // Updates for our still-in-RAM (to be flushed next) segment internal readonly BufferedUpdates pendingUpdates; private readonly SegmentInfo segmentInfo; // Current segment we are working on internal bool aborting = false; // True if an abort is pending internal bool hasAborted = false; // True if the last exception throws by #updateDocument was aborting private FieldInfos.Builder fieldInfos; private readonly InfoStream infoStream; private int numDocsInRAM; internal readonly DocumentsWriterDeleteQueue deleteQueue; private readonly DeleteSlice deleteSlice; private readonly NumberFormatInfo nf = CultureInfo.InvariantCulture.NumberFormat; internal readonly Allocator byteBlockAllocator; internal readonly Int32BlockPool.Allocator intBlockAllocator; private readonly LiveIndexWriterConfig indexWriterConfig; public DocumentsWriterPerThread(string segmentName, Directory directory, LiveIndexWriterConfig indexWriterConfig, InfoStream infoStream, DocumentsWriterDeleteQueue deleteQueue, FieldInfos.Builder fieldInfos) { this.directoryOrig = directory; this.directory = new TrackingDirectoryWrapper(directory); this.fieldInfos = fieldInfos; this.indexWriterConfig = indexWriterConfig; this.infoStream = infoStream; this.codec = indexWriterConfig.Codec; this.docState = new DocState(this, infoStream); this.docState.similarity = indexWriterConfig.Similarity; bytesUsed = Counter.NewCounter(); byteBlockAllocator = new DirectTrackingAllocator(bytesUsed); pendingUpdates = new BufferedUpdates(); intBlockAllocator = new Int32BlockAllocator(bytesUsed); this.deleteQueue = deleteQueue; Debug.Assert(numDocsInRAM == 0, "num docs " + numDocsInRAM); pendingUpdates.Clear(); deleteSlice = deleteQueue.NewSlice(); segmentInfo = new SegmentInfo(directoryOrig, Constants.LUCENE_MAIN_VERSION, segmentName, -1, false, codec, null); Debug.Assert(numDocsInRAM == 0); if (INFO_VERBOSE && infoStream.IsEnabled("DWPT")) { infoStream.Message("DWPT", Thread.CurrentThread.Name + " init seg=" + segmentName + " delQueue=" + deleteQueue); } // this should be the last call in the ctor // it really sucks that we need to pull this within the ctor and pass this ref to the chain! consumer = indexWriterConfig.IndexingChain.GetChain(this); } internal virtual void SetAborting() { aborting = true; } internal virtual bool CheckAndResetHasAborted() { bool retval = hasAborted; hasAborted = false; return retval; } internal bool TestPoint(string message) { if (infoStream.IsEnabled("TP")) { infoStream.Message("TP", message); } return true; } public virtual void UpdateDocument(IEnumerable<IIndexableField> doc, Analyzer analyzer, Term delTerm) { Debug.Assert(TestPoint("DocumentsWriterPerThread addDocument start")); Debug.Assert(deleteQueue != null); docState.doc = doc; docState.analyzer = analyzer; docState.docID = numDocsInRAM; if (INFO_VERBOSE && infoStream.IsEnabled("DWPT")) { infoStream.Message("DWPT", Thread.CurrentThread.Name + " update delTerm=" + delTerm + " docID=" + docState.docID + " seg=" + segmentInfo.Name); } bool success = false; try { try { consumer.ProcessDocument(fieldInfos); } finally { docState.Clear(); } success = true; } finally { if (!success) { if (!aborting) { // mark document as deleted DeleteDocID(docState.docID); numDocsInRAM++; } else { Abort(filesToDelete); } } } success = false; try { consumer.FinishDocument(); success = true; } finally { if (!success) { Abort(filesToDelete); } } FinishDocument(delTerm); } public virtual int UpdateDocuments(IEnumerable<IEnumerable<IIndexableField>> docs, Analyzer analyzer, Term delTerm) { Debug.Assert(TestPoint("DocumentsWriterPerThread addDocuments start")); Debug.Assert(deleteQueue != null); docState.analyzer = analyzer; if (INFO_VERBOSE && infoStream.IsEnabled("DWPT")) { infoStream.Message("DWPT", Thread.CurrentThread.Name + " update delTerm=" + delTerm + " docID=" + docState.docID + " seg=" + segmentInfo.Name); } int docCount = 0; bool allDocsIndexed = false; try { foreach (IEnumerable<IIndexableField> doc in docs) { docState.doc = doc; docState.docID = numDocsInRAM; docCount++; bool success = false; try { consumer.ProcessDocument(fieldInfos); success = true; } finally { if (!success) { // An exc is being thrown... if (!aborting) { // Incr here because finishDocument will not // be called (because an exc is being thrown): numDocsInRAM++; } else { Abort(filesToDelete); } } } success = false; try { consumer.FinishDocument(); success = true; } finally { if (!success) { Abort(filesToDelete); } } FinishDocument(null); } allDocsIndexed = true; // Apply delTerm only after all indexing has // succeeded, but apply it only to docs prior to when // this batch started: if (delTerm != null) { deleteQueue.Add(delTerm, deleteSlice); Debug.Assert(deleteSlice.IsTailItem(delTerm), "expected the delete term as the tail item"); deleteSlice.Apply(pendingUpdates, numDocsInRAM - docCount); } } finally { if (!allDocsIndexed && !aborting) { // the iterator threw an exception that is not aborting // go and mark all docs from this block as deleted int docID = numDocsInRAM - 1; int endDocID = docID - docCount; while (docID > endDocID) { DeleteDocID(docID); docID--; } } docState.Clear(); } return docCount; } [MethodImpl(MethodImplOptions.NoInlining)] private void FinishDocument(Term delTerm) { /* * here we actually finish the document in two steps 1. push the delete into * the queue and update our slice. 2. increment the DWPT private document * id. * * the updated slice we get from 1. holds all the deletes that have occurred * since we updated the slice the last time. */ bool applySlice = numDocsInRAM != 0; if (delTerm != null) { deleteQueue.Add(delTerm, deleteSlice); Debug.Assert(deleteSlice.IsTailItem(delTerm), "expected the delete term as the tail item"); } else { applySlice &= deleteQueue.UpdateSlice(deleteSlice); } if (applySlice) { deleteSlice.Apply(pendingUpdates, numDocsInRAM); } // if we don't need to apply we must reset! else { deleteSlice.Reset(); } ++numDocsInRAM; } // Buffer a specific docID for deletion. Currently only // used when we hit an exception when adding a document internal virtual void DeleteDocID(int docIDUpto) { pendingUpdates.AddDocID(docIDUpto); // NOTE: we do not trigger flush here. this is // potentially a RAM leak, if you have an app that tries // to add docs but every single doc always hits a // non-aborting exception. Allowing a flush here gets // very messy because we are only invoked when handling // exceptions so to do this properly, while handling an // exception we'd have to go off and flush new deletes // which is risky (likely would hit some other // confounding exception). } /// <summary> /// Returns the number of delete terms in this <see cref="DocumentsWriterPerThread"/> /// </summary> public virtual int NumDeleteTerms { get { // public for FlushPolicy return pendingUpdates.numTermDeletes.Get(); } } /// <summary> /// Returns the number of RAM resident documents in this <see cref="DocumentsWriterPerThread"/> /// </summary> public virtual int NumDocsInRAM { get { // public for FlushPolicy return numDocsInRAM; } } /// <summary> /// Prepares this DWPT for flushing. this method will freeze and return the /// <see cref="DocumentsWriterDeleteQueue"/>s global buffer and apply all pending /// deletes to this DWPT. /// </summary> internal virtual FrozenBufferedUpdates PrepareFlush() { Debug.Assert(numDocsInRAM > 0); FrozenBufferedUpdates globalUpdates = deleteQueue.FreezeGlobalBuffer(deleteSlice); /* deleteSlice can possibly be null if we have hit non-aborting exceptions during indexing and never succeeded adding a document. */ if (deleteSlice != null) { // apply all deletes before we flush and release the delete slice deleteSlice.Apply(pendingUpdates, numDocsInRAM); Debug.Assert(deleteSlice.IsEmpty); deleteSlice.Reset(); } return globalUpdates; } /// <summary> /// Flush all pending docs to a new segment </summary> [MethodImpl(MethodImplOptions.NoInlining)] internal virtual FlushedSegment Flush() { Debug.Assert(numDocsInRAM > 0); Debug.Assert(deleteSlice.IsEmpty, "all deletes must be applied in prepareFlush"); segmentInfo.DocCount = numDocsInRAM; SegmentWriteState flushState = new SegmentWriteState(infoStream, directory, segmentInfo, fieldInfos.Finish(), indexWriterConfig.TermIndexInterval, pendingUpdates, new IOContext(new FlushInfo(numDocsInRAM, BytesUsed))); double startMBUsed = BytesUsed / 1024.0 / 1024.0; // Apply delete-by-docID now (delete-byDocID only // happens when an exception is hit processing that // doc, eg if analyzer has some problem w/ the text): if (pendingUpdates.docIDs.Count > 0) { flushState.LiveDocs = codec.LiveDocsFormat.NewLiveDocs(numDocsInRAM); foreach (int delDocID in pendingUpdates.docIDs) { flushState.LiveDocs.Clear(delDocID); } flushState.DelCountOnFlush = pendingUpdates.docIDs.Count; pendingUpdates.bytesUsed.AddAndGet(-pendingUpdates.docIDs.Count * BufferedUpdates.BYTES_PER_DEL_DOCID); pendingUpdates.docIDs.Clear(); } if (aborting) { if (infoStream.IsEnabled("DWPT")) { infoStream.Message("DWPT", "flush: skip because aborting is set"); } return null; } if (infoStream.IsEnabled("DWPT")) { infoStream.Message("DWPT", "flush postings as segment " + flushState.SegmentInfo.Name + " numDocs=" + numDocsInRAM); } bool success = false; try { consumer.Flush(flushState); pendingUpdates.terms.Clear(); segmentInfo.SetFiles(new HashSet<string>(directory.CreatedFiles)); SegmentCommitInfo segmentInfoPerCommit = new SegmentCommitInfo(segmentInfo, 0, -1L, -1L); if (infoStream.IsEnabled("DWPT")) { infoStream.Message("DWPT", "new segment has " + (flushState.LiveDocs == null ? 0 : (flushState.SegmentInfo.DocCount - flushState.DelCountOnFlush)) + " deleted docs"); infoStream.Message("DWPT", "new segment has " + (flushState.FieldInfos.HasVectors ? "vectors" : "no vectors") + "; " + (flushState.FieldInfos.HasNorms ? "norms" : "no norms") + "; " + (flushState.FieldInfos.HasDocValues ? "docValues" : "no docValues") + "; " + (flushState.FieldInfos.HasProx ? "prox" : "no prox") + "; " + (flushState.FieldInfos.HasFreq ? "freqs" : "no freqs")); infoStream.Message("DWPT", "flushedFiles=" + Arrays.ToString(segmentInfoPerCommit.GetFiles())); infoStream.Message("DWPT", "flushed codec=" + codec); } BufferedUpdates segmentDeletes; if (pendingUpdates.queries.Count == 0 && pendingUpdates.numericUpdates.Count == 0 && pendingUpdates.binaryUpdates.Count == 0) { pendingUpdates.Clear(); segmentDeletes = null; } else { segmentDeletes = pendingUpdates; } if (infoStream.IsEnabled("DWPT")) { double newSegmentSize = segmentInfoPerCommit.GetSizeInBytes() / 1024.0 / 1024.0; infoStream.Message("DWPT", "flushed: segment=" + segmentInfo.Name + " ramUsed=" + startMBUsed.ToString(nf) + " MB" + " newFlushedSize(includes docstores)=" + newSegmentSize.ToString(nf) + " MB" + " docs/MB=" + (flushState.SegmentInfo.DocCount / newSegmentSize).ToString(nf)); } Debug.Assert(segmentInfo != null); FlushedSegment fs = new FlushedSegment(segmentInfoPerCommit, flushState.FieldInfos, segmentDeletes, flushState.LiveDocs, flushState.DelCountOnFlush); SealFlushedSegment(fs); success = true; return fs; } finally { if (!success) { Abort(filesToDelete); } } } private readonly HashSet<string> filesToDelete = new HashSet<string>(); public virtual ISet<string> PendingFilesToDelete { get { return filesToDelete; } } /// <summary> /// Seals the <see cref="Index.SegmentInfo"/> for the new flushed segment and persists /// the deleted documents <see cref="IMutableBits"/>. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] internal virtual void SealFlushedSegment(FlushedSegment flushedSegment) { Debug.Assert(flushedSegment != null); SegmentCommitInfo newSegment = flushedSegment.segmentInfo; IndexWriter.SetDiagnostics(newSegment.Info, IndexWriter.SOURCE_FLUSH); IOContext context = new IOContext(new FlushInfo(newSegment.Info.DocCount, newSegment.GetSizeInBytes())); bool success = false; try { if (indexWriterConfig.UseCompoundFile) { Collections.AddAll(filesToDelete, IndexWriter.CreateCompoundFile(infoStream, directory, CheckAbort.NONE, newSegment.Info, context)); newSegment.Info.UseCompoundFile = true; } // Have codec write SegmentInfo. Must do this after // creating CFS so that 1) .si isn't slurped into CFS, // and 2) .si reflects useCompoundFile=true change // above: codec.SegmentInfoFormat.SegmentInfoWriter.Write(directory, newSegment.Info, flushedSegment.fieldInfos, context); // TODO: ideally we would freeze newSegment here!! // because any changes after writing the .si will be // lost... // Must write deleted docs after the CFS so we don't // slurp the del file into CFS: if (flushedSegment.liveDocs != null) { int delCount = flushedSegment.delCount; Debug.Assert(delCount > 0); if (infoStream.IsEnabled("DWPT")) { infoStream.Message("DWPT", "flush: write " + delCount + " deletes gen=" + flushedSegment.segmentInfo.DelGen); } // TODO: we should prune the segment if it's 100% // deleted... but merge will also catch it. // TODO: in the NRT case it'd be better to hand // this del vector over to the // shortly-to-be-opened SegmentReader and let it // carry the changes; there's no reason to use // filesystem as intermediary here. SegmentCommitInfo info = flushedSegment.segmentInfo; Codec codec = info.Info.Codec; codec.LiveDocsFormat.WriteLiveDocs(flushedSegment.liveDocs, directory, info, delCount, context); newSegment.DelCount = delCount; newSegment.AdvanceDelGen(); } success = true; } finally { if (!success) { if (infoStream.IsEnabled("DWPT")) { infoStream.Message("DWPT", "hit exception creating compound file for newly flushed segment " + newSegment.Info.Name); } } } } /// <summary> /// Get current segment info we are writing. </summary> internal virtual SegmentInfo SegmentInfo { get { return segmentInfo; } } public virtual long BytesUsed { get { return bytesUsed.Get() + pendingUpdates.bytesUsed.Get(); } } /// <summary> /// Initial chunks size of the shared byte[] blocks used to /// store postings data /// </summary> internal static readonly int BYTE_BLOCK_NOT_MASK = ~ByteBlockPool.BYTE_BLOCK_MASK; /// <summary> /// if you increase this, you must fix field cache impl for /// getTerms/getTermsIndex requires &lt;= 32768 /// </summary> internal static readonly int MAX_TERM_LENGTH_UTF8 = ByteBlockPool.BYTE_BLOCK_SIZE - 2; /// <summary> /// NOTE: This was IntBlockAllocator in Lucene /// </summary> private class Int32BlockAllocator : Int32BlockPool.Allocator { private readonly Counter bytesUsed; public Int32BlockAllocator(Counter bytesUsed) : base(Int32BlockPool.INT32_BLOCK_SIZE) { this.bytesUsed = bytesUsed; } /// <summary> /// Allocate another int[] from the shared pool /// </summary> public override int[] GetInt32Block() { int[] b = new int[Int32BlockPool.INT32_BLOCK_SIZE]; bytesUsed.AddAndGet(Int32BlockPool.INT32_BLOCK_SIZE * RamUsageEstimator.NUM_BYTES_INT32); return b; } public override void RecycleInt32Blocks(int[][] blocks, int offset, int length) { bytesUsed.AddAndGet(-(length * (Int32BlockPool.INT32_BLOCK_SIZE * RamUsageEstimator.NUM_BYTES_INT32))); } } public override string ToString() { return "DocumentsWriterPerThread [pendingDeletes=" + pendingUpdates + ", segment=" + (segmentInfo != null ? segmentInfo.Name : "null") + ", aborting=" + aborting + ", numDocsInRAM=" + numDocsInRAM + ", deleteQueue=" + deleteQueue + "]"; } } }
using Microsoft.Azure.Commands.Compute.Common; using Microsoft.Azure.Common.Authentication.Models; using Microsoft.WindowsAzure.Commands.Common.Extensions.DSC; using Microsoft.WindowsAzure.Commands.Common.Extensions.DSC.Publish; using Microsoft.WindowsAzure.Storage.Auth; using System; using System.Management.Automation; namespace Microsoft.Azure.Commands.Compute.Extension.DSC { /// <summary> /// Uploads a Desired State Configuration script to Azure blob storage, which /// later can be applied to Azure Virtual Machines using the /// Set-AzureRmVMDscExtension cmdlet. /// </summary> [Cmdlet( VerbsData.Publish, ProfileNouns.VirtualMachineDscConfiguration, SupportsShouldProcess = true, DefaultParameterSetName = UploadArchiveParameterSetName), OutputType( typeof(String))] public class PublishAzureVMDscConfigurationCommand : DscExtensionPublishCmdletCommonBase { private const string CreateArchiveParameterSetName = "CreateArchive"; private const string UploadArchiveParameterSetName = "UploadArchive"; [Parameter( Mandatory = true, Position = 2, ParameterSetName = UploadArchiveParameterSetName, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the resource group that contains the storage account.")] [ValidateNotNullOrEmpty] public string ResourceGroupName { get; set; } /// <summary> /// Path to a file containing one or more configurations; the file can be a /// PowerShell script (*.ps1) or MOF interface (*.mof). /// </summary> [Parameter( Mandatory = true, Position = 1, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Path to a file containing one or more configurations")] [ValidateNotNullOrEmpty] public string ConfigurationPath { get; set; } /// <summary> /// Name of the Azure Storage Container the configuration is uploaded to. /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, Position = 4, ParameterSetName = UploadArchiveParameterSetName, HelpMessage = "Name of the Azure Storage Container the configuration is uploaded to")] [ValidateNotNullOrEmpty] public string ContainerName { get; set; } /// <summary> /// The Azure Storage Account name used to upload the configuration script to the container specified by ContainerName. /// </summary> [Parameter( Mandatory = true, Position = 3, ValueFromPipelineByPropertyName = true, ParameterSetName = UploadArchiveParameterSetName, HelpMessage = "The Azure Storage Account name used to upload the configuration script to the container " + "specified by ContainerName ")] [ValidateNotNullOrEmpty] public String StorageAccountName { get; set; } /// <summary> /// Path to a local ZIP file to write the configuration archive to. /// When using this parameter, Publish-AzureRmVMDscConfiguration creates a /// local ZIP archive instead of uploading it to blob storage.. /// </summary> [Alias("ConfigurationArchivePath")] [Parameter( Position = 2, ValueFromPipelineByPropertyName = true, ParameterSetName = CreateArchiveParameterSetName, HelpMessage = "Path to a local ZIP file to write the configuration archive to.")] [ValidateNotNullOrEmpty] public string OutputArchivePath { get; set; } /// <summary> /// Suffix for the storage end point, e.g. core.windows.net /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = UploadArchiveParameterSetName, HelpMessage = "Suffix for the storage end point, e.g. core.windows.net")] [ValidateNotNullOrEmpty] public string StorageEndpointSuffix { get; set; } /// <summary> /// By default Publish-AzureRmVMDscConfiguration will not overwrite any existing blobs. /// Use -Force to overwrite them. /// </summary> [Parameter(HelpMessage = "By default Publish-AzureRmVMDscConfiguration will not overwrite any existing blobs")] public SwitchParameter Force { get; set; } /// <summary> /// Excludes DSC resource dependencies from the configuration archive /// </summary> [Parameter(HelpMessage = "Excludes DSC resource dependencies from the configuration archive")] public SwitchParameter SkipDependencyDetection { get; set; } /// <summary> ///Path to a .psd1 file that specifies the data for the Configuration. This /// file must contain a hashtable with the items described in /// http://technet.microsoft.com/en-us/library/dn249925.aspx. /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, HelpMessage = "Path to a .psd1 file that specifies the data for the Configuration. This is added to the configuration " + "archive and then passed to the configuration function. It gets overwritten by the configuration data path " + "provided through the Set-AzureRmVMDscExtension cmdlet")] [ValidateNotNullOrEmpty] public string ConfigurationDataPath { get; set; } /// <summary> /// Path to a file or a directory to include in the configuration archive /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, HelpMessage = "Path to a file or a directory to include in the configuration archive. It gets downloaded to the " + "VM along with the configuration")] [ValidateNotNullOrEmpty] public String[] AdditionalPath { get; set; } //Private Variables /// <summary> /// Credentials used to access Azure Storage /// </summary> private StorageCredentials _storageCredentials; public override void ExecuteCmdlet() { base.ExecuteCmdlet(); try { ValidatePsVersion(); //validate cmdlet params ConfigurationPath = GetUnresolvedProviderPathFromPSPath(ConfigurationPath); ValidateConfigurationPath(ConfigurationPath, ParameterSetName); if (ConfigurationDataPath != null) { ConfigurationDataPath = GetUnresolvedProviderPathFromPSPath(ConfigurationDataPath); ValidateConfigurationDataPath(ConfigurationDataPath); } if (AdditionalPath != null && AdditionalPath.Length > 0) { for (var count = 0; count < AdditionalPath.Length; count++) { AdditionalPath[count] = GetUnresolvedProviderPathFromPSPath(AdditionalPath[count]); } } switch (ParameterSetName) { case CreateArchiveParameterSetName: OutputArchivePath = GetUnresolvedProviderPathFromPSPath(OutputArchivePath); break; case UploadArchiveParameterSetName: _storageCredentials = this.GetStorageCredentials(ResourceGroupName,StorageAccountName); if (ContainerName == null) { ContainerName = DscExtensionCmdletConstants.DefaultContainerName; } if (StorageEndpointSuffix == null) { StorageEndpointSuffix = DefaultProfile.Context.Environment.GetEndpoint(AzureEnvironment.Endpoint.StorageEndpointSuffix); } break; } PublishConfiguration( ConfigurationPath, ConfigurationDataPath, AdditionalPath, OutputArchivePath, StorageEndpointSuffix, ContainerName, ParameterSetName, Force.IsPresent, SkipDependencyDetection.IsPresent, _storageCredentials); } finally { DeleteTemporaryFiles(); } } } }
// 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 ShiftLeftLogicalUInt321() { var test = new ImmUnaryOpTest__ShiftLeftLogicalUInt321(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.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 (Avx.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 (Avx.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(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } 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 ImmUnaryOpTest__ShiftLeftLogicalUInt321 { private struct TestStruct { public Vector256<UInt32> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftLeftLogicalUInt321 testClass) { var result = Avx2.ShiftLeftLogical(_fld, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32); private static UInt32[] _data = new UInt32[Op1ElementCount]; private static Vector256<UInt32> _clsVar; private Vector256<UInt32> _fld; private SimpleUnaryOpTest__DataTable<UInt32, UInt32> _dataTable; static ImmUnaryOpTest__ShiftLeftLogicalUInt321() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); } public ImmUnaryOpTest__ShiftLeftLogicalUInt321() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); } _dataTable = new SimpleUnaryOpTest__DataTable<UInt32, UInt32>(_data, new UInt32[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.ShiftLeftLogical( Unsafe.Read<Vector256<UInt32>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.ShiftLeftLogical( Avx.LoadVector256((UInt32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.ShiftLeftLogical( Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical), new Type[] { typeof(Vector256<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<UInt32>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical), new Type[] { typeof(Vector256<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((UInt32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical), new Type[] { typeof(Vector256<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.ShiftLeftLogical( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArrayPtr); var result = Avx2.ShiftLeftLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Avx.LoadVector256((UInt32*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftLeftLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftLeftLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftLeftLogicalUInt321(); var result = Avx2.ShiftLeftLogical(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.ShiftLeftLogical(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.ShiftLeftLogical(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(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(Vector256<UInt32> firstOp, void* result, [CallerMemberName] string method = "") { UInt32[] inArray = new UInt32[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { UInt32[] inArray = new UInt32[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(UInt32[] firstOp, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((uint)(firstOp[0] << 1) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((uint)(firstOp[i] << 1) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ShiftLeftLogical)}<UInt32>(Vector256<UInt32><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.DDF { using System; using System.Text; using NPOI.Util; using System.IO; /// <summary> /// The escher client anchor specifies which rows and cells the shape is bound to as well as /// the offsets within those cells. Each cell is 1024 units wide by 256 units long regardless /// of the actual size of the cell. The EscherClientAnchorRecord only applies to the top-most /// shapes. Shapes contained in groups are bound using the EscherChildAnchorRecords. /// @author Glen Stampoultzis /// </summary> public class EscherClientAnchorRecord : EscherRecord { public const short RECORD_ID = unchecked((short)0xF010); public const String RECORD_DESCRIPTION = "MsofbtClientAnchor"; /** * bit[0] - fMove (1 bit): A bit that specifies whether the shape will be kept intact when the cells are moved. * bit[1] - fSize (1 bit): A bit that specifies whether the shape will be kept intact when the cells are resized. If fMove is 1, the value MUST be 1. * bit[2-4] - reserved, MUST be 0 and MUST be ignored * bit[5-15]- Undefined and MUST be ignored. * * it can take values: 0, 2, 3 */ private short field_1_flag; private short field_2_col1; private short field_3_dx1; private short field_4_row1; private short field_5_dy1; private short field_6_col2; private short field_7_dx2; private short field_8_row2; private short field_9_dy2; private byte[] remainingData = new byte[0]; private bool shortRecord = false; /// <summary> /// This method deSerializes the record from a byte array. /// </summary> /// <param name="data">The byte array containing the escher record information</param> /// <param name="offset">The starting offset into data</param> /// <param name="recordFactory">May be null since this is not a container record.</param> /// <returns>The number of bytes Read from the byte array.</returns> public override int FillFields(byte[] data, int offset, IEscherRecordFactory recordFactory) { int bytesRemaining = ReadHeader(data, offset); int pos = offset + 8; int size = 0; // Always find 4 two byte entries. Sometimes find 9 if (bytesRemaining == 4) // Word format only 4 bytes { // Not sure exactly what the format is quite yet, likely a reference to a PLC } else { field_1_flag = LittleEndian.GetShort(data, pos + size); size += 2; field_2_col1 = LittleEndian.GetShort(data, pos + size); size += 2; field_3_dx1 = LittleEndian.GetShort(data, pos + size); size += 2; field_4_row1 = LittleEndian.GetShort(data, pos + size); size += 2; if (bytesRemaining >= 18) { field_5_dy1 = LittleEndian.GetShort(data, pos + size); size += 2; field_6_col2 = LittleEndian.GetShort(data, pos + size); size += 2; field_7_dx2 = LittleEndian.GetShort(data, pos + size); size += 2; field_8_row2 = LittleEndian.GetShort(data, pos + size); size += 2; field_9_dy2 = LittleEndian.GetShort(data, pos + size); size += 2; shortRecord = false; } else { shortRecord = true; } } bytesRemaining -= size; remainingData = new byte[bytesRemaining]; Array.Copy(data, pos + size, remainingData, 0, bytesRemaining); return 8 + size + bytesRemaining; } /// <summary> /// This method Serializes this escher record into a byte array. /// </summary> /// <param name="offset">The offset into data to start writing the record data to.</param> /// <param name="data">The byte array to Serialize to.</param> /// <param name="listener">a listener for begin and end serialization events.</param> /// <returns>The number of bytes written.</returns> public override int Serialize(int offset, byte[] data, EscherSerializationListener listener) { listener.BeforeRecordSerialize(offset, RecordId, this); if (remainingData == null) remainingData = new byte[0]; LittleEndian.PutShort(data, offset, Options); LittleEndian.PutShort(data, offset + 2, RecordId); int remainingBytes = remainingData.Length + (shortRecord ? 8 : 18); LittleEndian.PutInt(data, offset + 4, remainingBytes); LittleEndian.PutShort(data, offset + 8, field_1_flag); LittleEndian.PutShort(data, offset + 10, field_2_col1); LittleEndian.PutShort(data, offset + 12, field_3_dx1); LittleEndian.PutShort(data, offset + 14, field_4_row1); if (!shortRecord) { LittleEndian.PutShort(data, offset + 16, field_5_dy1); LittleEndian.PutShort(data, offset + 18, field_6_col2); LittleEndian.PutShort(data, offset + 20, field_7_dx2); LittleEndian.PutShort(data, offset + 22, field_8_row2); LittleEndian.PutShort(data, offset + 24, field_9_dy2); } Array.Copy(remainingData, 0, data, offset + (shortRecord ? 16 : 26), remainingData.Length); int pos = offset + 8 + (shortRecord ? 8 : 18) + remainingData.Length; listener.AfterRecordSerialize(pos, RecordId, pos - offset, this); return pos - offset; } /// <summary> /// Returns the number of bytes that are required to Serialize this record. /// </summary> /// <value>Number of bytes</value> public override int RecordSize { get { return 8 + (shortRecord ? 8 : 18) + (remainingData == null ? 0 : remainingData.Length); } } /// <summary> /// The record id for this record. /// </summary> /// <value></value> public override short RecordId { get { return RECORD_ID; } } /// <summary> /// The short name for this record /// </summary> /// <value></value> public override String RecordName { get { return "ClientAnchor"; } } /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> public override String ToString() { String nl = Environment.NewLine; String extraData = HexDump.Dump(this.remainingData, 0, 0); return GetType().Name + ":" + nl + " RecordId: 0x" + HexDump.ToHex(RECORD_ID) + nl + " Version: 0x" + HexDump.ToHex(Version) + nl + " Instance: 0x" + HexDump.ToHex(Instance) + nl + " Flag: " + field_1_flag + nl + " Col1: " + field_2_col1 + nl + " DX1: " + field_3_dx1 + nl + " Row1: " + field_4_row1 + nl + " DY1: " + field_5_dy1 + nl + " Col2: " + field_6_col2 + nl + " DX2: " + field_7_dx2 + nl + " Row2: " + field_8_row2 + nl + " DY2: " + field_9_dy2 + nl + " Extra Data:" + nl + extraData; } public override String ToXml(String tab) { String extraData = HexDump.Dump(this.remainingData, 0, 0).Trim(); StringBuilder builder = new StringBuilder(); builder.Append(tab) .Append(FormatXmlRecordHeader(GetType().Name, HexDump.ToHex(RecordId), HexDump.ToHex(Version), HexDump.ToHex(Instance))) .Append(tab).Append("\t").Append("<Flag>").Append(field_1_flag).Append("</Flag>\n") .Append(tab).Append("\t").Append("<Col1>").Append(field_2_col1).Append("</Col1>\n") .Append(tab).Append("\t").Append("<DX1>").Append(field_3_dx1).Append("</DX1>\n") .Append(tab).Append("\t").Append("<Row1>").Append(field_4_row1).Append("</Row1>\n") .Append(tab).Append("\t").Append("<DY1>").Append(field_5_dy1).Append("</DY1>\n") .Append(tab).Append("\t").Append("<Col2>").Append(field_6_col2).Append("</Col2>\n") .Append(tab).Append("\t").Append("<DX2>").Append(field_7_dx2).Append("</DX2>\n") .Append(tab).Append("\t").Append("<Row2>").Append(field_8_row2).Append("</Row2>\n") .Append(tab).Append("\t").Append("<DY2>").Append(field_9_dy2).Append("</DY2>\n") .Append(tab).Append("\t").Append("<ExtraData>").Append(extraData).Append("</ExtraData>\n"); builder.Append(tab).Append("</").Append(GetType().Name).Append(">\n"); return builder.ToString(); } /// <summary> /// Gets or sets the flag. /// </summary> /// <value>0 = Move and size with Cells, 2 = Move but don't size with cells, 3 = Don't move or size with cells.</value> public short Flag { get { return field_1_flag; } set { field_1_flag = value; } } /// <summary> /// Gets or sets The column number for the top-left position. 0 based. /// </summary> /// <value>The col1.</value> public short Col1 { get { return field_2_col1; } set { field_2_col1 = value; } } /// <summary> /// Gets or sets The x offset within the top-left cell. Range is from 0 to 1023. /// </summary> /// <value>The DX1.</value> public short Dx1 { get { return field_3_dx1; } set { field_3_dx1 = value; } } /// <summary> /// Gets or sets The row number for the top-left corner of the shape. /// </summary> /// <value>The row1.</value> public short Row1 { get { return field_4_row1; } set { this.field_4_row1 = value; } } /// <summary> /// Gets or sets The y offset within the top-left corner of the current shape. /// </summary> /// <value>The dy1.</value> public short Dy1 { get { return field_5_dy1; } set { shortRecord = false; this.field_5_dy1 = value; } } /// <summary> /// Gets or sets The column of the bottom right corner of this shape. /// </summary> /// <value>The col2.</value> public short Col2 { get { return field_6_col2; } set { shortRecord = false; this.field_6_col2 = value; } } /// <summary> /// Gets or sets The x offset withing the cell for the bottom-right corner of this shape. /// </summary> /// <value>The DX2.</value> public short Dx2 { get { return field_7_dx2; } set { shortRecord = false; this.field_7_dx2 = value; } } /// <summary> /// Gets or sets The row number for the bottom-right corner of the current shape. /// </summary> /// <value>The row2.</value> public short Row2 { get { return field_8_row2; } set { shortRecord = false; this.field_8_row2 = value; } } /// <summary> /// Gets or sets The y offset withing the cell for the bottom-right corner of this shape. /// </summary> /// <value>The dy2.</value> public short Dy2 { get { return field_9_dy2; } set { field_9_dy2 = value; } } /// <summary> /// Gets or sets the remaining data. /// </summary> /// <value>The remaining data.</value> public byte[] RemainingData { get { return remainingData; } set { if (value == null) { this.remainingData = new byte[0]; } else { remainingData = new byte[value.Length]; if (value.Length > 0) Array.Copy(value, remainingData, value.Length); } } } } }
using System; using System.Drawing; using System.Windows.Forms; using System.ComponentModel; using System.ComponentModel.Design; namespace WeifenLuo.WinFormsUI.Docking { partial class DockPanel { // This class comes from Jacob Slusser's MdiClientController class: // http://www.codeproject.com/cs/miscctrl/mdiclientcontroller.asp private class MdiClientController : NativeWindow, IComponent, IDisposable { private bool m_autoScroll = true; private BorderStyle m_borderStyle = BorderStyle.Fixed3D; private MdiClient m_mdiClient = null; private Form m_parentForm = null; private ISite m_site = null; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { if (Site != null && Site.Container != null) Site.Container.Remove(this); if (Disposed != null) Disposed(this, EventArgs.Empty); } } public bool AutoScroll { get { return m_autoScroll; } set { // By default the MdiClient control scrolls. It can appear though that // there are no scrollbars by turning them off when the non-client // area is calculated. I decided to expose this method following // the .NET vernacular of an AutoScroll property. m_autoScroll = value; if (MdiClient != null) UpdateStyles(); } } public BorderStyle BorderStyle { set { // Error-check the enum. if (!Enum.IsDefined(typeof(BorderStyle), value)) throw new InvalidEnumArgumentException(); m_borderStyle = value; if (MdiClient == null) return; // This property can actually be visible in design-mode, // but to keep it consistent with the others, // prevent this from being show at design-time. if (Site != null && Site.DesignMode) return; // There is no BorderStyle property exposed by the MdiClient class, // but this can be controlled by Win32 functions. A Win32 ExStyle // of WS_EX_CLIENTEDGE is equivalent to a Fixed3D border and a // Style of WS_BORDER is equivalent to a FixedSingle border. // This code is inspired Jason Dori's article: // "Adding designable borders to user controls". // http://www.codeproject.com/cs/miscctrl/CsAddingBorders.asp if (!Win32Helper.IsRunningOnMono) { // Get styles using Win32 calls int style = NativeMethods.GetWindowLong(MdiClient.Handle, (int)Win32.GetWindowLongIndex.GWL_STYLE); int exStyle = NativeMethods.GetWindowLong(MdiClient.Handle, (int)Win32.GetWindowLongIndex.GWL_EXSTYLE); // Add or remove style flags as necessary. switch (m_borderStyle) { case BorderStyle.Fixed3D: exStyle |= (int)Win32.WindowExStyles.WS_EX_CLIENTEDGE; style &= ~((int)Win32.WindowStyles.WS_BORDER); break; case BorderStyle.FixedSingle: exStyle &= ~((int)Win32.WindowExStyles.WS_EX_CLIENTEDGE); style |= (int)Win32.WindowStyles.WS_BORDER; break; case BorderStyle.None: style &= ~((int)Win32.WindowStyles.WS_BORDER); exStyle &= ~((int)Win32.WindowExStyles.WS_EX_CLIENTEDGE); break; } // Set the styles using Win32 calls NativeMethods.SetWindowLong(MdiClient.Handle, (int)Win32.GetWindowLongIndex.GWL_STYLE, style); NativeMethods.SetWindowLong(MdiClient.Handle, (int)Win32.GetWindowLongIndex.GWL_EXSTYLE, exStyle); } // Cause an update of the non-client area. UpdateStyles(); } } public MdiClient MdiClient { get { return m_mdiClient; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Form ParentForm { get { return m_parentForm; } set { // If the ParentForm has previously been set, // unwire events connected to the old parent. if (m_parentForm != null) { m_parentForm.HandleCreated -= new EventHandler(ParentFormHandleCreated); m_parentForm.MdiChildActivate -= new EventHandler(ParentFormMdiChildActivate); } m_parentForm = value; if (m_parentForm == null) return; // If the parent form has not been created yet, // wait to initialize the MDI client until it is. if (m_parentForm.IsHandleCreated) { InitializeMdiClient(); RefreshProperties(); } else m_parentForm.HandleCreated += new EventHandler(ParentFormHandleCreated); m_parentForm.MdiChildActivate += new EventHandler(ParentFormMdiChildActivate); } } public ISite Site { get { return m_site; } set { m_site = value; if (m_site == null) return; // If the component is dropped onto a form during design-time, // set the ParentForm property. IDesignerHost host = (value.GetService(typeof(IDesignerHost)) as IDesignerHost); if (host != null) { Form parent = host.RootComponent as Form; if (parent != null) ParentForm = parent; } } } public void RenewMdiClient() { // Reinitialize the MdiClient and its properties. InitializeMdiClient(); RefreshProperties(); } public event EventHandler Disposed; public event EventHandler HandleAssigned; public event EventHandler MdiChildActivate; public event LayoutEventHandler Layout; protected virtual void OnHandleAssigned(EventArgs e) { // Raise the HandleAssigned event. if (HandleAssigned != null) HandleAssigned(this, e); } protected virtual void OnMdiChildActivate(EventArgs e) { // Raise the MdiChildActivate event if (MdiChildActivate != null) MdiChildActivate(this, e); } protected virtual void OnLayout(LayoutEventArgs e) { // Raise the Layout event if (Layout != null) Layout(this, e); } public event PaintEventHandler Paint; protected virtual void OnPaint(PaintEventArgs e) { // Raise the Paint event. if (Paint != null) Paint(this, e); } protected override void WndProc(ref Message m) { switch (m.Msg) { case (int)Win32.Msgs.WM_NCCALCSIZE: // If AutoScroll is set to false, hide the scrollbars when the control // calculates its non-client area. if (!AutoScroll) { if (!Win32Helper.IsRunningOnMono) { NativeMethods.ShowScrollBar(m.HWnd, (int)Win32.ScrollBars.SB_BOTH, 0 /*false*/); } } break; } base.WndProc(ref m); } private void ParentFormHandleCreated(object sender, EventArgs e) { // The form has been created, unwire the event, and initialize the MdiClient. this.m_parentForm.HandleCreated -= new EventHandler(ParentFormHandleCreated); InitializeMdiClient(); RefreshProperties(); } private void ParentFormMdiChildActivate(object sender, EventArgs e) { OnMdiChildActivate(e); } private void MdiClientLayout(object sender, LayoutEventArgs e) { OnLayout(e); } private void MdiClientHandleDestroyed(object sender, EventArgs e) { // If the MdiClient handle has been released, drop the reference and // release the handle. if (m_mdiClient != null) { m_mdiClient.HandleDestroyed -= new EventHandler(MdiClientHandleDestroyed); m_mdiClient = null; } ReleaseHandle(); } private void InitializeMdiClient() { // If the mdiClient has previously been set, unwire events connected // to the old MDI. if (MdiClient != null) { MdiClient.HandleDestroyed -= new EventHandler(MdiClientHandleDestroyed); MdiClient.Layout -= new LayoutEventHandler(MdiClientLayout); } if (ParentForm == null) return; // Get the MdiClient from the parent form. foreach (Control control in ParentForm.Controls) { // If the form is an MDI container, it will contain an MdiClient control // just as it would any other control. m_mdiClient = control as MdiClient; if (m_mdiClient == null) continue; // Assign the MdiClient Handle to the NativeWindow. ReleaseHandle(); AssignHandle(MdiClient.Handle); // Raise the HandleAssigned event. OnHandleAssigned(EventArgs.Empty); // Monitor the MdiClient for when its handle is destroyed. MdiClient.HandleDestroyed += new EventHandler(MdiClientHandleDestroyed); MdiClient.Layout += new LayoutEventHandler(MdiClientLayout); break; } } private void RefreshProperties() { // Refresh all the properties BorderStyle = m_borderStyle; AutoScroll = m_autoScroll; } private void UpdateStyles() { // To show style changes, the non-client area must be repainted. Using the // control's Invalidate method does not affect the non-client area. // Instead use a Win32 call to signal the style has changed. if (!Win32Helper.IsRunningOnMono) NativeMethods.SetWindowPos(MdiClient.Handle, IntPtr.Zero, 0, 0, 0, 0, Win32.FlagsSetWindowPos.SWP_NOACTIVATE | Win32.FlagsSetWindowPos.SWP_NOMOVE | Win32.FlagsSetWindowPos.SWP_NOSIZE | Win32.FlagsSetWindowPos.SWP_NOZORDER | Win32.FlagsSetWindowPos.SWP_NOOWNERZORDER | Win32.FlagsSetWindowPos.SWP_FRAMECHANGED); } } private MdiClientController m_mdiClientController = null; private MdiClientController GetMdiClientController() { if (m_mdiClientController == null) { m_mdiClientController = new MdiClientController(); m_mdiClientController.HandleAssigned += new EventHandler(MdiClientHandleAssigned); m_mdiClientController.MdiChildActivate += new EventHandler(ParentFormMdiChildActivate); m_mdiClientController.Layout += new LayoutEventHandler(MdiClient_Layout); } return m_mdiClientController; } private void ParentFormMdiChildActivate(object sender, EventArgs e) { if (GetMdiClientController().ParentForm == null) return; IDockContent content = GetMdiClientController().ParentForm.ActiveMdiChild as IDockContent; if (content == null) return; if (content.DockHandler.DockPanel == this && content.DockHandler.Pane != null) content.DockHandler.Pane.ActiveContent = content; } private bool MdiClientExists { get { return GetMdiClientController().MdiClient != null; } } private void SetMdiClientBounds(Rectangle bounds) { GetMdiClientController().MdiClient.Bounds = bounds; } private void SuspendMdiClientLayout() { if (GetMdiClientController().MdiClient != null) GetMdiClientController().MdiClient.SuspendLayout(); } private void ResumeMdiClientLayout(bool perform) { if (GetMdiClientController().MdiClient != null) GetMdiClientController().MdiClient.ResumeLayout(perform); } private void PerformMdiClientLayout() { if (GetMdiClientController().MdiClient != null) GetMdiClientController().MdiClient.PerformLayout(); } // Called when: // 1. DockPanel.DocumentStyle changed // 2. DockPanel.Visible changed // 3. MdiClientController.Handle assigned private void SetMdiClient() { MdiClientController controller = GetMdiClientController(); if (this.DocumentStyle == DocumentStyle.DockingMdi) { controller.AutoScroll = false; controller.BorderStyle = BorderStyle.None; if (MdiClientExists) controller.MdiClient.Dock = DockStyle.Fill; } else if (DocumentStyle == DocumentStyle.DockingSdi || DocumentStyle == DocumentStyle.DockingWindow) { controller.AutoScroll = true; controller.BorderStyle = BorderStyle.Fixed3D; if (MdiClientExists) controller.MdiClient.Dock = DockStyle.Fill; } else if (this.DocumentStyle == DocumentStyle.SystemMdi) { controller.AutoScroll = true; controller.BorderStyle = BorderStyle.Fixed3D; if (controller.MdiClient != null) { controller.MdiClient.Dock = DockStyle.None; controller.MdiClient.Bounds = SystemMdiClientBounds; } } } internal Rectangle RectangleToMdiClient(Rectangle rect) { if (MdiClientExists) return GetMdiClientController().MdiClient.RectangleToClient(rect); else return Rectangle.Empty; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="MainViewModel.cs" company="PicklesDoc"> // Copyright 2011 Jeffrey Cameron // Copyright 2012-present PicklesDoc team and community contributors // // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO.Abstractions; using System.Linq; using System.Windows.Input; using Autofac; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using PicklesDoc.Pickles.ObjectModel; using PicklesDoc.Pickles.UserInterface.Mvvm; using PicklesDoc.Pickles.UserInterface.Settings; namespace PicklesDoc.Pickles.UserInterface.ViewModel { /// <summary> /// This class contains properties that the main View can data bind to. /// <para> /// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel. /// </para> /// <para> /// You can also use Blend to data bind with the tool's support. /// </para> /// <para> /// See http://www.galasoft.ch/mvvm /// </para> /// </summary> public class MainViewModel : ViewModelBase { private readonly MultiSelectableCollection<DocumentationFormat> documentationFormats; private readonly SelectableCollection<TestResultsFormat> testResultsFormats; private readonly RelayCommand browseForFeatureFolderCommand; private readonly RelayCommand browseForOutputFolderCommand; private readonly RelayCommand browseForTestResultsFileCommand; private readonly RelayCommand generateCommand; private readonly RelayCommand openOutputDirectory; private readonly IMainModelSerializer mainModelSerializer; private readonly IFileSystem fileSystem; private readonly CultureInfo[] neutralCultures; private string picklesVersion = typeof(Feature).Assembly.GetName().Version.ToString(); private string featureFolder; private string outputFolder; private string projectName; private string projectVersion; private string testResultsFile; private CultureInfo selectedLanguage; private bool includeTests; private bool isRunning; private bool isFeatureDirectoryValid; private bool isOutputDirectoryValid; private bool isProjectNameValid; private bool isProjectVersionValid; private bool isTestResultsFileValid; private bool isTestResultsFormatValid; private bool isLanguageValid = true; private bool createDirectoryForEachOutputFormat; private bool isDocumentationFormatValid; public MainViewModel(IMainModelSerializer mainModelSerializer, IFileSystem fileSystem) { this.documentationFormats = new MultiSelectableCollection<DocumentationFormat>( Enum.GetValues(typeof(DocumentationFormat)).Cast<DocumentationFormat>()); this.documentationFormats.First().IsSelected = true; this.documentationFormats.SelectionChanged += this.DocumentationFormatsOnCollectionChanged; this.testResultsFormats = new SelectableCollection<TestResultsFormat>( Enum.GetValues(typeof(TestResultsFormat)).Cast<TestResultsFormat>()); this.testResultsFormats.First().IsSelected = true; this.testResultsFormats.SelectionChanged += this.TestResultsFormatsOnCollectionChanged; this.browseForFeatureFolderCommand = new RelayCommand(this.DoBrowseForFeature); this.browseForOutputFolderCommand = new RelayCommand(this.DoBrowseForOutputFolder); this.browseForTestResultsFileCommand = new RelayCommand(this.DoBrowseForTestResultsFile); this.generateCommand = new RelayCommand(this.DoGenerate, this.CanGenerate); this.openOutputDirectory = new RelayCommand(this.DoOpenOutputDirectory, this.CanOpenOutputDirectory); this.PropertyChanged += this.MainWindowViewModelPropertyChanged; this.neutralCultures = CultureInfo.GetCultures(CultureTypes.NeutralCultures); this.selectedLanguage = CultureInfo.GetCultureInfo("en"); this.mainModelSerializer = mainModelSerializer; this.fileSystem = fileSystem; } public string PicklesVersion { get { return this.picklesVersion; } set { this.Set(() => this.PicklesVersion, ref this.picklesVersion, value); } } public string FeatureFolder { get { return this.featureFolder; } set { this.Set(() => this.FeatureFolder, ref this.featureFolder, value); } } public string OutputFolder { get { return this.outputFolder; } set { this.Set(() => this.OutputFolder, ref this.outputFolder, value); } } public MultiSelectableCollection<DocumentationFormat> DocumentationFormatValues { get { return this.documentationFormats; } } public string ProjectName { get { return this.projectName; } set { this.Set(() => this.ProjectName, ref this.projectName, value); } } public string ProjectVersion { get { return this.projectVersion; } set { this.Set(() => this.ProjectVersion, ref this.projectVersion, value); } } public string TestResultsFile { get { return this.testResultsFile; } set { this.Set(() => this.TestResultsFile, ref this.testResultsFile, value); } } public SelectableCollection<TestResultsFormat> TestResultsFormatValues { get { return this.testResultsFormats; } } public CultureInfo SelectedLanguage { get { return this.selectedLanguage; } set { this.Set(() => this.SelectedLanguage, ref this.selectedLanguage, value); } } public IEnumerable<CultureInfo> LanguageValues { get { return this.neutralCultures; } } public bool IncludeTests { get { return this.includeTests; } set { this.Set(() => this.IncludeTests, ref this.includeTests, value); } } public ICommand GeneratePickles { get { return this.generateCommand; } } public ICommand BrowseForFeatureFolder { get { return this.browseForFeatureFolderCommand; } } public ICommand BrowseForOutputFolder { get { return this.browseForOutputFolderCommand; } } public ICommand BrowseForTestResultsFile { get { return this.browseForTestResultsFileCommand; } } public RelayCommand OpenOutputDirectory { get { return this.openOutputDirectory; } } public bool IsRunning { get { return this.isRunning; } set { this.Set(() => this.IsRunning, ref this.isRunning, value); } } public bool IsFeatureDirectoryValid { get { return this.isFeatureDirectoryValid; } set { this.Set(() => this.IsFeatureDirectoryValid, ref this.isFeatureDirectoryValid, value); } } public bool IsDocumentationFormatValid { get { return this.isDocumentationFormatValid; } set { this.Set(() => this.IsDocumentationFormatValid, ref this.isDocumentationFormatValid, value); } } public bool IsOutputDirectoryValid { get { return this.isOutputDirectoryValid; } set { this.Set(() => this.IsOutputDirectoryValid, ref this.isOutputDirectoryValid, value); } } public bool IsProjectNameValid { get { return this.isProjectNameValid; } set { this.Set(() => this.IsProjectNameValid, ref this.isProjectNameValid, value); } } public bool IsProjectVersionValid { get { return this.isProjectVersionValid; } set { this.Set(() => this.IsProjectVersionValid, ref this.isProjectVersionValid, value); } } public bool IsTestResultsFileValid { get { return this.isTestResultsFileValid; } set { this.Set(() => this.IsTestResultsFileValid, ref this.isTestResultsFileValid, value); } } public bool IsTestResultsFormatValid { get { return this.isTestResultsFormatValid; } set { this.Set(() => this.IsTestResultsFormatValid, ref this.isTestResultsFormatValid, value); } } public bool IsLanguageValid { get { return this.isLanguageValid; } set { this.Set(() => this.IsLanguageValid, ref this.isLanguageValid, value); } } public bool CreateDirectoryForEachOutputFormat { get { return this.createDirectoryForEachOutputFormat; } set { this.Set(() => this.CreateDirectoryForEachOutputFormat, ref this.createDirectoryForEachOutputFormat, value); } } public void SaveToSettings() { MainModel mainModel = new MainModel { FeatureDirectory = this.featureFolder, OutputDirectory = this.outputFolder, ProjectName = this.projectName, ProjectVersion = this.projectVersion, IncludeTestResults = this.includeTests, TestResultsFile = this.testResultsFile, TestResultsFormat = this.testResultsFormats.Selected, SelectedLanguageLcid = this.selectedLanguage.LCID, DocumentationFormats = this.documentationFormats.Where(item => item.IsSelected).Select(item => item.Item).ToArray(), CreateDirectoryForEachOutputFormat = this.createDirectoryForEachOutputFormat }; this.mainModelSerializer.Write(mainModel); } public void LoadFromSettings() { MainModel mainModel = this.mainModelSerializer.Read(); if (mainModel == null) { return; } this.FeatureFolder = mainModel.FeatureDirectory; this.OutputFolder = mainModel.OutputDirectory; this.ProjectName = mainModel.ProjectName; this.ProjectVersion = mainModel.ProjectVersion; this.IncludeTests = mainModel.IncludeTestResults; this.TestResultsFile = mainModel.TestResultsFile; foreach (var item in this.TestResultsFormatValues) { if (item.Item == mainModel.TestResultsFormat) { item.IsSelected = true; } else { item.IsSelected = false; } } this.SelectedLanguage = this.neutralCultures.Where(lv => lv.LCID == mainModel.SelectedLanguageLcid).FirstOrDefault(); foreach (var item in this.documentationFormats) { item.IsSelected = mainModel.DocumentationFormats.Contains(item.Item); } this.CreateDirectoryForEachOutputFormat = mainModel.CreateDirectoryForEachOutputFormat; } private void TestResultsFormatsOnCollectionChanged(object sender, EventArgs notifyCollectionChangedEventArgs) { this.IsTestResultsFormatValid = Enum.IsDefined(typeof(TestResultsFormat), this.testResultsFormats.Selected); } private void DocumentationFormatsOnCollectionChanged(object sender, EventArgs notifyCollectionChangedEventArgs) { this.IsDocumentationFormatValid = this.documentationFormats.Selected.Any(); } private void MainWindowViewModelPropertyChanged(object sender, PropertyChangedEventArgs e) { switch (e.PropertyName) { case "FeatureFolder": { if (this.fileSystem.Directory.Exists(this.featureFolder)) { this.IsFeatureDirectoryValid = true; } else { this.IsFeatureDirectoryValid = false; } break; } case "OutputFolder": { if (this.fileSystem.Directory.Exists(this.outputFolder)) { this.IsOutputDirectoryValid = true; } else { this.IsOutputDirectoryValid = false; } this.openOutputDirectory.RaiseCanExecuteChanged(); break; } case "TestResultsFile": { if (this.testResultsFile == null || this.testResultsFile.Split(';').All(trf => this.fileSystem.File.Exists(trf))) { this.IsTestResultsFileValid = true; } else { this.IsTestResultsFileValid = false; } break; } case "ProjectName": { this.IsProjectNameValid = !string.IsNullOrWhiteSpace(this.projectName); break; } case "ProjectVersion": { this.IsProjectVersionValid = !string.IsNullOrWhiteSpace(this.projectVersion); break; } case "IsRunning": case "IsFeatureDirectoryValid": case "IsOutputDirectoryValid": case "IsProjectNameValid": case "IsProjectVersionValid": case "IsTestResultsFileValid": case "IsTestResultsFormatValid": case "IsLanguageValid": case "IncludeTests": case "IsDocumentationFormatValid": { this.generateCommand.RaiseCanExecuteChanged(); break; } } } private bool CanGenerate() { return !this.isRunning && this.isFeatureDirectoryValid && this.isOutputDirectoryValid && this.isProjectNameValid && this.isProjectVersionValid && (this.isTestResultsFileValid || !this.includeTests) && (this.isTestResultsFormatValid || !this.includeTests) && this.isDocumentationFormatValid && this.isLanguageValid; } private void DoGenerate() { this.IsRunning = true; var backgroundWorker = new BackgroundWorker(); backgroundWorker.DoWork += (sender, args) => this.DoWork(); backgroundWorker.RunWorkerCompleted += (sender, args) => { this.IsRunning = false; }; backgroundWorker.RunWorkerAsync(); } private void DoWork() { foreach (DocumentationFormat documentationFormat in this.documentationFormats.Selected) { var builder = new ContainerBuilder(); builder.RegisterAssemblyTypes(typeof(Runner).Assembly); builder.Register<IFileSystem>(_ => this.fileSystem).SingleInstance(); builder.RegisterModule<PicklesModule>(); var container = builder.Build(); var configuration = container.Resolve<Configuration>(); configuration.FeatureFolder = this.fileSystem.DirectoryInfo.FromDirectoryName(this.featureFolder); if (this.createDirectoryForEachOutputFormat) { configuration.OutputFolder = this.fileSystem.DirectoryInfo.FromDirectoryName( this.fileSystem.Path.Combine( this.outputFolder, documentationFormat.ToString("G"))); } else { configuration.OutputFolder = this.fileSystem.DirectoryInfo.FromDirectoryName(this.outputFolder); } configuration.SystemUnderTestName = this.projectName; configuration.SystemUnderTestVersion = this.projectVersion; configuration.AddTestResultFiles(this.IncludeTests ? this.testResultsFile.Split(';').Select(trf => this.fileSystem.FileInfo.FromFileName(trf)).ToArray() : null); configuration.TestResultsFormat = this.testResultsFormats.Selected; configuration.Language = this.selectedLanguage != null ? this.selectedLanguage.TwoLetterISOLanguageName : CultureInfo.CurrentUICulture.TwoLetterISOLanguageName; configuration.DocumentationFormat = documentationFormat; var runner = container.Resolve<Runner>(); runner.Run(container); } } private void DoBrowseForTestResultsFile() { var dlg = new Ookii.Dialogs.Wpf.VistaOpenFileDialog(); dlg.Multiselect = true; var result = dlg.ShowDialog(); if (result == true) { this.TestResultsFile = string.Join(";", dlg.FileNames); } } private void DoBrowseForFeature() { var dlg = new Ookii.Dialogs.Wpf.VistaFolderBrowserDialog(); var result = dlg.ShowDialog(); if (result == true) { this.FeatureFolder = dlg.SelectedPath; } } private void DoBrowseForOutputFolder() { var dlg = new Ookii.Dialogs.Wpf.VistaFolderBrowserDialog(); var result = dlg.ShowDialog(); if (result == true) { this.OutputFolder = dlg.SelectedPath; } } private void DoOpenOutputDirectory() { Process.Start(this.outputFolder); } private bool CanOpenOutputDirectory() { return this.isOutputDirectoryValid; } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the cloudfront-2015-04-17.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.CloudFront.Model { /// <summary> /// A distribution Configuration. /// </summary> public partial class DistributionConfig { private Aliases _aliases; private CacheBehaviors _cacheBehaviors; private string _callerReference; private string _comment; private CustomErrorResponses _customErrorResponses; private DefaultCacheBehavior _defaultCacheBehavior; private string _defaultRootObject; private bool? _enabled; private LoggingConfig _logging; private Origins _origins; private PriceClass _priceClass; private Restrictions _restrictions; private ViewerCertificate _viewerCertificate; /// <summary> /// Empty constructor used to set properties independently even when a simple constructor is available /// </summary> public DistributionConfig() { } /// <summary> /// Instantiates DistributionConfig with the parameterized properties /// </summary> /// <param name="callerReference">A unique number that ensures the request can't be replayed. If the CallerReference is new (no matter the content of the DistributionConfig object), a new distribution is created. If the CallerReference is a value you already sent in a previous request to create a distribution, and the content of the DistributionConfig is identical to the original request (ignoring white space), the response includes the same information returned to the original request. If the CallerReference is a value you already sent in a previous request to create a distribution but the content of the DistributionConfig is different from the original request, CloudFront returns a DistributionAlreadyExists error.</param> /// <param name="enabled">Whether the distribution is enabled to accept end user requests for content.</param> public DistributionConfig(string callerReference, bool enabled) { _callerReference = callerReference; _enabled = enabled; } /// <summary> /// Gets and sets the property Aliases. A complex type that contains information about /// CNAMEs (alternate domain names), if any, for this distribution. /// </summary> public Aliases Aliases { get { return this._aliases; } set { this._aliases = value; } } // Check to see if Aliases property is set internal bool IsSetAliases() { return this._aliases != null; } /// <summary> /// Gets and sets the property CacheBehaviors. A complex type that contains zero or more /// CacheBehavior elements. /// </summary> public CacheBehaviors CacheBehaviors { get { return this._cacheBehaviors; } set { this._cacheBehaviors = value; } } // Check to see if CacheBehaviors property is set internal bool IsSetCacheBehaviors() { return this._cacheBehaviors != null; } /// <summary> /// Gets and sets the property CallerReference. A unique number that ensures the request /// can't be replayed. If the CallerReference is new (no matter the content of the DistributionConfig /// object), a new distribution is created. If the CallerReference is a value you already /// sent in a previous request to create a distribution, and the content of the DistributionConfig /// is identical to the original request (ignoring white space), the response includes /// the same information returned to the original request. If the CallerReference is a /// value you already sent in a previous request to create a distribution but the content /// of the DistributionConfig is different from the original request, CloudFront returns /// a DistributionAlreadyExists error. /// </summary> public string CallerReference { get { return this._callerReference; } set { this._callerReference = value; } } // Check to see if CallerReference property is set internal bool IsSetCallerReference() { return this._callerReference != null; } /// <summary> /// Gets and sets the property Comment. Any comments you want to include about the distribution. /// </summary> public string Comment { get { return this._comment; } set { this._comment = value; } } // Check to see if Comment property is set internal bool IsSetComment() { return this._comment != null; } /// <summary> /// Gets and sets the property CustomErrorResponses. A complex type that contains zero /// or more CustomErrorResponse elements. /// </summary> public CustomErrorResponses CustomErrorResponses { get { return this._customErrorResponses; } set { this._customErrorResponses = value; } } // Check to see if CustomErrorResponses property is set internal bool IsSetCustomErrorResponses() { return this._customErrorResponses != null; } /// <summary> /// Gets and sets the property DefaultCacheBehavior. A complex type that describes the /// default cache behavior if you do not specify a CacheBehavior element or if files don't /// match any of the values of PathPattern in CacheBehavior elements.You must create exactly /// one default cache behavior. /// </summary> public DefaultCacheBehavior DefaultCacheBehavior { get { return this._defaultCacheBehavior; } set { this._defaultCacheBehavior = value; } } // Check to see if DefaultCacheBehavior property is set internal bool IsSetDefaultCacheBehavior() { return this._defaultCacheBehavior != null; } /// <summary> /// Gets and sets the property DefaultRootObject. The object that you want CloudFront /// to return (for example, index.html) when an end user requests the root URL for your /// distribution (http://www.example.com) instead of an object in your distribution (http://www.example.com/index.html). /// Specifying a default root object avoids exposing the contents of your distribution. /// If you don't want to specify a default root object when you create a distribution, /// include an empty DefaultRootObject element. To delete the default root object from /// an existing distribution, update the distribution configuration and include an empty /// DefaultRootObject element. To replace the default root object, update the distribution /// configuration and specify the new object. /// </summary> public string DefaultRootObject { get { return this._defaultRootObject; } set { this._defaultRootObject = value; } } // Check to see if DefaultRootObject property is set internal bool IsSetDefaultRootObject() { return this._defaultRootObject != null; } /// <summary> /// Gets and sets the property Enabled. Whether the distribution is enabled to accept /// end user requests for content. /// </summary> public bool Enabled { get { return this._enabled.GetValueOrDefault(); } set { this._enabled = value; } } // Check to see if Enabled property is set internal bool IsSetEnabled() { return this._enabled.HasValue; } /// <summary> /// Gets and sets the property Logging. A complex type that controls whether access logs /// are written for the distribution. /// </summary> public LoggingConfig Logging { get { return this._logging; } set { this._logging = value; } } // Check to see if Logging property is set internal bool IsSetLogging() { return this._logging != null; } /// <summary> /// Gets and sets the property Origins. A complex type that contains information about /// origins for this distribution. /// </summary> public Origins Origins { get { return this._origins; } set { this._origins = value; } } // Check to see if Origins property is set internal bool IsSetOrigins() { return this._origins != null; } /// <summary> /// Gets and sets the property PriceClass. A complex type that contains information about /// price class for this distribution. /// </summary> public PriceClass PriceClass { get { return this._priceClass; } set { this._priceClass = value; } } // Check to see if PriceClass property is set internal bool IsSetPriceClass() { return this._priceClass != null; } /// <summary> /// Gets and sets the property Restrictions. /// </summary> public Restrictions Restrictions { get { return this._restrictions; } set { this._restrictions = value; } } // Check to see if Restrictions property is set internal bool IsSetRestrictions() { return this._restrictions != null; } /// <summary> /// Gets and sets the property ViewerCertificate. /// </summary> public ViewerCertificate ViewerCertificate { get { return this._viewerCertificate; } set { this._viewerCertificate = value; } } // Check to see if ViewerCertificate property is set internal bool IsSetViewerCertificate() { return this._viewerCertificate != null; } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Windows.Media.VisualTreeHelper.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Windows.Media { static public partial class VisualTreeHelper { #region Methods and constructors public static System.Windows.Media.Effects.BitmapEffect GetBitmapEffect(Visual reference) { Contract.Requires(reference != null); // May return null return default(System.Windows.Media.Effects.BitmapEffect); } public static System.Windows.Media.Effects.BitmapEffectInput GetBitmapEffectInput(Visual reference) { Contract.Requires(reference != null); // May return null return default(System.Windows.Media.Effects.BitmapEffectInput); } public static CacheMode GetCacheMode(Visual reference) { return default(CacheMode); } public static System.Windows.DependencyObject GetChild(System.Windows.DependencyObject reference, int childIndex) { Contract.Requires(reference != null); Contract.Ensures(Contract.Result<System.Windows.DependencyObject>() != null); return default(System.Windows.DependencyObject); } public static int GetChildrenCount(System.Windows.DependencyObject reference) { Contract.Requires(reference != null); Contract.Ensures(Contract.Result<int>() >= 0); return default(int); } public static Geometry GetClip(Visual reference) { Contract.Requires(reference != null); // May return null return default(Geometry); } public static System.Windows.Rect GetContentBounds(Visual reference) { Contract.Requires(reference != null); return default(System.Windows.Rect); } public static System.Windows.Media.Media3D.Rect3D GetContentBounds(System.Windows.Media.Media3D.Visual3D reference) { Contract.Requires(reference != null); return default(System.Windows.Media.Media3D.Rect3D); } public static System.Windows.Media.Media3D.Rect3D GetDescendantBounds(System.Windows.Media.Media3D.Visual3D reference) { Contract.Requires(reference != null); return default(System.Windows.Media.Media3D.Rect3D); } public static System.Windows.Rect GetDescendantBounds(Visual reference) { Contract.Requires(reference != null); return default(System.Windows.Rect); } public static DrawingGroup GetDrawing(Visual reference) { Contract.Requires(reference != null); return default(DrawingGroup); } public static EdgeMode GetEdgeMode(Visual reference) { Contract.Requires(reference != null); return default(EdgeMode); } public static System.Windows.Media.Effects.Effect GetEffect(Visual reference) { Contract.Requires(reference != null); return default(System.Windows.Media.Effects.Effect); } public static System.Windows.Vector GetOffset(Visual reference) { Contract.Requires(reference != null); return default(System.Windows.Vector); } public static double GetOpacity(Visual reference) { Contract.Requires(reference != null); return default(double); } public static Brush GetOpacityMask(Visual reference) { Contract.Requires(reference != null); return default(Brush); } public static System.Windows.DependencyObject GetParent(System.Windows.DependencyObject reference) { Contract.Requires(reference != null); return default(System.Windows.DependencyObject); } public static Transform GetTransform(Visual reference) { Contract.Requires(reference != null); return default(Transform); } public static DoubleCollection GetXSnappingGuidelines(Visual reference) { Contract.Requires(reference != null); return default(DoubleCollection); } public static DoubleCollection GetYSnappingGuidelines(Visual reference) { Contract.Requires(reference != null); return default(DoubleCollection); } public static void HitTest(System.Windows.Media.Media3D.Visual3D reference, HitTestFilterCallback filterCallback, HitTestResultCallback resultCallback, System.Windows.Media.Media3D.HitTestParameters3D hitTestParameters) { Contract.Requires(reference != null); Contract.Requires(resultCallback != null); Contract.Requires(hitTestParameters != null); } public static void HitTest(Visual reference, HitTestFilterCallback filterCallback, HitTestResultCallback resultCallback, HitTestParameters hitTestParameters) { Contract.Requires(reference != null); Contract.Requires(resultCallback != null); Contract.Requires(hitTestParameters != null); } public static HitTestResult HitTest(Visual reference, System.Windows.Point point) { Contract.Requires(reference != null); return default(HitTestResult); } #endregion } }
using System.Windows.Forms; using GuiLabs.Utils; namespace GuiLabs.Canvas.Controls { public partial class TextBox { #region Events public event KeyPressEventHandler PreviewKeyPress; protected void RaisePreviewKeyPress(KeyPressEventArgs e) { if (PreviewKeyPress != null) { PreviewKeyPress(this, e); } } public event KeyEventHandler PreviewKeyDown; protected void RaisePreviewKeyDown(KeyEventArgs e) { if (PreviewKeyDown != null) { PreviewKeyDown(this, e); } } public event KeyEventHandler AfterKeyDown; protected void RaiseAfterKeyDown(KeyEventArgs e) { if (AfterKeyDown != null) { AfterKeyDown(this, e); } } #endregion #region KeyBrake private KeyboardBrakeSystem mKeyBrake = new KeyboardBrakeSystem(); public KeyboardBrakeSystem KeyBrake { get { return mKeyBrake; } set { mKeyBrake = value; } } #endregion /// <summary> /// Called when this TextBox has focus and user presses a keyboard key. /// </summary> /// <remarks> /// Raises KeyDown event. /// </remarks> /// <param name="e">Information about the key pressed.</param> public override void OnKeyDown(KeyEventArgs e) { RaisePreviewKeyDown(e); if (e.Handled) { return; } if (e.KeyCode == Keys.Left) { OnKeyDownLeft(e); } else if (e.KeyCode == Keys.Right) { OnKeyDownRight(e); } else if (e.KeyCode == Keys.Down) { OnKeyDownDown(e); } else if (e.KeyCode == Keys.Home) { OnKeyDownHome(e); } else if (e.KeyCode == Keys.End) { OnKeyDownEnd(e); } else if (e.KeyCode == Keys.Back) { OnKeyDownBack(e); } else if (e.KeyCode == Keys.Delete) { OnKeyDownDelete(e); } //else if (e.KeyCode == Keys.C && e.Control) //{ // OnUserCopyCommand(); //} //else if (e.KeyCode == Keys.V && e.Control) //{ // OnUserPasteCommand(); //} //else if (e.KeyCode == Keys.X && e.Control) //{ // OnUserCutCommand(); //} else { // Only if the key pressed wasn't handled by this TextBox, // notify the listeners by raising KeyDown event. // // If we can handle the event by ourselves // (e.g. user pressed the "left" button and the cursor // can be moved to the left, just move the cursor, // no need to inform the listeners. RaiseKeyDown(e); } RaiseAfterKeyDown(e); } protected virtual void OnKeyDownLeft(KeyEventArgs e) { bool ShouldRaiseEvent = false; bool CaretChanged = true; if (CaretPosition > 0) { if (!e.Shift && !e.Alt && !e.Control) { KeyBrake.SetBrake(); } if (e.Shift) { CaretPosition = GoToLeft(e.Control); } else { if (!HasSelection) { CaretPosition = GoToLeft(e.Control); } else { CaretPosition = SelectionStart; } ResetSelection(); } } else { if (HasSelection && !e.Shift) { ResetSelection(); } else { ShouldRaiseEvent = true; CaretChanged = false; } if (e.Shift || KeyBrake.QueryAndDecreaseCounter()) { ShouldRaiseEvent = false; } } if (CaretChanged) { this.AfterCaretChanged(); } if (ShouldRaiseEvent) { RaiseKeyDown(e); } } protected virtual void OnKeyDownRight(KeyEventArgs e) { bool ShouldRaiseEvent = false; bool CaretChanged = true; if (CaretPosition < TextLength) { if (!e.Shift && !e.Alt && !e.Control) { KeyBrake.SetBrake(); } if (e.Shift) { CaretPosition = GoToRight(e.Control); } else { if (!HasSelection) { CaretPosition = GoToRight(e.Control); } else { CaretPosition = SelectionEnd; } ResetSelection(); } } else { if (HasSelection && !e.Shift) { ResetSelection(); } else { ShouldRaiseEvent = true; CaretChanged = false; } if (e.Shift || KeyBrake.QueryAndDecreaseCounter()) { ShouldRaiseEvent = false; } } if (CaretChanged) { this.AfterCaretChanged(); } if (ShouldRaiseEvent) { RaiseKeyDown(e); } } protected virtual void OnKeyDownDown(KeyEventArgs e) { if (CaretPosition == 0 && TextLength > 0 && e.Shift) { SelectionStartPos = TextLength; AfterCaretChanged(); } else { RaiseKeyDown(e); } } protected virtual void OnKeyDownHome(KeyEventArgs e) { bool ShouldRaiseEvent = false; bool CaretChanged = true; if (CaretPosition > 0) { CaretPosition = 0; if (!e.Shift) { ResetSelection(); } } else { if (HasSelection && !e.Shift) { CaretPosition = 0; ResetSelection(); } else { CaretChanged = false; ShouldRaiseEvent = true; } } if (CaretChanged) { this.AfterCaretChanged(); } if (ShouldRaiseEvent) { RaiseKeyDown(e); } } protected virtual void OnKeyDownEnd(KeyEventArgs e) { bool ShouldRaiseEvent = false; bool CaretChanged = true; if (CaretPosition < TextLength) { CaretPosition = TextLength; if (!e.Shift) { ResetSelection(); } } else { if (HasSelection && !e.Shift) { CaretPosition = TextLength; ResetSelection(); } else { CaretChanged = false; ShouldRaiseEvent = true; } } if (CaretChanged) { this.AfterCaretChanged(); } if (ShouldRaiseEvent) { RaiseKeyDown(e); } } protected virtual void OnKeyDownBack(KeyEventArgs e) { if (e.Handled) { return; } using (RedrawAccumulator a = new RedrawAccumulator(this.Root, false)) { if (HasSelection) { DeleteSelection(); a.ShouldRedrawAtTheEnd = true; e.Handled = true; } else if (!CaretIsAtBeginning) { this.CaretPosition = GoToLeft(e.Control); DeleteSelection(); a.ShouldRedrawAtTheEnd = true; e.Handled = true; } if (!e.Handled) { RaiseKeyDown(e); if (e.Handled) { a.ShouldRedrawAtTheEnd = true; } } } } protected virtual void OnKeyDownDelete(KeyEventArgs e) { if (e.Handled) { return; } using (RedrawAccumulator a = new RedrawAccumulator(this.Root, false)) { if (!e.Shift && !e.Alt) { if (HasSelection) { DeleteSelection(); a.ShouldRedrawAtTheEnd = true; e.Handled = true; } else if (!CaretIsAtEnd) { this.CaretPosition = GoToRight(e.Control); DeleteSelection(); a.ShouldRedrawAtTheEnd = true; e.Handled = true; } } if (!e.Handled) { RaiseKeyDown(e); if (e.Handled) { a.ShouldRedrawAtTheEnd = true; } } } } public override void OnKeyPress(KeyPressEventArgs e) { RaisePreviewKeyPress(e); if (e.Handled) { return; } using (RedrawAccumulator a = new RedrawAccumulator(this.Root, false)) { if (IsCharAcceptable(e.KeyChar) && !char.IsControl(e.KeyChar)) { InsertText(e.KeyChar.ToString()); a.ShouldRedrawAtTheEnd = true; } RaiseKeyPress(e); if (e.Handled) { a.ShouldRedrawAtTheEnd = true; } } } public override void OnKeyUp(KeyEventArgs e) { RaiseKeyUp(e); KeyBrake.ReleaseBrake(); } } }
/* * * 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.IO; using System.Collections; using Lucene.Net.Analysis.Standard; using Lucene.Net.Support; using Version = Lucene.Net.Util.Version; namespace Lucene.Net.Analysis.Nl { /* * {@link Analyzer} for Dutch language. * <p> * Supports an external list of stopwords (words that * will not be indexed at all), an external list of exclusions (word that will * not be stemmed, but indexed) and an external list of word-stem pairs that overrule * the algorithm (dictionary stemming). * A default set of stopwords is used unless an alternative list is specified, but the * exclusion list is empty by default. * </p> * * <p><b>NOTE</b>: This class uses the same {@link Version} * dependent settings as {@link StandardAnalyzer}.</p> */ public class DutchAnalyzer : Analyzer { /* * List of typical Dutch stopwords. * @deprecated use {@link #getDefaultStopSet()} instead */ public static readonly String[] DUTCH_STOP_WORDS = { "de", "en", "van", "ik", "te", "dat", "die", "in", "een", "hij", "het", "niet", "zijn", "is", "was", "op", "aan", "met", "als", "voor", "had", "er", "maar", "om", "hem", "dan", "zou", "of", "wat", "mijn", "men", "dit", "zo", "door", "over", "ze", "zich", "bij", "ook", "tot", "je", "mij", "uit", "der", "daar", "haar", "naar", "heb", "hoe", "heeft", "hebben", "deze", "u", "want", "nog", "zal", "me", "zij", "nu", "ge", "geen", "omdat", "iets", "worden", "toch", "al", "waren", "veel", "meer", "doen", "toen", "moet", "ben", "zonder", "kan", "hun", "dus", "alles", "onder", "ja", "eens", "hier", "wie", "werd", "altijd", "doch", "wordt", "wezen", "kunnen", "ons", "zelf", "tegen", "na", "reeds", "wil", "kon", "niets", "uw", "iemand", "geweest", "andere" }; /* * Returns an unmodifiable instance of the default stop-words set. * @return an unmodifiable instance of the default stop-words set. */ public static ISet<string> getDefaultStopSet() { return DefaultSetHolder.DEFAULT_STOP_SET; } static class DefaultSetHolder { internal static readonly ISet<string> DEFAULT_STOP_SET = CharArraySet .UnmodifiableSet(new CharArraySet((IEnumerable<string>)DUTCH_STOP_WORDS, false)); } /* * Contains the stopwords used with the StopFilter. */ private readonly ISet<string> stoptable; /* * Contains words that should be indexed but not stemmed. */ private ISet<string> excltable = Support.Compatibility.SetFactory.CreateHashSet<string>(); private IDictionary<String, String> stemdict = new HashMap<String, String>(); private readonly Version matchVersion; /* * Builds an analyzer with the default stop words ({@link #DUTCH_STOP_WORDS}) * and a few default entries for the stem exclusion table. * */ public DutchAnalyzer(Version matchVersion) : this(matchVersion, DefaultSetHolder.DEFAULT_STOP_SET) { stemdict.Add("fiets", "fiets"); //otherwise fiet stemdict.Add("bromfiets", "bromfiets"); //otherwise bromfiet stemdict.Add("ei", "eier"); stemdict.Add("kind", "kinder"); } public DutchAnalyzer(Version matchVersion, ISet<string> stopwords) : this(matchVersion, stopwords, CharArraySet.EMPTY_SET) { } public DutchAnalyzer(Version matchVersion, ISet<string> stopwords, ISet<string> stemExclusionTable) { stoptable = CharArraySet.UnmodifiableSet(CharArraySet.Copy(stopwords)); excltable = CharArraySet.UnmodifiableSet(CharArraySet.Copy(stemExclusionTable)); this.matchVersion = matchVersion; SetOverridesTokenStreamMethod<DutchAnalyzer>(); } /* * Builds an analyzer with the given stop words. * * @param matchVersion * @param stopwords * @deprecated use {@link #DutchAnalyzer(Version, Set)} instead */ public DutchAnalyzer(Version matchVersion, params string[] stopwords) : this(matchVersion, StopFilter.MakeStopSet(stopwords)) { } /* * Builds an analyzer with the given stop words. * * @param stopwords * @deprecated use {@link #DutchAnalyzer(Version, Set)} instead */ public DutchAnalyzer(Version matchVersion, HashSet<string> stopwords) : this(matchVersion, (ISet<string>)stopwords) { } /* * Builds an analyzer with the given stop words. * * @param stopwords * @deprecated use {@link #DutchAnalyzer(Version, Set)} instead */ public DutchAnalyzer(Version matchVersion, FileInfo stopwords) { // this is completely broken! SetOverridesTokenStreamMethod<DutchAnalyzer>(); try { stoptable = WordlistLoader.GetWordSet(stopwords); } catch (IOException e) { // TODO: throw IOException throw new Exception("", e); } this.matchVersion = matchVersion; } /* * Builds an exclusionlist from an array of Strings. * * @param exclusionlist * @deprecated use {@link #DutchAnalyzer(Version, Set, Set)} instead */ public void SetStemExclusionTable(params string[] exclusionlist) { excltable = StopFilter.MakeStopSet(exclusionlist); PreviousTokenStream = null; // force a new stemmer to be created } /* * Builds an exclusionlist from a Hashtable. * @deprecated use {@link #DutchAnalyzer(Version, Set, Set)} instead */ public void SetStemExclusionTable(ISet<string> exclusionlist) { excltable = exclusionlist; PreviousTokenStream = null; // force a new stemmer to be created } /* * Builds an exclusionlist from the words contained in the given file. * @deprecated use {@link #DutchAnalyzer(Version, Set, Set)} instead */ public void SetStemExclusionTable(FileInfo exclusionlist) { try { excltable = WordlistLoader.GetWordSet(exclusionlist); PreviousTokenStream = null; // force a new stemmer to be created } catch (IOException e) { // TODO: throw IOException throw new Exception("", e); } } /* * Reads a stemdictionary file , that overrules the stemming algorithm * This is a textfile that contains per line * <tt>word<b>\t</b>stem</tt>, i.e: two tab seperated words */ public void SetStemDictionary(FileInfo stemdictFile) { try { stemdict = WordlistLoader.GetStemDict(stemdictFile); PreviousTokenStream = null; // force a new stemmer to be created } catch (IOException e) { // TODO: throw IOException throw new Exception(string.Empty, e); } } /* * Creates a {@link TokenStream} which tokenizes all the text in the * provided {@link Reader}. * * @return A {@link TokenStream} built from a {@link StandardTokenizer} * filtered with {@link StandardFilter}, {@link StopFilter}, * and {@link DutchStemFilter} */ public override TokenStream TokenStream(String fieldName, TextReader reader) { TokenStream result = new StandardTokenizer(matchVersion, reader); result = new StandardFilter(result); result = new StopFilter(StopFilter.GetEnablePositionIncrementsVersionDefault(matchVersion), result, stoptable); result = new DutchStemFilter(result, excltable, stemdict); return result; } class SavedStreams { protected internal Tokenizer source; protected internal TokenStream result; }; /* * Returns a (possibly reused) {@link TokenStream} which tokenizes all the * text in the provided {@link Reader}. * * @return A {@link TokenStream} built from a {@link StandardTokenizer} * filtered with {@link StandardFilter}, {@link StopFilter}, * and {@link DutchStemFilter} */ public override TokenStream ReusableTokenStream(String fieldName, TextReader reader) { if (overridesTokenStreamMethod) { // LUCENE-1678: force fallback to tokenStream() if we // have been subclassed and that subclass overrides // tokenStream but not reusableTokenStream return TokenStream(fieldName, reader); } SavedStreams streams = (SavedStreams)PreviousTokenStream; if (streams == null) { streams = new SavedStreams(); streams.source = new StandardTokenizer(matchVersion, reader); streams.result = new StandardFilter(streams.source); streams.result = new StopFilter(StopFilter.GetEnablePositionIncrementsVersionDefault(matchVersion), streams.result, stoptable); streams.result = new DutchStemFilter(streams.result, excltable, stemdict); PreviousTokenStream = streams; } else { streams.source.Reset(reader); } return streams.result; } } }
// 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 TestZInt16() { var test = new BooleanBinaryOpTest__TestZInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.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 (Avx.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 (Avx.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 (Avx.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 (Avx.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 (Avx.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 (Avx.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 (Avx.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 BooleanBinaryOpTest__TestZInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, 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 Dispose() { inHandle1.Free(); inHandle2.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Int16> _fld1; public Vector256<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); return testStruct; } public void RunStructFldScenario(BooleanBinaryOpTest__TestZInt16 testClass) { var result = Avx.TestZ(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } public void RunStructFldScenario_Load(BooleanBinaryOpTest__TestZInt16 testClass) { fixed (Vector256<Int16>* pFld1 = &_fld1) fixed (Vector256<Int16>* pFld2 = &_fld2) { var result = Avx.TestZ( Avx.LoadVector256((Int16*)(pFld1)), Avx.LoadVector256((Int16*)(pFld2)) ); testClass.ValidateResult(_fld1, _fld2, result); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector256<Int16> _clsVar1; private static Vector256<Int16> _clsVar2; private Vector256<Int16> _fld1; private Vector256<Int16> _fld2; private DataTable _dataTable; static BooleanBinaryOpTest__TestZInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); } public BooleanBinaryOpTest__TestZInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx.TestZ( Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx.TestZ( Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx.TestZ( Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx).GetMethod(nameof(Avx.TestZ), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx).GetMethod(nameof(Avx.TestZ), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }) .Invoke(null, new object[] { Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx).GetMethod(nameof(Avx.TestZ), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx.TestZ( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<Int16>* pClsVar1 = &_clsVar1) fixed (Vector256<Int16>* pClsVar2 = &_clsVar2) { var result = Avx.TestZ( Avx.LoadVector256((Int16*)(pClsVar1)), Avx.LoadVector256((Int16*)(pClsVar2)) ); ValidateResult(_clsVar1, _clsVar2, result); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr); var result = Avx.TestZ(op1, op2); ValidateResult(op1, op2, result); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)); var result = Avx.TestZ(op1, op2); ValidateResult(op1, op2, result); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)); var result = Avx.TestZ(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new BooleanBinaryOpTest__TestZInt16(); var result = Avx.TestZ(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new BooleanBinaryOpTest__TestZInt16(); fixed (Vector256<Int16>* pFld1 = &test._fld1) fixed (Vector256<Int16>* pFld2 = &test._fld2) { var result = Avx.TestZ( Avx.LoadVector256((Int16*)(pFld1)), Avx.LoadVector256((Int16*)(pFld2)) ); ValidateResult(test._fld1, test._fld2, result); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx.TestZ(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<Int16>* pFld1 = &_fld1) fixed (Vector256<Int16>* pFld2 = &_fld2) { var result = Avx.TestZ( Avx.LoadVector256((Int16*)(pFld1)), Avx.LoadVector256((Int16*)(pFld2)) ); ValidateResult(_fld1, _fld2, result); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx.TestZ(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Avx.TestZ( Avx.LoadVector256((Int16*)(&test._fld1)), Avx.LoadVector256((Int16*)(&test._fld2)) ); ValidateResult(test._fld1, test._fld2, result); } 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(Vector256<Int16> op1, Vector256<Int16> op2, bool result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Int16[] left, Int16[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; var expectedResult = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult &= ((left[i] & right[i]) == 0); } succeeded = (expectedResult == result); if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.TestZ)}<Int16>(Vector256<Int16>, Vector256<Int16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
#region PDFsharp - A .NET library for processing PDF // // Authors: // Stefan Lange // // Copyright (c) 2005-2016 empira Software GmbH, Cologne Area (Germany) // // http://www.pdfsharp.com // http://sourceforge.net/projects/pdfsharp // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Collections; using PdfSharp.Pdf.Content.Objects; using PdfSharp.Pdf.IO; namespace PdfSharp.Pdf.Advanced { /// <summary> /// Represents an array of PDF content streams of a page. /// </summary> public sealed class PdfContents : PdfArray { /// <summary> /// Initializes a new instance of the <see cref="PdfContents"/> class. /// </summary> /// <param name="document">The document.</param> public PdfContents(PdfDocument document) : base(document) { } internal PdfContents(PdfArray array) : base(array) { int count = Elements.Count; for (int idx = 0; idx < count; idx++) { // Convert the references from PdfDictionary to PdfContent PdfItem item = Elements[idx]; PdfReference iref = item as PdfReference; if (iref != null && iref.Value is PdfDictionary) { // The following line is correct! new PdfContent((PdfDictionary)iref.Value); } else throw new InvalidOperationException("Unexpected item in a content stream array."); } } /// <summary> /// Appends a new content stream and returns it. /// </summary> public PdfContent AppendContent() { Debug.Assert(Owner != null); SetModified(); PdfContent content = new PdfContent(Owner); Owner._irefTable.Add(content); Debug.Assert(content.Reference != null); Elements.Add(content.Reference); return content; } /// <summary> /// Prepends a new content stream and returns it. /// </summary> public PdfContent PrependContent() { Debug.Assert(Owner != null); SetModified(); PdfContent content = new PdfContent(Owner); Owner._irefTable.Add(content); Debug.Assert(content.Reference != null); Elements.Insert(0, content.Reference); return content; } /// <summary> /// Creates a single content stream with the bytes from the array of the content streams. /// This operation does not modify any of the content streams in this array. /// </summary> public PdfContent CreateSingleContent() { byte[] bytes = new byte[0]; byte[] bytes1; byte[] bytes2; foreach (PdfItem iref in Elements) { PdfDictionary cont = (PdfDictionary)((PdfReference)iref).Value; bytes1 = bytes; bytes2 = cont.Stream.UnfilteredValue; bytes = new byte[bytes1.Length + bytes2.Length + 1]; bytes1.CopyTo(bytes, 0); bytes[bytes1.Length] = (byte)'\n'; bytes2.CopyTo(bytes, bytes1.Length + 1); } PdfContent content = new PdfContent(Owner); content.Stream = new PdfDictionary.PdfStream(bytes, content); return content; } /// <summary> /// Replaces the current content of the page with the specified content sequence. /// </summary> public PdfContent ReplaceContent(CSequence cseq) { if (cseq == null) throw new ArgumentException("cseq"); return ReplaceContent(cseq.ToContent()); } /// <summary> /// Replaces the current content of the page with the specified bytes. /// </summary> PdfContent ReplaceContent(byte[] contentBytes) { Debug.Assert(Owner != null); PdfContent content = new PdfContent(Owner); content.CreateStream(contentBytes); Owner._irefTable.Add(content); Elements.Clear(); Elements.Add(content.Reference); return content; } void SetModified() { if (!_modified) { _modified = true; int count = Elements.Count; if (count == 1) { PdfContent content = (PdfContent)((PdfReference)Elements[0]).Value; content.PreserveGraphicsState(); } else if (count > 1) { // Surround content streams with q/Q operations byte[] value; int length; PdfContent content = (PdfContent)((PdfReference)Elements[0]).Value; if (content != null && content.Stream != null) { length = content.Stream.Length; value = new byte[length + 2]; value[0] = (byte)'q'; value[1] = (byte)'\n'; Array.Copy(content.Stream.Value, 0, value, 2, length); content.Stream.Value = value; content.Elements.SetInteger("/Length", length + 2); } content = (PdfContent)((PdfReference)Elements[count - 1]).Value; if (content != null && content.Stream != null) { length = content.Stream.Length; value = new byte[length + 3]; Array.Copy(content.Stream.Value, 0, value, 0, length); value[length] = (byte)' '; value[length + 1] = (byte)'Q'; value[length + 2] = (byte)'\n'; content.Stream.Value = value; content.Elements.SetInteger("/Length", length + 3); } } } } bool _modified; internal override void WriteObject(PdfWriter writer) { // Save two bytes in PDF stream... if (Elements.Count == 1) Elements[0].WriteObject(writer); else base.WriteObject(writer); } /// <summary> /// Gets the enumerator. /// </summary> public new IEnumerator<PdfContent> GetEnumerator() { return new PdfPageContentEnumerator(this); } class PdfPageContentEnumerator : IEnumerator<PdfContent> { internal PdfPageContentEnumerator(PdfContents list) { _contents = list; _index = -1; } public bool MoveNext() { if (_index < _contents.Elements.Count - 1) { _index++; _currentElement = (PdfContent)((PdfReference)_contents.Elements[_index]).Value; return true; } _index = _contents.Elements.Count; return false; } public void Reset() { _currentElement = null; _index = -1; } object IEnumerator.Current { get { return Current; } } public PdfContent Current { get { if (_index == -1 || _index >= _contents.Elements.Count) throw new InvalidOperationException(PSSR.ListEnumCurrentOutOfRange); return _currentElement; } } public void Dispose() { // Nothing to do. } PdfContent _currentElement; int _index; readonly PdfContents _contents; } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * [email protected]. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using EnvDTE; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using VSConstants = Microsoft.VisualStudio.VSConstants; namespace Microsoft.VisualStudioTools.Project.Automation { /// <summary> /// Represents an automation object for a file in a project /// </summary> [SuppressMessage("Microsoft.Interoperability", "CA1405:ComVisibleTypeBaseTypesShouldBeComVisible")] [ComVisible(true)] public class OAFileItem : OAProjectItem { #region ctors internal OAFileItem(OAProject project, FileNode node) : base(project, node) { } #endregion private new FileNode Node { get { return (FileNode)base.Node; } } public override string Name { get { return this.Node.FileName; } set { UIThread.Instance.RunSync(() => base.Name = value); } } #region overridden methods /// <summary> /// Returns the dirty state of the document. /// </summary> /// <exception cref="InvalidOperationException">Is thrown if the project is closed or it the service provider attached to the project is invalid.</exception> /// <exception cref="ComException">Is thrown if the dirty state cannot be retrived.</exception> public override bool IsDirty { get { CheckProjectIsValid(); bool isDirty = false; using (AutomationScope scope = new AutomationScope(this.Node.ProjectMgr.Site)) { UIThread.Instance.RunSync(() => { DocumentManager manager = this.Node.GetDocumentManager(); Utilities.CheckNotNull(manager); bool isOpen, isOpenedByUs; uint docCookie; IVsPersistDocData persistDocData; manager.GetDocInfo(out isOpen, out isDirty, out isOpenedByUs, out docCookie, out persistDocData); }); } return isDirty; } } /// <summary> /// Gets the Document associated with the item, if one exists. /// </summary> public override EnvDTE.Document Document { get { CheckProjectIsValid(); EnvDTE.Document document = null; using (AutomationScope scope = new AutomationScope(this.Node.ProjectMgr.Site)) { UIThread.Instance.RunSync(() => { IVsUIHierarchy hier; uint itemid; IVsWindowFrame windowFrame; VsShellUtilities.IsDocumentOpen(this.Node.ProjectMgr.Site, this.Node.Url, VSConstants.LOGVIEWID_Any, out hier, out itemid, out windowFrame); if (windowFrame != null) { object var; ErrorHandler.ThrowOnFailure(windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocCookie, out var)); object documentAsObject; ErrorHandler.ThrowOnFailure(scope.Extensibility.GetDocumentFromDocCookie((int)var, out documentAsObject)); Utilities.CheckNotNull(documentAsObject); document = (Document)documentAsObject; } }); } return document; } } /// <summary> /// Opens the file item in the specified view. /// </summary> /// <param name="ViewKind">Specifies the view kind in which to open the item (file)</param> /// <returns>Window object</returns> public override EnvDTE.Window Open(string viewKind) { CheckProjectIsValid(); IVsWindowFrame windowFrame = null; IntPtr docData = IntPtr.Zero; using (AutomationScope scope = new AutomationScope(this.Node.ProjectMgr.Site)) { UIThread.Instance.RunSync(() => { try { // Validate input params Guid logicalViewGuid = VSConstants.LOGVIEWID_Primary; try { if (!(String.IsNullOrEmpty(viewKind))) { logicalViewGuid = new Guid(viewKind); } } catch (FormatException) { // Not a valid guid throw new ArgumentException(SR.GetString(SR.ParameterMustBeAValidGuid, CultureInfo.CurrentUICulture), "viewKind"); } uint itemid; IVsHierarchy ivsHierarchy; uint docCookie; IVsRunningDocumentTable rdt = this.Node.ProjectMgr.Site.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; if (rdt == null) { throw new InvalidOperationException("Could not get running document table from the services exposed by this project"); } ErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, this.Node.Url, out ivsHierarchy, out itemid, out docData, out docCookie)); // Open the file using the IVsProject interface // We get the outer hierarchy so that projects can customize opening. var project = Node.ProjectMgr.GetOuterInterface<IVsProject>(); ErrorHandler.ThrowOnFailure(project.OpenItem(Node.ID, ref logicalViewGuid, docData, out windowFrame)); } finally { if (docData != IntPtr.Zero) { Marshal.Release(docData); } } }); } // Get the automation object and return it return ((windowFrame != null) ? VsShellUtilities.GetWindowObject(windowFrame) : null); } /// <summary> /// Saves the project item. /// </summary> /// <param name="fileName">The name with which to save the project or project item.</param> /// <exception cref="InvalidOperationException">Is thrown if the save operation failes.</exception> /// <exception cref="ArgumentNullException">Is thrown if fileName is null.</exception> public override void Save(string fileName) { UIThread.Instance.RunSync(() => { this.DoSave(false, fileName); }); } /// <summary> /// Saves the project item. /// </summary> /// <param name="fileName">The file name with which to save the solution, project, or project item. If the file exists, it is overwritten</param> /// <returns>true if the rename was successful. False if Save as failes</returns> public override bool SaveAs(string fileName) { try { UIThread.Instance.RunSync(() => { this.DoSave(true, fileName); }); } catch (InvalidOperationException) { return false; } catch (COMException) { return false; } return true; } /// <summary> /// Gets a value indicating whether the project item is open in a particular view type. /// </summary> /// <param name="viewKind">A Constants.vsViewKind* indicating the type of view to check./param> /// <returns>A Boolean value indicating true if the project is open in the given view type; false if not. </returns> public override bool get_IsOpen(string viewKind) { CheckProjectIsValid(); // Validate input params Guid logicalViewGuid = VSConstants.LOGVIEWID_Primary; try { if (!(String.IsNullOrEmpty(viewKind))) { logicalViewGuid = new Guid(viewKind); } } catch (FormatException) { // Not a valid guid throw new ArgumentException(SR.GetString(SR.ParameterMustBeAValidGuid, CultureInfo.CurrentUICulture), "viewKind"); } bool isOpen = false; using (AutomationScope scope = new AutomationScope(this.Node.ProjectMgr.Site)) { UIThread.Instance.RunSync(() => { IVsUIHierarchy hier; uint itemid; IVsWindowFrame windowFrame; isOpen = VsShellUtilities.IsDocumentOpen(this.Node.ProjectMgr.Site, this.Node.Url, logicalViewGuid, out hier, out itemid, out windowFrame); }); } return isOpen; } /// <summary> /// Gets the ProjectItems for the object. /// </summary> public override ProjectItems ProjectItems { get { return UIThread.Instance.RunSync<ProjectItems>(() => { if (this.Project.ProjectNode.CanFileNodesHaveChilds) return new OAProjectItems(this.Project, this.Node); else return base.ProjectItems; }); } } #endregion #region helpers /// <summary> /// Saves or Save As the file /// </summary> /// <param name="isCalledFromSaveAs">Flag determining which Save method called , the SaveAs or the Save.</param> /// <param name="fileName">The name of the project file.</param> private void DoSave(bool isCalledFromSaveAs, string fileName) { Utilities.ArgumentNotNull("fileName", fileName); CheckProjectIsValid(); using (AutomationScope scope = new AutomationScope(this.Node.ProjectMgr.Site)) { UIThread.Instance.RunSync(() => { IntPtr docData = IntPtr.Zero; try { IVsRunningDocumentTable rdt = this.Node.ProjectMgr.Site.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; if (rdt == null) { throw new InvalidOperationException("Could not get running document table from the services exposed by this project"); } // First we see if someone else has opened the requested view of the file. uint itemid; IVsHierarchy ivsHierarchy; uint docCookie; int canceled; string url = this.Node.Url; ErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, url, out ivsHierarchy, out itemid, out docData, out docCookie)); // If an empty file name is passed in for Save then make the file name the project name. if (!isCalledFromSaveAs && fileName.Length == 0) { ErrorHandler.ThrowOnFailure(this.Node.ProjectMgr.SaveItem(VSSAVEFLAGS.VSSAVE_SilentSave, url, this.Node.ID, docData, out canceled)); } else { Utilities.ValidateFileName(this.Node.ProjectMgr.Site, fileName); // Compute the fullpath from the directory of the existing Url. string fullPath = CommonUtils.GetAbsoluteFilePath(Path.GetDirectoryName(url), fileName); if (!isCalledFromSaveAs) { if (!CommonUtils.IsSamePath(this.Node.Url, fullPath)) { throw new InvalidOperationException(); } ErrorHandler.ThrowOnFailure(this.Node.ProjectMgr.SaveItem(VSSAVEFLAGS.VSSAVE_SilentSave, fullPath, this.Node.ID, docData, out canceled)); } else { ErrorHandler.ThrowOnFailure(this.Node.ProjectMgr.SaveItem(VSSAVEFLAGS.VSSAVE_SilentSave, fullPath, this.Node.ID, docData, out canceled)); } } if (canceled == 1) { throw new InvalidOperationException(); } } catch (COMException e) { throw new InvalidOperationException(e.Message); } finally { if (docData != IntPtr.Zero) { Marshal.Release(docData); } } }); } } #endregion } }
/* * [The "BSD license"] * Copyright (c) 2013 Terence Parr * Copyright (c) 2013 Sam Harwell * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 Antlr4.Runtime; using Antlr4.Runtime.Atn; using Antlr4.Runtime.Dfa; using Antlr4.Runtime.Misc; using Antlr4.Runtime.Sharpen; namespace Antlr4.Runtime.Atn { /// <summary>"dup" of ParserInterpreter</summary> public class LexerATNSimulator : ATNSimulator { #if !PORTABLE public const bool debug = false; public const bool dfa_debug = false; #endif public const int MinDfaEdge = 0; public const int MaxDfaEdge = 127; public bool optimize_tail_calls = true; /// <summary> /// When we hit an accept state in either the DFA or the ATN, we /// have to notify the character stream to start buffering characters /// via /// <see cref="Antlr4.Runtime.IIntStream.Mark()"/> /// and record the current state. The current sim state /// includes the current index into the input, the current line, /// and current character position in that line. Note that the Lexer is /// tracking the starting line and characterization of the token. These /// variables track the "state" of the simulator when it hits an accept state. /// <p>We track these variables separately for the DFA and ATN simulation /// because the DFA simulation often has to fail over to the ATN /// simulation. If the ATN simulation fails, we need the DFA to fall /// back to its previously accepted state, if any. If the ATN succeeds, /// then the ATN does the accept and the DFA simulator that invoked it /// can simply return the predicted token type.</p> /// </summary> protected internal class SimState { protected internal int index = -1; protected internal int line = 0; protected internal int charPos = -1; protected internal DFAState dfaState; // forces unicode to stay in ATN protected internal virtual void Reset() { index = -1; line = 0; charPos = -1; dfaState = null; } } [Nullable] protected internal readonly Lexer recog; /// <summary>The current token's starting index into the character stream.</summary> /// <remarks> /// The current token's starting index into the character stream. /// Shared across DFA to ATN simulation in case the ATN fails and the /// DFA did not have a previous accept state. In this case, we use the /// ATN-generated exception object. /// </remarks> protected internal int startIndex = -1; /// <summary>line number 1..n within the input</summary> private int _line = 1; /// <summary>The index of the character relative to the beginning of the line 0..n-1</summary> protected internal int charPositionInLine = 0; protected internal int mode = Lexer.DefaultMode; /// <summary>Used during DFA/ATN exec to record the most recent accept configuration info</summary> [NotNull] protected internal readonly LexerATNSimulator.SimState prevAccept = new LexerATNSimulator.SimState(); public static int match_calls = 0; public LexerATNSimulator(ATN atn) : this(null, atn) { } public LexerATNSimulator(Lexer recog, ATN atn) : base(atn) { this.recog = recog; } public virtual void CopyState(LexerATNSimulator simulator) { this.charPositionInLine = simulator.charPositionInLine; this._line = simulator._line; this.mode = simulator.mode; this.startIndex = simulator.startIndex; } public virtual int Match(ICharStream input, int mode) { match_calls++; this.mode = mode; int mark = input.Mark(); try { this.startIndex = input.Index; this.prevAccept.Reset(); DFAState s0 = atn.modeToDFA[mode].s0.Get(); if (s0 == null) { return MatchATN(input); } else { return ExecATN(input, s0); } } finally { input.Release(mark); } } public override void Reset() { prevAccept.Reset(); startIndex = -1; _line = 1; charPositionInLine = 0; mode = Lexer.DefaultMode; } protected internal virtual int MatchATN(ICharStream input) { ATNState startState = atn.modeToStartState[mode]; ATNConfigSet s0_closure = ComputeStartState(input, startState); bool suppressEdge = s0_closure.HasSemanticContext; if (suppressEdge) { s0_closure.ClearExplicitSemanticContext(); } DFAState next = AddDFAState(s0_closure); if (!suppressEdge) { if (!atn.modeToDFA[mode].s0.CompareAndSet(null, next)) { next = atn.modeToDFA[mode].s0.Get(); } } int predict = ExecATN(input, next); return predict; } protected internal virtual int ExecATN(ICharStream input, DFAState ds0) { //System.out.println("enter exec index "+input.index()+" from "+ds0.configs); if (ds0.IsAcceptState) { // allow zero-length tokens CaptureSimState(prevAccept, input, ds0); } int t = input.La(1); DFAState s = ds0; // s is current/from DFA state while (true) { // while more work // As we move src->trg, src->trg, we keep track of the previous trg to // avoid looking up the DFA state again, which is expensive. // If the previous target was already part of the DFA, we might // be able to avoid doing a reach operation upon t. If s!=null, // it means that semantic predicates didn't prevent us from // creating a DFA state. Once we know s!=null, we check to see if // the DFA state has an edge already for t. If so, we can just reuse // it's configuration set; there's no point in re-computing it. // This is kind of like doing DFA simulation within the ATN // simulation because DFA simulation is really just a way to avoid // computing reach/closure sets. Technically, once we know that // we have a previously added DFA state, we could jump over to // the DFA simulator. But, that would mean popping back and forth // a lot and making things more complicated algorithmically. // This optimization makes a lot of sense for loops within DFA. // A character will take us back to an existing DFA state // that already has lots of edges out of it. e.g., .* in comments. DFAState target = GetExistingTargetState(s, t); if (target == null) { target = ComputeTargetState(input, s, t); } if (target == Error) { break; } // If this is a consumable input element, make sure to consume before // capturing the accept state so the input index, line, and char // position accurately reflect the state of the interpreter at the // end of the token. if (t != IntStreamConstants.Eof) { Consume(input); } if (target.IsAcceptState) { CaptureSimState(prevAccept, input, target); if (t == IntStreamConstants.Eof) { break; } } t = input.La(1); s = target; } // flip; current DFA target becomes new src/from state return FailOrAccept(prevAccept, input, s.configs, t); } /// <summary>Get an existing target state for an edge in the DFA.</summary> /// <remarks> /// Get an existing target state for an edge in the DFA. If the target state /// for the edge has not yet been computed or is otherwise not available, /// this method returns /// <see langword="null"/> /// . /// </remarks> /// <param name="s">The current DFA state</param> /// <param name="t">The next input symbol</param> /// <returns> /// The existing target DFA state for the given input symbol /// <paramref name="t"/> /// , or /// <see langword="null"/> /// if the target state for this edge is not /// already cached /// </returns> [return: Nullable] protected internal virtual DFAState GetExistingTargetState(DFAState s, int t) { DFAState target = s.GetTarget(t); #if !PORTABLE #pragma warning disable 162, 429 if (debug && target != null) { System.Console.Out.WriteLine("reuse state " + s.stateNumber + " edge to " + target.stateNumber); } #pragma warning restore 162, 429 #endif return target; } /// <summary> /// Compute a target state for an edge in the DFA, and attempt to add the /// computed state and corresponding edge to the DFA. /// </summary> /// <remarks> /// Compute a target state for an edge in the DFA, and attempt to add the /// computed state and corresponding edge to the DFA. /// </remarks> /// <param name="input">The input stream</param> /// <param name="s">The current DFA state</param> /// <param name="t">The next input symbol</param> /// <returns> /// The computed target DFA state for the given input symbol /// <paramref name="t"/> /// . If /// <paramref name="t"/> /// does not lead to a valid DFA state, this method /// returns /// <see cref="ATNSimulator.Error"/> /// . /// </returns> [return: NotNull] protected internal virtual DFAState ComputeTargetState(ICharStream input, DFAState s, int t) { ATNConfigSet reach = new OrderedATNConfigSet(); // if we don't find an existing DFA state // Fill reach starting from closure, following t transitions GetReachableConfigSet(input, s.configs, reach, t); if (reach.IsEmpty()) { // we got nowhere on t from s if (!reach.HasSemanticContext) { // we got nowhere on t, don't throw out this knowledge; it'd // cause a failover from DFA later. AddDFAEdge(s, t, Error); } // stop when we can't match any more char return Error; } // Add an edge from s to target DFA found/created for reach return AddDFAEdge(s, t, reach); } protected internal virtual int FailOrAccept(LexerATNSimulator.SimState prevAccept, ICharStream input, ATNConfigSet reach, int t) { if (prevAccept.dfaState != null) { LexerActionExecutor lexerActionExecutor = prevAccept.dfaState.LexerActionExecutor; Accept(input, lexerActionExecutor, startIndex, prevAccept.index, prevAccept.line, prevAccept.charPos); return prevAccept.dfaState.Prediction; } else { // if no accept and EOF is first char, return EOF if (t == IntStreamConstants.Eof && input.Index == startIndex) { return TokenConstants.Eof; } throw new LexerNoViableAltException(recog, input, startIndex, reach); } } /// <summary> /// Given a starting configuration set, figure out all ATN configurations /// we can reach upon input /// <paramref name="t"/> /// . Parameter /// <paramref name="reach"/> /// is a return /// parameter. /// </summary> protected internal virtual void GetReachableConfigSet(ICharStream input, ATNConfigSet closure, ATNConfigSet reach, int t) { // this is used to skip processing for configs which have a lower priority // than a config that already reached an accept state for the same rule int skipAlt = ATN.InvalidAltNumber; foreach (ATNConfig c in closure) { bool currentAltReachedAcceptState = c.Alt == skipAlt; if (currentAltReachedAcceptState && c.PassedThroughNonGreedyDecision) { continue; } int n = c.State.NumberOfOptimizedTransitions; for (int ti = 0; ti < n; ti++) { // for each optimized transition Transition trans = c.State.GetOptimizedTransition(ti); ATNState target = GetReachableTarget(trans, t); if (target != null) { LexerActionExecutor lexerActionExecutor = c.ActionExecutor; if (lexerActionExecutor != null) { lexerActionExecutor = lexerActionExecutor.FixOffsetBeforeMatch(input.Index - startIndex); } bool treatEofAsEpsilon = t == IntStreamConstants.Eof; if (Closure(input, c.Transform(target, lexerActionExecutor, true), reach, currentAltReachedAcceptState, true, treatEofAsEpsilon)) { // any remaining configs for this alt have a lower priority than // the one that just reached an accept state. skipAlt = c.Alt; break; } } } } } protected internal virtual void Accept(ICharStream input, LexerActionExecutor lexerActionExecutor, int startIndex, int index, int line, int charPos) { // seek to after last char in token input.Seek(index); this._line = line; this.charPositionInLine = charPos; if (lexerActionExecutor != null && recog != null) { lexerActionExecutor.Execute(recog, input, startIndex); } } [return: Nullable] protected internal virtual ATNState GetReachableTarget(Transition trans, int t) { if (trans.Matches(t, char.MinValue, char.MaxValue)) { return trans.target; } return null; } [return: NotNull] protected internal virtual ATNConfigSet ComputeStartState(ICharStream input, ATNState p) { PredictionContext initialContext = PredictionContext.EmptyFull; ATNConfigSet configs = new OrderedATNConfigSet(); for (int i = 0; i < p.NumberOfTransitions; i++) { ATNState target = p.Transition(i).target; ATNConfig c = ATNConfig.Create(target, i + 1, initialContext); Closure(input, c, configs, false, false, false); } return configs; } /// <summary> /// Since the alternatives within any lexer decision are ordered by /// preference, this method stops pursuing the closure as soon as an accept /// state is reached. /// </summary> /// <remarks> /// Since the alternatives within any lexer decision are ordered by /// preference, this method stops pursuing the closure as soon as an accept /// state is reached. After the first accept state is reached by depth-first /// search from /// <paramref name="config"/> /// , all other (potentially reachable) states for /// this rule would have a lower priority. /// </remarks> /// <returns> /// /// <see langword="true"/> /// if an accept state is reached, otherwise /// <see langword="false"/> /// . /// </returns> protected internal virtual bool Closure(ICharStream input, ATNConfig config, ATNConfigSet configs, bool currentAltReachedAcceptState, bool speculative, bool treatEofAsEpsilon) { if (config.State is RuleStopState) { PredictionContext context = config.Context; if (context.IsEmpty) { configs.Add(config); return true; } else { if (context.HasEmpty) { configs.Add(config.Transform(config.State, PredictionContext.EmptyFull, true)); currentAltReachedAcceptState = true; } } for (int i = 0; i < context.Size; i++) { int returnStateNumber = context.GetReturnState(i); if (returnStateNumber == PredictionContext.EmptyFullStateKey) { continue; } PredictionContext newContext = context.GetParent(i); // "pop" return state ATNState returnState = atn.states[returnStateNumber]; ATNConfig c = config.Transform(returnState, newContext, false); currentAltReachedAcceptState = Closure(input, c, configs, currentAltReachedAcceptState, speculative, treatEofAsEpsilon); } return currentAltReachedAcceptState; } // optimization if (!config.State.OnlyHasEpsilonTransitions) { if (!currentAltReachedAcceptState || !config.PassedThroughNonGreedyDecision) { configs.Add(config); } } ATNState p = config.State; for (int i_1 = 0; i_1 < p.NumberOfOptimizedTransitions; i_1++) { Transition t = p.GetOptimizedTransition(i_1); ATNConfig c = GetEpsilonTarget(input, config, t, configs, speculative, treatEofAsEpsilon); if (c != null) { currentAltReachedAcceptState = Closure(input, c, configs, currentAltReachedAcceptState, speculative, treatEofAsEpsilon); } } return currentAltReachedAcceptState; } // side-effect: can alter configs.hasSemanticContext [return: Nullable] protected internal virtual ATNConfig GetEpsilonTarget(ICharStream input, ATNConfig config, Transition t, ATNConfigSet configs, bool speculative, bool treatEofAsEpsilon) { ATNConfig c; switch (t.TransitionType) { case TransitionType.Rule: { RuleTransition ruleTransition = (RuleTransition)t; if (optimize_tail_calls && ruleTransition.optimizedTailCall && !config.Context.HasEmpty) { c = config.Transform(t.target, true); } else { PredictionContext newContext = config.Context.GetChild(ruleTransition.followState.stateNumber); c = config.Transform(t.target, newContext, true); } break; } case TransitionType.Precedence: { throw new NotSupportedException("Precedence predicates are not supported in lexers."); } case TransitionType.Predicate: { PredicateTransition pt = (PredicateTransition)t; configs.MarkExplicitSemanticContext(); if (EvaluatePredicate(input, pt.ruleIndex, pt.predIndex, speculative)) { c = config.Transform(t.target, true); } else { c = null; } break; } case TransitionType.Action: { if (config.Context.HasEmpty) { // execute actions anywhere in the start rule for a token. // // TODO: if the entry rule is invoked recursively, some // actions may be executed during the recursive call. The // problem can appear when hasEmpty() is true but // isEmpty() is false. In this case, the config needs to be // split into two contexts - one with just the empty path // and another with everything but the empty path. // Unfortunately, the current algorithm does not allow // getEpsilonTarget to return two configurations, so // additional modifications are needed before we can support // the split operation. LexerActionExecutor lexerActionExecutor = LexerActionExecutor.Append(config.ActionExecutor, atn.lexerActions[((ActionTransition)t).actionIndex]); c = config.Transform(t.target, lexerActionExecutor, true); break; } else { // ignore actions in referenced rules c = config.Transform(t.target, true); break; } } case TransitionType.Epsilon: { c = config.Transform(t.target, true); break; } case TransitionType.Atom: case TransitionType.Range: case TransitionType.Set: { if (treatEofAsEpsilon) { if (t.Matches(IntStreamConstants.Eof, char.MinValue, char.MaxValue)) { c = config.Transform(t.target, false); break; } } c = null; break; } default: { c = null; break; } } return c; } /// <summary>Evaluate a predicate specified in the lexer.</summary> /// <remarks> /// Evaluate a predicate specified in the lexer. /// <p>If /// <paramref name="speculative"/> /// is /// <see langword="true"/> /// , this method was called before /// <see cref="Consume(Antlr4.Runtime.ICharStream)"/> /// for the matched character. This method should call /// <see cref="Consume(Antlr4.Runtime.ICharStream)"/> /// before evaluating the predicate to ensure position /// sensitive values, including /// <see cref="Antlr4.Runtime.Lexer.Text()"/> /// , /// <see cref="Antlr4.Runtime.Lexer.Line()"/> /// , /// and /// <see cref="Antlr4.Runtime.Lexer.Column()"/> /// , properly reflect the current /// lexer state. This method should restore /// <paramref name="input"/> /// and the simulator /// to the original state before returning (i.e. undo the actions made by the /// call to /// <see cref="Consume(Antlr4.Runtime.ICharStream)"/> /// .</p> /// </remarks> /// <param name="input">The input stream.</param> /// <param name="ruleIndex">The rule containing the predicate.</param> /// <param name="predIndex">The index of the predicate within the rule.</param> /// <param name="speculative"> /// /// <see langword="true"/> /// if the current index in /// <paramref name="input"/> /// is /// one character before the predicate's location. /// </param> /// <returns> /// /// <see langword="true"/> /// if the specified predicate evaluates to /// <see langword="true"/> /// . /// </returns> protected internal virtual bool EvaluatePredicate(ICharStream input, int ruleIndex, int predIndex, bool speculative) { // assume true if no recognizer was provided if (recog == null) { return true; } if (!speculative) { return recog.Sempred(null, ruleIndex, predIndex); } int savedCharPositionInLine = charPositionInLine; int savedLine = _line; int index = input.Index; int marker = input.Mark(); try { Consume(input); return recog.Sempred(null, ruleIndex, predIndex); } finally { charPositionInLine = savedCharPositionInLine; _line = savedLine; input.Seek(index); input.Release(marker); } } protected internal virtual void CaptureSimState(LexerATNSimulator.SimState settings, ICharStream input, DFAState dfaState) { settings.index = input.Index; settings.line = _line; settings.charPos = charPositionInLine; settings.dfaState = dfaState; } [return: NotNull] protected internal virtual DFAState AddDFAEdge(DFAState from, int t, ATNConfigSet q) { bool suppressEdge = q.HasSemanticContext; if (suppressEdge) { q.ClearExplicitSemanticContext(); } DFAState to = AddDFAState(q); if (suppressEdge) { return to; } AddDFAEdge(from, t, to); return to; } protected internal virtual void AddDFAEdge(DFAState p, int t, DFAState q) { if (p != null) { p.SetTarget(t, q); } } /// <summary> /// Add a new DFA state if there isn't one with this set of /// configurations already. /// </summary> /// <remarks> /// Add a new DFA state if there isn't one with this set of /// configurations already. This method also detects the first /// configuration containing an ATN rule stop state. Later, when /// traversing the DFA, we will know which rule to accept. /// </remarks> [return: NotNull] protected internal virtual DFAState AddDFAState(ATNConfigSet configs) { System.Diagnostics.Debug.Assert(!configs.HasSemanticContext); DFAState proposed = new DFAState(atn.modeToDFA[mode], configs); DFAState existing; if (atn.modeToDFA[mode].states.TryGetValue(proposed, out existing)) { return existing; } configs.OptimizeConfigs(this); DFAState newState = new DFAState(atn.modeToDFA[mode], configs.Clone(true)); ATNConfig firstConfigWithRuleStopState = null; foreach (ATNConfig c in configs) { if (c.State is RuleStopState) { firstConfigWithRuleStopState = c; break; } } if (firstConfigWithRuleStopState != null) { int prediction = atn.ruleToTokenType[firstConfigWithRuleStopState.State.ruleIndex]; LexerActionExecutor lexerActionExecutor = firstConfigWithRuleStopState.ActionExecutor; newState.AcceptStateInfo = new AcceptStateInfo(prediction, lexerActionExecutor); } return atn.modeToDFA[mode].AddState(newState); } [return: NotNull] public DFA GetDFA(int mode) { return atn.modeToDFA[mode]; } /// <summary>Get the text matched so far for the current token.</summary> /// <remarks>Get the text matched so far for the current token.</remarks> [return: NotNull] public virtual string GetText(ICharStream input) { // index is first lookahead char, don't include. return input.GetText(Interval.Of(startIndex, input.Index - 1)); } public virtual int Line { get { return _line; } set { this._line = value; } } public virtual int Column { get { return charPositionInLine; } set { int charPositionInLine = value; this.charPositionInLine = charPositionInLine; } } public virtual void Consume(ICharStream input) { int curChar = input.La(1); if (curChar == '\n') { _line++; charPositionInLine = 0; } else { charPositionInLine++; } input.Consume(); } [return: NotNull] public virtual string GetTokenName(int t) { if (t == -1) { return "EOF"; } //if ( atn.g!=null ) return atn.g.getTokenDisplayName(t); return "'" + (char)t + "'"; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using UnityEngine; namespace InControl { public sealed class AutoDiscover : Attribute { } public class UnityInputDeviceProfile { public string Name { get; protected set; } public string Meta { get; protected set; } public InputControlMapping[] AnalogMappings { get; protected set; } public InputControlMapping[] ButtonMappings { get; protected set; } protected string[] SupportedPlatforms; protected string[] JoystickNames; protected string[] JoystickRegex; protected string LastResortRegex; public VersionInfo MinUnityVersion { get; protected set; } public VersionInfo MaxUnityVersion { get; protected set; } static HashSet<Type> hideList = new HashSet<Type>(); float sensitivity; float lowerDeadZone; float upperDeadZone; public UnityInputDeviceProfile() { Name = ""; Meta = ""; sensitivity = 1.0f; lowerDeadZone = 0.2f; upperDeadZone = 0.9f; AnalogMappings = new InputControlMapping[0]; ButtonMappings = new InputControlMapping[0]; MinUnityVersion = new VersionInfo( 3 ); MaxUnityVersion = new VersionInfo( 9 ); } public float Sensitivity { get { return sensitivity; } protected set { sensitivity = Mathf.Clamp01( value ); } } public float LowerDeadZone { get { return lowerDeadZone; } protected set { lowerDeadZone = Mathf.Clamp01( value ); } } public float UpperDeadZone { get { return upperDeadZone; } protected set { upperDeadZone = Mathf.Clamp01( value ); } } public bool IsSupportedOnThisPlatform { get { if (!IsSupportedOnThisVersionOfUnity) { return false; } if (SupportedPlatforms == null || SupportedPlatforms.Length == 0) { return true; } foreach (var platform in SupportedPlatforms) { if (InputManager.Platform.Contains( platform.ToUpper() )) { return true; } } return false; } } public bool IsSupportedOnThisVersionOfUnity { get { var unityVersion = VersionInfo.UnityVersion(); return unityVersion >= MinUnityVersion && unityVersion <= MaxUnityVersion; } } public bool IsJoystick { get { return (LastResortRegex != null) || (JoystickNames != null && JoystickNames.Length > 0) || (JoystickRegex != null && JoystickRegex.Length > 0); } } public bool IsNotJoystick { get { return !IsJoystick; } } public bool HasJoystickName( string joystickName ) { if (IsNotJoystick) { return false; } if (JoystickNames != null) { if (JoystickNames.Contains( joystickName, StringComparer.OrdinalIgnoreCase )) { return true; } } if (JoystickRegex != null) { for (int i = 0; i < JoystickRegex.Length; i++) { if (Regex.IsMatch( joystickName, JoystickRegex[i], RegexOptions.IgnoreCase )) { return true; } } } return false; } public bool HasLastResortRegex( string joystickName ) { if (IsNotJoystick) { return false; } if (LastResortRegex == null) { return false; } return Regex.IsMatch( joystickName, LastResortRegex, RegexOptions.IgnoreCase ); } public bool HasJoystickOrRegexName( string joystickName ) { return HasJoystickName( joystickName ) || HasLastResortRegex( joystickName ); } public static void Hide( Type type ) { hideList.Add( type ); } public bool IsHidden { get { return hideList.Contains( GetType() ); } } public virtual bool IsKnown { get { return true; } } public int AnalogCount { get { return AnalogMappings.Length; } } public int ButtonCount { get { return ButtonMappings.Length; } } #region InputControlSource Helpers protected static InputControlSource Button( int index ) { return new UnityButtonSource( index ); } protected static InputControlSource Analog( int index ) { return new UnityAnalogSource( index ); } protected static InputControlSource KeyCodeButton( params KeyCode[] keyCodeList ) { return new UnityKeyCodeSource( keyCodeList ); } protected static InputControlSource KeyCodeComboButton( params KeyCode[] keyCodeList ) { return new UnityKeyCodeComboSource( keyCodeList ); } protected static InputControlSource KeyCodeAxis( KeyCode negativeKeyCode, KeyCode positiveKeyCode ) { return new UnityKeyCodeAxisSource( negativeKeyCode, positiveKeyCode ); } protected static InputControlSource Button0 = Button( 0 ); protected static InputControlSource Button1 = Button( 1 ); protected static InputControlSource Button2 = Button( 2 ); protected static InputControlSource Button3 = Button( 3 ); protected static InputControlSource Button4 = Button( 4 ); protected static InputControlSource Button5 = Button( 5 ); protected static InputControlSource Button6 = Button( 6 ); protected static InputControlSource Button7 = Button( 7 ); protected static InputControlSource Button8 = Button( 8 ); protected static InputControlSource Button9 = Button( 9 ); protected static InputControlSource Button10 = Button( 10 ); protected static InputControlSource Button11 = Button( 11 ); protected static InputControlSource Button12 = Button( 12 ); protected static InputControlSource Button13 = Button( 13 ); protected static InputControlSource Button14 = Button( 14 ); protected static InputControlSource Button15 = Button( 15 ); protected static InputControlSource Button16 = Button( 16 ); protected static InputControlSource Button17 = Button( 17 ); protected static InputControlSource Button18 = Button( 18 ); protected static InputControlSource Button19 = Button( 19 ); protected static InputControlSource Analog0 = Analog( 0 ); protected static InputControlSource Analog1 = Analog( 1 ); protected static InputControlSource Analog2 = Analog( 2 ); protected static InputControlSource Analog3 = Analog( 3 ); protected static InputControlSource Analog4 = Analog( 4 ); protected static InputControlSource Analog5 = Analog( 5 ); protected static InputControlSource Analog6 = Analog( 6 ); protected static InputControlSource Analog7 = Analog( 7 ); protected static InputControlSource Analog8 = Analog( 8 ); protected static InputControlSource Analog9 = Analog( 9 ); protected static InputControlSource Analog10 = Analog( 10 ); protected static InputControlSource Analog11 = Analog( 11 ); protected static InputControlSource Analog12 = Analog( 12 ); protected static InputControlSource Analog13 = Analog( 13 ); protected static InputControlSource Analog14 = Analog( 14 ); protected static InputControlSource Analog15 = Analog( 15 ); protected static InputControlSource Analog16 = Analog( 16 ); protected static InputControlSource Analog17 = Analog( 17 ); protected static InputControlSource Analog18 = Analog( 18 ); protected static InputControlSource Analog19 = Analog( 19 ); protected static InputControlSource MouseButton0 = new UnityMouseButtonSource( 0 ); protected static InputControlSource MouseButton1 = new UnityMouseButtonSource( 1 ); protected static InputControlSource MouseButton2 = new UnityMouseButtonSource( 2 ); protected static InputControlSource MouseXAxis = new UnityMouseAxisSource( "x" ); protected static InputControlSource MouseYAxis = new UnityMouseAxisSource( "y" ); protected static InputControlSource MouseScrollWheel = new UnityMouseAxisSource( "z" ); #endregion } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the rds-2014-10-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.RDS.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.RDS.Model.Internal.MarshallTransformations { /// <summary> /// CreateDBInstance Request Marshaller /// </summary> public class CreateDBInstanceRequestMarshaller : IMarshaller<IRequest, CreateDBInstanceRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((CreateDBInstanceRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(CreateDBInstanceRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.RDS"); request.Parameters.Add("Action", "CreateDBInstance"); request.Parameters.Add("Version", "2014-10-31"); if(publicRequest != null) { if(publicRequest.IsSetAllocatedStorage()) { request.Parameters.Add("AllocatedStorage", StringUtils.FromInt(publicRequest.AllocatedStorage)); } if(publicRequest.IsSetAutoMinorVersionUpgrade()) { request.Parameters.Add("AutoMinorVersionUpgrade", StringUtils.FromBool(publicRequest.AutoMinorVersionUpgrade)); } if(publicRequest.IsSetAvailabilityZone()) { request.Parameters.Add("AvailabilityZone", StringUtils.FromString(publicRequest.AvailabilityZone)); } if(publicRequest.IsSetBackupRetentionPeriod()) { request.Parameters.Add("BackupRetentionPeriod", StringUtils.FromInt(publicRequest.BackupRetentionPeriod)); } if(publicRequest.IsSetCharacterSetName()) { request.Parameters.Add("CharacterSetName", StringUtils.FromString(publicRequest.CharacterSetName)); } if(publicRequest.IsSetDBClusterIdentifier()) { request.Parameters.Add("DBClusterIdentifier", StringUtils.FromString(publicRequest.DBClusterIdentifier)); } if(publicRequest.IsSetDBInstanceClass()) { request.Parameters.Add("DBInstanceClass", StringUtils.FromString(publicRequest.DBInstanceClass)); } if(publicRequest.IsSetDBInstanceIdentifier()) { request.Parameters.Add("DBInstanceIdentifier", StringUtils.FromString(publicRequest.DBInstanceIdentifier)); } if(publicRequest.IsSetDBName()) { request.Parameters.Add("DBName", StringUtils.FromString(publicRequest.DBName)); } if(publicRequest.IsSetDBParameterGroupName()) { request.Parameters.Add("DBParameterGroupName", StringUtils.FromString(publicRequest.DBParameterGroupName)); } if(publicRequest.IsSetDBSecurityGroups()) { int publicRequestlistValueIndex = 1; foreach(var publicRequestlistValue in publicRequest.DBSecurityGroups) { request.Parameters.Add("DBSecurityGroups" + "." + "member" + "." + publicRequestlistValueIndex, StringUtils.FromString(publicRequestlistValue)); publicRequestlistValueIndex++; } } if(publicRequest.IsSetDBSubnetGroupName()) { request.Parameters.Add("DBSubnetGroupName", StringUtils.FromString(publicRequest.DBSubnetGroupName)); } if(publicRequest.IsSetEngine()) { request.Parameters.Add("Engine", StringUtils.FromString(publicRequest.Engine)); } if(publicRequest.IsSetEngineVersion()) { request.Parameters.Add("EngineVersion", StringUtils.FromString(publicRequest.EngineVersion)); } if(publicRequest.IsSetIops()) { request.Parameters.Add("Iops", StringUtils.FromInt(publicRequest.Iops)); } if(publicRequest.IsSetKmsKeyId()) { request.Parameters.Add("KmsKeyId", StringUtils.FromString(publicRequest.KmsKeyId)); } if(publicRequest.IsSetLicenseModel()) { request.Parameters.Add("LicenseModel", StringUtils.FromString(publicRequest.LicenseModel)); } if(publicRequest.IsSetMasterUsername()) { request.Parameters.Add("MasterUsername", StringUtils.FromString(publicRequest.MasterUsername)); } if(publicRequest.IsSetMasterUserPassword()) { request.Parameters.Add("MasterUserPassword", StringUtils.FromString(publicRequest.MasterUserPassword)); } if(publicRequest.IsSetMultiAZ()) { request.Parameters.Add("MultiAZ", StringUtils.FromBool(publicRequest.MultiAZ)); } if(publicRequest.IsSetOptionGroupName()) { request.Parameters.Add("OptionGroupName", StringUtils.FromString(publicRequest.OptionGroupName)); } if(publicRequest.IsSetPort()) { request.Parameters.Add("Port", StringUtils.FromInt(publicRequest.Port)); } if(publicRequest.IsSetPreferredBackupWindow()) { request.Parameters.Add("PreferredBackupWindow", StringUtils.FromString(publicRequest.PreferredBackupWindow)); } if(publicRequest.IsSetPreferredMaintenanceWindow()) { request.Parameters.Add("PreferredMaintenanceWindow", StringUtils.FromString(publicRequest.PreferredMaintenanceWindow)); } if(publicRequest.IsSetPubliclyAccessible()) { request.Parameters.Add("PubliclyAccessible", StringUtils.FromBool(publicRequest.PubliclyAccessible)); } if(publicRequest.IsSetStorageEncrypted()) { request.Parameters.Add("StorageEncrypted", StringUtils.FromBool(publicRequest.StorageEncrypted)); } if(publicRequest.IsSetStorageType()) { request.Parameters.Add("StorageType", StringUtils.FromString(publicRequest.StorageType)); } if(publicRequest.IsSetTags()) { int publicRequestlistValueIndex = 1; foreach(var publicRequestlistValue in publicRequest.Tags) { if(publicRequestlistValue.IsSetKey()) { request.Parameters.Add("Tags" + "." + "member" + "." + publicRequestlistValueIndex + "." + "Key", StringUtils.FromString(publicRequestlistValue.Key)); } if(publicRequestlistValue.IsSetValue()) { request.Parameters.Add("Tags" + "." + "member" + "." + publicRequestlistValueIndex + "." + "Value", StringUtils.FromString(publicRequestlistValue.Value)); } publicRequestlistValueIndex++; } } if(publicRequest.IsSetTdeCredentialArn()) { request.Parameters.Add("TdeCredentialArn", StringUtils.FromString(publicRequest.TdeCredentialArn)); } if(publicRequest.IsSetTdeCredentialPassword()) { request.Parameters.Add("TdeCredentialPassword", StringUtils.FromString(publicRequest.TdeCredentialPassword)); } if(publicRequest.IsSetVpcSecurityGroupIds()) { int publicRequestlistValueIndex = 1; foreach(var publicRequestlistValue in publicRequest.VpcSecurityGroupIds) { request.Parameters.Add("VpcSecurityGroupIds" + "." + "member" + "." + publicRequestlistValueIndex, StringUtils.FromString(publicRequestlistValue)); publicRequestlistValueIndex++; } } } return request; } } }
// 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 gax = Google.Api.Gax; using gcav = Google.Cloud.AIPlatform.V1; using sys = System; namespace Google.Cloud.AIPlatform.V1 { /// <summary>Resource name for the <c>EntityType</c> resource.</summary> public sealed partial class EntityTypeName : gax::IResourceName, sys::IEquatable<EntityTypeName> { /// <summary>The possible contents of <see cref="EntityTypeName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entity_type}</c>. /// </summary> ProjectLocationFeaturestoreEntityType = 1, } private static gax::PathTemplate s_projectLocationFeaturestoreEntityType = new gax::PathTemplate("projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entity_type}"); /// <summary>Creates a <see cref="EntityTypeName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="EntityTypeName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static EntityTypeName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new EntityTypeName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="EntityTypeName"/> with the pattern /// <c>projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entity_type}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="featurestoreId">The <c>Featurestore</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="entityTypeId">The <c>EntityType</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="EntityTypeName"/> constructed from the provided ids.</returns> public static EntityTypeName FromProjectLocationFeaturestoreEntityType(string projectId, string locationId, string featurestoreId, string entityTypeId) => new EntityTypeName(ResourceNameType.ProjectLocationFeaturestoreEntityType, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), featurestoreId: gax::GaxPreconditions.CheckNotNullOrEmpty(featurestoreId, nameof(featurestoreId)), entityTypeId: gax::GaxPreconditions.CheckNotNullOrEmpty(entityTypeId, nameof(entityTypeId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="EntityTypeName"/> with pattern /// <c>projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entity_type}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="featurestoreId">The <c>Featurestore</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="entityTypeId">The <c>EntityType</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="EntityTypeName"/> with pattern /// <c>projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entity_type}</c>. /// </returns> public static string Format(string projectId, string locationId, string featurestoreId, string entityTypeId) => FormatProjectLocationFeaturestoreEntityType(projectId, locationId, featurestoreId, entityTypeId); /// <summary> /// Formats the IDs into the string representation of this <see cref="EntityTypeName"/> with pattern /// <c>projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entity_type}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="featurestoreId">The <c>Featurestore</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="entityTypeId">The <c>EntityType</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="EntityTypeName"/> with pattern /// <c>projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entity_type}</c>. /// </returns> public static string FormatProjectLocationFeaturestoreEntityType(string projectId, string locationId, string featurestoreId, string entityTypeId) => s_projectLocationFeaturestoreEntityType.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(featurestoreId, nameof(featurestoreId)), gax::GaxPreconditions.CheckNotNullOrEmpty(entityTypeId, nameof(entityTypeId))); /// <summary>Parses the given resource name string into a new <see cref="EntityTypeName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entity_type}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="entityTypeName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="EntityTypeName"/> if successful.</returns> public static EntityTypeName Parse(string entityTypeName) => Parse(entityTypeName, false); /// <summary> /// Parses the given resource name string into a new <see cref="EntityTypeName"/> instance; optionally allowing /// an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entity_type}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="entityTypeName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="EntityTypeName"/> if successful.</returns> public static EntityTypeName Parse(string entityTypeName, bool allowUnparsed) => TryParse(entityTypeName, allowUnparsed, out EntityTypeName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="EntityTypeName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entity_type}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="entityTypeName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="EntityTypeName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string entityTypeName, out EntityTypeName result) => TryParse(entityTypeName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="EntityTypeName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entity_type}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="entityTypeName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="EntityTypeName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string entityTypeName, bool allowUnparsed, out EntityTypeName result) { gax::GaxPreconditions.CheckNotNull(entityTypeName, nameof(entityTypeName)); gax::TemplatedResourceName resourceName; if (s_projectLocationFeaturestoreEntityType.TryParseName(entityTypeName, out resourceName)) { result = FromProjectLocationFeaturestoreEntityType(resourceName[0], resourceName[1], resourceName[2], resourceName[3]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(entityTypeName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private EntityTypeName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string entityTypeId = null, string featurestoreId = null, string locationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; EntityTypeId = entityTypeId; FeaturestoreId = featurestoreId; LocationId = locationId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="EntityTypeName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entity_type}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="featurestoreId">The <c>Featurestore</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="entityTypeId">The <c>EntityType</c> ID. Must not be <c>null</c> or empty.</param> public EntityTypeName(string projectId, string locationId, string featurestoreId, string entityTypeId) : this(ResourceNameType.ProjectLocationFeaturestoreEntityType, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), featurestoreId: gax::GaxPreconditions.CheckNotNullOrEmpty(featurestoreId, nameof(featurestoreId)), entityTypeId: gax::GaxPreconditions.CheckNotNullOrEmpty(entityTypeId, nameof(entityTypeId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>EntityType</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string EntityTypeId { get; } /// <summary> /// The <c>Featurestore</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string FeaturestoreId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationFeaturestoreEntityType: return s_projectLocationFeaturestoreEntityType.Expand(ProjectId, LocationId, FeaturestoreId, EntityTypeId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as EntityTypeName); /// <inheritdoc/> public bool Equals(EntityTypeName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(EntityTypeName a, EntityTypeName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(EntityTypeName a, EntityTypeName b) => !(a == b); } public partial class EntityType { /// <summary> /// <see cref="gcav::EntityTypeName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcav::EntityTypeName EntityTypeName { get => string.IsNullOrEmpty(Name) ? null : gcav::EntityTypeName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
using System; using System.Collections.Generic; using System.ComponentModel.Design; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using ErrorHandler = Microsoft.VisualStudio.ErrorHandler; using VSConstants = Microsoft.VisualStudio.VSConstants; namespace Nitra.VisualStudio { /// <summary> /// Single node inside the tree of the libraries in the object browser or class view. /// </summary> class LibraryNode : IVsSimpleObjectList2, IVsNavInfoNode { public const uint NullIndex = (uint)0xFFFFFFFF; /// <summary> /// Enumeration of the capabilities of a node. It is possible to combine different values /// to support more capabilities. /// This enumeration is a copy of _LIB_LISTCAPABILITIES with the Flags attribute set. /// </summary> [Flags] public enum LibraryNodeCapabilities { None = _LIB_LISTCAPABILITIES.LLC_NONE, HasBrowseObject = _LIB_LISTCAPABILITIES.LLC_HASBROWSEOBJ, HasDescriptionPane = _LIB_LISTCAPABILITIES.LLC_HASDESCPANE, HasSourceContext = _LIB_LISTCAPABILITIES.LLC_HASSOURCECONTEXT, HasCommands = _LIB_LISTCAPABILITIES.LLC_HASCOMMANDS, AllowDragDrop = _LIB_LISTCAPABILITIES.LLC_ALLOWDRAGDROP, AllowRename = _LIB_LISTCAPABILITIES.LLC_ALLOWRENAME, AllowDelete = _LIB_LISTCAPABILITIES.LLC_ALLOWDELETE, AllowSourceControl = _LIB_LISTCAPABILITIES.LLC_ALLOWSCCOPS, } /// <summary> /// Enumeration of the possible types of node. The type of a node can be the combination /// of one of more of these values. /// This is actually a copy of the _LIB_LISTTYPE enumeration with the difference that the /// Flags attribute is set so that it is possible to specify more than one value. /// </summary> [Flags] public enum LibraryNodeType { None = 0, Hierarchy = _LIB_LISTTYPE.LLT_HIERARCHY, Namespaces = _LIB_LISTTYPE.LLT_NAMESPACES, Classes = _LIB_LISTTYPE.LLT_CLASSES, Members = _LIB_LISTTYPE.LLT_MEMBERS, Package = _LIB_LISTTYPE.LLT_PACKAGE, PhysicalContainer = _LIB_LISTTYPE.LLT_PHYSICALCONTAINERS, Containment = _LIB_LISTTYPE.LLT_CONTAINMENT, ContainedBy = _LIB_LISTTYPE.LLT_CONTAINEDBY, UsesClasses = _LIB_LISTTYPE.LLT_USESCLASSES, UsedByClasses = _LIB_LISTTYPE.LLT_USEDBYCLASSES, NestedClasses = _LIB_LISTTYPE.LLT_NESTEDCLASSES, InheritedInterface = _LIB_LISTTYPE.LLT_INHERITEDINTERFACES, InterfaceUsedByClasses = _LIB_LISTTYPE.LLT_INTERFACEUSEDBYCLASSES, Definitions = _LIB_LISTTYPE.LLT_DEFINITIONS, References = _LIB_LISTTYPE.LLT_REFERENCES, DeferExpansion = _LIB_LISTTYPE.LLT_DEFEREXPANSION, } private string _name; private LibraryNodeType _type; private List<LibraryNode> _children; private LibraryNodeCapabilities _capabilities; private List<VSOBJCLIPFORMAT> _clipboardFormats; private VSTREEDISPLAYDATA _displayData; private _VSTREEFLAGS _flags; private CommandID _contextMenuID; private string _tooltip; private uint _updateCount; private Dictionary<LibraryNodeType, LibraryNode> _filteredView; public LibraryNode(string name) : this(name, LibraryNodeType.None, LibraryNodeCapabilities.None, null) { } public LibraryNode(string name, LibraryNodeType type) : this(name, type, LibraryNodeCapabilities.None, null) { } public LibraryNode( string name, LibraryNodeType type, LibraryNodeCapabilities capabilities, CommandID contextMenuID) { _capabilities = capabilities; _contextMenuID = contextMenuID; _name = name; _tooltip = name; _type = type; _children = new List<LibraryNode>(); _clipboardFormats = new List<VSOBJCLIPFORMAT>(); _filteredView = new Dictionary<LibraryNodeType, LibraryNode>(); } public LibraryNode(LibraryNode node) { _capabilities = node._capabilities; _contextMenuID = node._contextMenuID; _displayData = node._displayData; _name = node._name; _tooltip = node._tooltip; _type = node._type; _children = new List<LibraryNode>(); foreach (LibraryNode child in node._children) _children.Add(child); _clipboardFormats = new List<VSOBJCLIPFORMAT>(); foreach (VSOBJCLIPFORMAT format in node._clipboardFormats) _clipboardFormats.Add(format); _filteredView = new Dictionary<LibraryNodeType, LibraryNode>(); _updateCount = node._updateCount; } protected void SetCapabilityFlag(LibraryNodeCapabilities flag, bool value) { if (value) _capabilities |= flag; else _capabilities &= ~flag; } /// <summary> /// Get or Set if the node can be deleted. /// </summary> public bool CanDelete { get { return (_capabilities & LibraryNodeCapabilities.AllowDelete) != 0; } set { SetCapabilityFlag(LibraryNodeCapabilities.AllowDelete, value); } } /// <summary> /// Get or Set if the node can be associated with some source code. /// </summary> public bool CanGoToSource { get { return (_capabilities & LibraryNodeCapabilities.HasSourceContext) != 0; } set { SetCapabilityFlag(LibraryNodeCapabilities.HasSourceContext, value); } } /// <summary> /// Get or Set if the node can be renamed. /// </summary> public bool CanRename { get { return (_capabilities & LibraryNodeCapabilities.AllowRename) != 0; } set { SetCapabilityFlag(LibraryNodeCapabilities.AllowRename, value); } } public LibraryNodeCapabilities Capabilities { get { return _capabilities; } set { _capabilities = value; } } public _VSTREEFLAGS Flags { get { return _flags; } set { _flags = value; } } public string TooltipText { get { return _tooltip; } set { _tooltip = value; } } internal void AddNode(LibraryNode node) { lock (_children) { _children.Add(node); } _updateCount++; } internal void RemoveNode(LibraryNode node) { lock (_children) { _children.Remove(node); } _updateCount++; } protected virtual object BrowseObject { get { return null; } } protected virtual uint CategoryField(LIB_CATEGORY category) { switch (category) { case LIB_CATEGORY.LC_LISTTYPE: LibraryNodeType subTypes = LibraryNodeType.None; foreach (LibraryNode node in _children) subTypes |= node._type; return (uint)subTypes; case (LIB_CATEGORY)_LIB_CATEGORY2.LC_HIERARCHYTYPE: return (uint)_LIBCAT_HIERARCHYTYPE.LCHT_UNKNOWN; default: throw new NotImplementedException(); } } protected virtual LibraryNode Clone() { return new LibraryNode(this); } /// <summary> /// Performs the operations needed to delete this node. /// </summary> protected virtual void Delete() { } /// <summary> /// Perform a Drag and Drop operation on this node. /// </summary> protected virtual void DoDragDrop(OleDataObject dataObject, uint keyState, uint effect) { } protected virtual uint EnumClipboardFormats(_VSOBJCFFLAGS flags, VSOBJCLIPFORMAT[] formats) { if ((null == formats) || (formats.Length == 0)) return (uint)_clipboardFormats.Count; uint itemsToCopy = (uint)_clipboardFormats.Count; if (itemsToCopy > (uint)formats.Length) itemsToCopy = (uint)formats.Length; Array.Copy(_clipboardFormats.ToArray(), formats, (int)itemsToCopy); return itemsToCopy; } protected virtual void FillDescription(_VSOBJDESCOPTIONS flags, IVsObjectBrowserDescription3 description) { description.ClearDescriptionText(); description.AddDescriptionText3(_name, VSOBDESCRIPTIONSECTION.OBDS_NAME, null); } protected IVsSimpleObjectList2 FilterView(LibraryNodeType filterType) { LibraryNode filtered; if (_filteredView.TryGetValue(filterType, out filtered)) return filtered; filtered = Clone(); for (int i = 0; i < filtered._children.Count; ) { if (0 == (filtered._children[i]._type & filterType)) filtered._children.RemoveAt(i); else i += 1; } _filteredView.Add(filterType, filtered); return filtered; } protected virtual void GotoSource(VSOBJGOTOSRCTYPE gotoType) { // Do nothing. } public string Name { get { return _name; } set { _name = value; } } public LibraryNodeType NodeType { get { return _type; } set { _type = value; } } /// <summary> /// Finds the source files associated with this node. /// </summary> /// <param name="hierarchy">The hierarchy containing the items.</param> /// <param name="itemId">The item id of the item.</param> /// <param name="itemsCount">Number of items.</param> protected virtual void SourceItems(out IVsHierarchy hierarchy, out uint itemId, out uint itemsCount) { hierarchy = null; itemId = 0; itemsCount = 0; } protected virtual void Rename(string newName, uint flags) { _name = newName; } public virtual string UniqueName { get { return Name; } } #region IVsSimpleObjectList2 Members int IVsSimpleObjectList2.CanDelete(uint index, out int pfOK) { if (index >= (uint)_children.Count) throw new ArgumentOutOfRangeException(nameof(index)); pfOK = _children[(int)index].CanDelete ? 1 : 0; return VSConstants.S_OK; } int IVsSimpleObjectList2.CanGoToSource(uint index, VSOBJGOTOSRCTYPE SrcType, out int pfOK) { if (index >= (uint)_children.Count) throw new ArgumentOutOfRangeException(nameof(index)); pfOK = _children[(int)index].CanGoToSource ? 1 : 0; return VSConstants.S_OK; } int IVsSimpleObjectList2.CanRename(uint index, string pszNewName, out int pfOK) { if (index >= (uint)_children.Count) throw new ArgumentOutOfRangeException(nameof(index)); pfOK = _children[(int)index].CanRename ? 1 : 0; return VSConstants.S_OK; } int IVsSimpleObjectList2.CountSourceItems(uint index, out IVsHierarchy ppHier, out uint pItemid, out uint pcItems) { if (index >= (uint)_children.Count) throw new ArgumentOutOfRangeException(nameof(index)); _children[(int)index].SourceItems(out ppHier, out pItemid, out pcItems); return VSConstants.S_OK; } int IVsSimpleObjectList2.DoDelete(uint index, uint grfFlags) { if (index >= (uint)_children.Count) throw new ArgumentOutOfRangeException(nameof(index)); _children[(int)index].Delete(); _children.RemoveAt((int)index); return VSConstants.S_OK; } int IVsSimpleObjectList2.DoDragDrop(uint index, IDataObject pDataObject, uint grfKeyState, ref uint pdwEffect) { if (index >= (uint)_children.Count) throw new ArgumentOutOfRangeException(nameof(index)); OleDataObject dataObject = new OleDataObject(pDataObject); _children[(int)index].DoDragDrop(dataObject, grfKeyState, pdwEffect); return VSConstants.S_OK; } int IVsSimpleObjectList2.DoRename(uint index, string pszNewName, uint grfFlags) { if (index >= (uint)_children.Count) throw new ArgumentOutOfRangeException(nameof(index)); _children[(int)index].Rename(pszNewName, grfFlags); return VSConstants.S_OK; } int IVsSimpleObjectList2.EnumClipboardFormats(uint index, uint grfFlags, uint celt, VSOBJCLIPFORMAT[] rgcfFormats, uint[] pcActual) { if (index >= (uint)_children.Count) throw new ArgumentOutOfRangeException(nameof(index)); uint copied = _children[(int)index].EnumClipboardFormats((_VSOBJCFFLAGS)grfFlags, rgcfFormats); if ((null != pcActual) && (pcActual.Length > 0)) pcActual[0] = copied; return VSConstants.S_OK; } int IVsSimpleObjectList2.FillDescription2(uint index, uint grfOptions, IVsObjectBrowserDescription3 pobDesc) { if (index >= (uint)_children.Count) throw new ArgumentOutOfRangeException(nameof(index)); _children[(int)index].FillDescription((_VSOBJDESCOPTIONS)grfOptions, pobDesc); return VSConstants.S_OK; } int IVsSimpleObjectList2.GetBrowseObject(uint index, out object ppdispBrowseObj) { if (index >= (uint)_children.Count) throw new ArgumentOutOfRangeException(nameof(index)); ppdispBrowseObj = _children[(int)index].BrowseObject; if (null == ppdispBrowseObj) return VSConstants.E_NOTIMPL; return VSConstants.S_OK; } int IVsSimpleObjectList2.GetCapabilities2(out uint pgrfCapabilities) { pgrfCapabilities = (uint)Capabilities; return VSConstants.S_OK; } int IVsSimpleObjectList2.GetCategoryField2(uint index, int Category, out uint pfCatField) { LibraryNode node; if (NullIndex == index) { node = this; } else if (index < (uint)_children.Count) { node = _children[(int)index]; } else { throw new ArgumentOutOfRangeException(nameof(index)); } pfCatField = node.CategoryField((LIB_CATEGORY)Category); return VSConstants.S_OK; } int IVsSimpleObjectList2.GetClipboardFormat(uint index, uint grfFlags, FORMATETC[] pFormatetc, STGMEDIUM[] pMedium) { return VSConstants.E_NOTIMPL; } int IVsSimpleObjectList2.GetContextMenu(uint index, out Guid pclsidActive, out int pnMenuId, out IOleCommandTarget ppCmdTrgtActive) { if (index >= (uint)_children.Count) throw new ArgumentOutOfRangeException(nameof(index)); CommandID commandId = _children[(int)index]._contextMenuID; if (commandId == null) { pclsidActive = Guid.Empty; pnMenuId = 0; ppCmdTrgtActive = null; return VSConstants.E_NOTIMPL; } pclsidActive = commandId.Guid; pnMenuId = commandId.ID; ppCmdTrgtActive = _children[(int)index] as IOleCommandTarget; return VSConstants.S_OK; } int IVsSimpleObjectList2.GetDisplayData(uint index, VSTREEDISPLAYDATA[] pData) { if (index >= (uint)_children.Count) throw new ArgumentOutOfRangeException(nameof(index)); pData[0] = _children[(int)index]._displayData; return VSConstants.S_OK; } int IVsSimpleObjectList2.GetExpandable3(uint index, uint ListTypeExcluded, out int pfExpandable) { // There is a not empty implementation of GetCategoryField2, so this method should // return E_NOTIMPL. pfExpandable = 0; return VSConstants.E_NOTIMPL; } int IVsSimpleObjectList2.GetExtendedClipboardVariant(uint index, uint grfFlags, VSOBJCLIPFORMAT[] pcfFormat, out object pvarFormat) { pvarFormat = null; return VSConstants.E_NOTIMPL; } int IVsSimpleObjectList2.GetFlags(out uint pFlags) { pFlags = (uint)Flags; return VSConstants.S_OK; } int IVsSimpleObjectList2.GetItemCount(out uint pCount) { pCount = (uint)_children.Count; return VSConstants.S_OK; } int IVsSimpleObjectList2.GetList2(uint index, uint ListType, uint flags, VSOBSEARCHCRITERIA2[] pobSrch, out IVsSimpleObjectList2 ppIVsSimpleObjectList2) { // TODO: Use the flags and list type to actually filter the result. if (index >= (uint)_children.Count) throw new ArgumentOutOfRangeException(nameof(index)); ppIVsSimpleObjectList2 = _children[(int)index].FilterView((LibraryNodeType)ListType); return VSConstants.S_OK; } int IVsSimpleObjectList2.GetMultipleSourceItems(uint index, uint grfGSI, uint cItems, VSITEMSELECTION[] rgItemSel) { return VSConstants.E_NOTIMPL; } int IVsSimpleObjectList2.GetNavInfo(uint index, out IVsNavInfo ppNavInfo) { ppNavInfo = null; return VSConstants.E_NOTIMPL; } int IVsSimpleObjectList2.GetNavInfoNode(uint index, out IVsNavInfoNode ppNavInfoNode) { if (index >= (uint)_children.Count) throw new ArgumentOutOfRangeException(nameof(index)); ppNavInfoNode = _children[(int)index] as IVsNavInfoNode; return VSConstants.S_OK; } int IVsSimpleObjectList2.GetProperty(uint index, int propid, out object pvar) { pvar = null; return VSConstants.E_NOTIMPL; } protected virtual void GetSourceContextWithOwnership(out string fileName, out uint pulLineNum) { fileName = null; pulLineNum = 0; } int IVsSimpleObjectList2.GetSourceContextWithOwnership(uint index, out string pbstrFilename, out uint pulLineNum) { if(index >= (uint)_children.Count) throw new ArgumentOutOfRangeException(nameof(index)); _children[(int)index].GetSourceContextWithOwnership(out pbstrFilename, out pulLineNum); return pbstrFilename != null ? VSConstants.S_OK : VSConstants.E_NOTIMPL; } protected virtual string GetTextWithOwnership(VSTREETEXTOPTIONS tto) { return Name; } int IVsSimpleObjectList2.GetTextWithOwnership(uint index, VSTREETEXTOPTIONS tto, out string pbstrText) { // TODO: make use of the text option. if (index >= (uint)_children.Count) throw new ArgumentOutOfRangeException(nameof(index)); pbstrText = _children[(int)index].GetTextWithOwnership(tto); return pbstrText != null ? VSConstants.S_OK : VSConstants.E_NOTIMPL; } int IVsSimpleObjectList2.GetTipTextWithOwnership(uint index, VSTREETOOLTIPTYPE eTipType, out string pbstrText) { // TODO: Make use of the tooltip type. if (index >= (uint)_children.Count) throw new ArgumentOutOfRangeException(nameof(index)); pbstrText = _children[(int)index].TooltipText; return VSConstants.S_OK; } int IVsSimpleObjectList2.GetUserContext(uint index, out object ppunkUserCtx) { ppunkUserCtx = null; return VSConstants.E_NOTIMPL; } int IVsSimpleObjectList2.GoToSource(uint index, VSOBJGOTOSRCTYPE SrcType) { if (index >= (uint)_children.Count) throw new ArgumentOutOfRangeException(nameof(index)); _children[(int)index].GotoSource(SrcType); return VSConstants.S_OK; } int IVsSimpleObjectList2.LocateNavInfoNode(IVsNavInfoNode pNavInfoNode, out uint pulIndex) { if (null == pNavInfoNode) throw new ArgumentNullException(nameof(pNavInfoNode)); pulIndex = NullIndex; string nodeName; ErrorHandler.ThrowOnFailure(pNavInfoNode.get_Name(out nodeName)); for (int i = 0; i < _children.Count; i++) { if (0 == string.Compare(_children[i].UniqueName, nodeName, StringComparison.OrdinalIgnoreCase)) { pulIndex = (uint)i; return VSConstants.S_OK; } } return VSConstants.S_FALSE; } int IVsSimpleObjectList2.OnClose(VSTREECLOSEACTIONS[] ptca) { // Do Nothing. return VSConstants.S_OK; } int IVsSimpleObjectList2.QueryDragDrop(uint index, IDataObject pDataObject, uint grfKeyState, ref uint pdwEffect) { return VSConstants.E_NOTIMPL; } int IVsSimpleObjectList2.ShowHelp(uint index) { return VSConstants.E_NOTIMPL; } int IVsSimpleObjectList2.UpdateCounter(out uint pCurUpdate) { pCurUpdate = _updateCount; return VSConstants.S_OK; } #endregion #region IVsNavInfoNode Members int IVsNavInfoNode.get_Name(out string pbstrName) { pbstrName = UniqueName; return VSConstants.S_OK; } int IVsNavInfoNode.get_Type(out uint pllt) { pllt = (uint)_type; return VSConstants.S_OK; } #endregion } }
using System.Collections.Generic; using GitTools.Testing; using GitVersion; using GitVersionCore.Tests; using LibGit2Sharp; using NUnit.Framework; [TestFixture] public class FeatureBranchScenarios { [Test] public void ShouldInheritIncrementCorrectlyWithMultiplePossibleParentsAndWeirdlyNamedDevelopBranch() { using (var fixture = new EmptyRepositoryFixture()) { fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("development"); Commands.Checkout(fixture.Repository, "development"); //Create an initial feature branch var feature123 = fixture.Repository.CreateBranch("feature/JIRA-123"); Commands.Checkout(fixture.Repository, "feature/JIRA-123"); fixture.Repository.MakeCommits(1); //Merge it Commands.Checkout(fixture.Repository, "development"); fixture.Repository.Merge(feature123, Generate.SignatureNow()); //Create a second feature branch fixture.Repository.CreateBranch("feature/JIRA-124"); Commands.Checkout(fixture.Repository, "feature/JIRA-124"); fixture.Repository.MakeCommits(1); fixture.AssertFullSemver("1.1.0-JIRA-124.1+2"); } } [Test] public void BranchCreatedAfterFastForwardMergeShouldInheritCorrectly() { var config = new Config { Branches = { { "unstable", new BranchConfig { Increment = IncrementStrategy.Minor, Regex = "unstable", SourceBranches = new List<string>(), IsSourceBranchFor = new [] { "feature" } } } } }; using (var fixture = new EmptyRepositoryFixture()) { fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("unstable"); Commands.Checkout(fixture.Repository, "unstable"); //Create an initial feature branch var feature123 = fixture.Repository.CreateBranch("feature/JIRA-123"); Commands.Checkout(fixture.Repository, "feature/JIRA-123"); fixture.Repository.MakeCommits(1); //Merge it Commands.Checkout(fixture.Repository, "unstable"); fixture.Repository.Merge(feature123, Generate.SignatureNow()); //Create a second feature branch fixture.Repository.CreateBranch("feature/JIRA-124"); Commands.Checkout(fixture.Repository, "feature/JIRA-124"); fixture.Repository.MakeCommits(1); fixture.AssertFullSemver(config, "1.1.0-JIRA-124.1+2"); } } [Test] public void ShouldNotUseNumberInFeatureBranchAsPreReleaseNumberOffDevelop() { using (var fixture = new EmptyRepositoryFixture()) { fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("develop"); Commands.Checkout(fixture.Repository, "develop"); fixture.Repository.CreateBranch("feature/JIRA-123"); Commands.Checkout(fixture.Repository, "feature/JIRA-123"); fixture.Repository.MakeCommits(5); fixture.AssertFullSemver("1.1.0-JIRA-123.1+5"); } } [Test] public void ShouldNotUseNumberInFeatureBranchAsPreReleaseNumberOffMaster() { using (var fixture = new EmptyRepositoryFixture()) { fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("feature/JIRA-123"); Commands.Checkout(fixture.Repository, "feature/JIRA-123"); fixture.Repository.MakeCommits(5); fixture.AssertFullSemver("1.0.1-JIRA-123.1+5"); } } [Test] public void TestFeatureBranch() { using (var fixture = new EmptyRepositoryFixture()) { fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("feature-test"); Commands.Checkout(fixture.Repository, "feature-test"); fixture.Repository.MakeCommits(5); fixture.AssertFullSemver("1.0.1-test.1+5"); } } [Test] public void TestFeaturesBranch() { using (var fixture = new EmptyRepositoryFixture()) { fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("features/test"); Commands.Checkout(fixture.Repository, "features/test"); fixture.Repository.MakeCommits(5); fixture.AssertFullSemver("1.0.1-test.1+5"); } } [Test] public void WhenTwoFeatureBranchPointToTheSameCommit() { using (var fixture = new EmptyRepositoryFixture()) { fixture.Repository.MakeACommit(); fixture.Repository.CreateBranch("develop"); Commands.Checkout(fixture.Repository, "develop"); fixture.Repository.CreateBranch("feature/feature1"); Commands.Checkout(fixture.Repository, "feature/feature1"); fixture.Repository.MakeACommit(); fixture.Repository.CreateBranch("feature/feature2"); Commands.Checkout(fixture.Repository, "feature/feature2"); fixture.AssertFullSemver("0.1.0-feature2.1+1"); } } [Test] public void ShouldBePossibleToMergeDevelopForALongRunningBranchWhereDevelopAndMasterAreEqual() { using (var fixture = new EmptyRepositoryFixture()) { fixture.Repository.MakeATaggedCommit("v1.0.0"); fixture.Repository.CreateBranch("develop"); Commands.Checkout(fixture.Repository, "develop"); fixture.Repository.CreateBranch("feature/longrunning"); Commands.Checkout(fixture.Repository, "feature/longrunning"); fixture.Repository.MakeACommit(); Commands.Checkout(fixture.Repository, "develop"); fixture.Repository.MakeACommit(); Commands.Checkout(fixture.Repository, "master"); fixture.Repository.Merge(fixture.Repository.Branches["develop"], Generate.SignatureNow()); fixture.Repository.ApplyTag("v1.1.0"); Commands.Checkout(fixture.Repository, "feature/longrunning"); fixture.Repository.Merge(fixture.Repository.Branches["develop"], Generate.SignatureNow()); var configuration = new Config { VersioningMode = VersioningMode.ContinuousDeployment }; fixture.AssertFullSemver(configuration, "1.2.0-longrunning.2"); } } [Test] public void CanUseBranchNameOffAReleaseBranch() { var config = new Config { Branches = { { "release", new BranchConfig { Tag = "build" } }, { "feature", new BranchConfig { Tag = "useBranchName" } } } }; using (var fixture = new EmptyRepositoryFixture()) { fixture.MakeACommit(); fixture.BranchTo("release/0.3.0"); fixture.MakeATaggedCommit("v0.3.0-build.1"); fixture.MakeACommit(); fixture.BranchTo("feature/PROJ-1"); fixture.MakeACommit(); fixture.AssertFullSemver(config, "0.3.0-PROJ-1.1+2"); } } [TestCase("alpha", "JIRA-123", "alpha")] [TestCase("useBranchName", "JIRA-123", "JIRA-123")] [TestCase("alpha.{BranchName}", "JIRA-123", "alpha.JIRA-123")] public void ShouldUseConfiguredTag(string tag, string featureName, string preReleaseTagName) { var config = new Config { Branches = { { "feature", new BranchConfig { Tag = tag } } } }; using (var fixture = new EmptyRepositoryFixture()) { fixture.Repository.MakeATaggedCommit("1.0.0"); var featureBranchName = $"feature/{featureName}"; fixture.Repository.CreateBranch(featureBranchName); Commands.Checkout(fixture.Repository, featureBranchName); fixture.Repository.MakeCommits(5); var expectedFullSemVer = $"1.0.1-{preReleaseTagName}.1+5"; fixture.AssertFullSemver(config, expectedFullSemVer); } } [Test] public void BranchCreatedAfterFinishReleaseShouldInheritAndIncrementFromLastMasterCommitTag() { using (var fixture = new BaseGitFlowRepositoryFixture("0.1.0")) { //validate current version fixture.AssertFullSemver("0.2.0-alpha.1"); fixture.Repository.CreateBranch("release/0.2.0"); Commands.Checkout(fixture.Repository, "release/0.2.0"); //validate release version fixture.AssertFullSemver("0.2.0-beta.1+0"); fixture.Checkout("master"); fixture.Repository.MergeNoFF("release/0.2.0"); fixture.Repository.ApplyTag("0.2.0"); //validate master branch version fixture.AssertFullSemver("0.2.0"); fixture.Checkout("develop"); fixture.Repository.MergeNoFF("release/0.2.0"); fixture.Repository.Branches.Remove("release/2.0.0"); fixture.Repository.MakeACommit(); //validate develop branch version after merging release 0.2.0 to master and develop (finish release) fixture.AssertFullSemver("0.3.0-alpha.1"); //create a feature branch from develop fixture.BranchTo("feature/TEST-1"); fixture.Repository.MakeACommit(); //I'm not entirely sure what the + value should be but I know the semvar major/minor/patch should be 0.3.0 fixture.AssertFullSemver("0.3.0-TEST-1.1+2"); } } [Test] public void ShouldPickUpVersionFromDevelopAfterReleaseBranchCreated() { using (var fixture = new EmptyRepositoryFixture()) { // Create develop and release branches fixture.MakeACommit(); fixture.BranchTo("develop"); fixture.MakeACommit(); fixture.BranchTo("release/1.0"); fixture.MakeACommit(); fixture.Checkout("develop"); fixture.MakeACommit(); fixture.AssertFullSemver("1.1.0-alpha.1"); // create a feature branch from develop and verify the version fixture.BranchTo("feature/test"); fixture.AssertFullSemver("1.1.0-test.1+1"); } } [Test] public void ShouldPickUpVersionFromDevelopAfterReleaseBranchMergedBack() { using (var fixture = new EmptyRepositoryFixture()) { // Create develop and release branches fixture.MakeACommit(); fixture.BranchTo("develop"); fixture.MakeACommit(); fixture.BranchTo("release/1.0"); fixture.MakeACommit(); // merge release into develop fixture.Checkout("develop"); fixture.MergeNoFF("release/1.0"); fixture.AssertFullSemver("1.1.0-alpha.2"); // create a feature branch from develop and verify the version fixture.BranchTo("feature/test"); fixture.AssertFullSemver("1.1.0-test.1+2"); } } public class WhenMasterMarkedAsIsDevelop { [Test] public void ShouldPickUpVersionFromMasterAfterReleaseBranchCreated() { var config = new Config { Branches = new Dictionary<string, BranchConfig> { { "master", new BranchConfig() { TracksReleaseBranches = true, Regex = "master" } } } }; using (var fixture = new EmptyRepositoryFixture()) { // Create release branch fixture.MakeACommit(); fixture.BranchTo("release/1.0"); fixture.MakeACommit(); fixture.Checkout("master"); fixture.MakeACommit(); fixture.AssertFullSemver(config, "1.0.1+1"); // create a feature branch from master and verify the version fixture.BranchTo("feature/test"); fixture.AssertFullSemver(config, "1.0.1-test.1+1"); } } [Test] public void ShouldPickUpVersionFromMasterAfterReleaseBranchMergedBack() { var config = new Config { Branches = new Dictionary<string, BranchConfig> { { "master", new BranchConfig() { TracksReleaseBranches = true, Regex = "master" } } } }; using (var fixture = new EmptyRepositoryFixture()) { // Create release branch fixture.MakeACommit(); fixture.BranchTo("release/1.0"); fixture.MakeACommit(); // merge release into master fixture.Checkout("master"); fixture.MergeNoFF("release/1.0"); fixture.AssertFullSemver(config, "1.0.1+2"); // create a feature branch from master and verify the version fixture.BranchTo("feature/test"); fixture.AssertFullSemver(config, "1.0.1-test.1+2"); } } } public class WhenFeatureBranchHasNoConfig { [Test] public void ShouldPickUpVersionFromMasterAfterReleaseBranchCreated() { using (var fixture = new EmptyRepositoryFixture()) { // Create develop and release branches fixture.MakeACommit(); fixture.BranchTo("develop"); fixture.MakeACommit(); fixture.BranchTo("release/1.0"); fixture.MakeACommit(); fixture.Checkout("develop"); fixture.MakeACommit(); fixture.AssertFullSemver("1.1.0-alpha.1"); // create a misnamed feature branch (i.e. it uses the default config) from develop and verify the version fixture.BranchTo("misnamed"); fixture.AssertFullSemver("1.1.0-misnamed.1+1"); } } [Test] public void ShouldPickUpVersionFromDevelopAfterReleaseBranchMergedBack() { using (var fixture = new EmptyRepositoryFixture()) { // Create develop and release branches fixture.MakeACommit(); fixture.BranchTo("develop"); fixture.MakeACommit(); fixture.BranchTo("release/1.0"); fixture.MakeACommit(); // merge release into develop fixture.Checkout("develop"); fixture.MergeNoFF("release/1.0"); fixture.AssertFullSemver("1.1.0-alpha.2"); // create a misnamed feature branch (i.e. it uses the default config) from develop and verify the version fixture.BranchTo("misnamed"); fixture.AssertFullSemver("1.1.0-misnamed.1+2"); } } // ReSharper disable once MemberHidesStaticFromOuterClass public class WhenMasterMarkedAsIsDevelop { [Test] public void ShouldPickUpVersionFromMasterAfterReleaseBranchCreated() { var config = new Config { Branches = new Dictionary<string, BranchConfig> { { "master", new BranchConfig() { TracksReleaseBranches = true, Regex = "master" } } } }; using (var fixture = new EmptyRepositoryFixture()) { // Create release branch fixture.MakeACommit(); fixture.BranchTo("release/1.0"); fixture.MakeACommit(); fixture.Checkout("master"); fixture.MakeACommit(); fixture.AssertFullSemver(config, "1.0.1+1"); // create a misnamed feature branch (i.e. it uses the default config) from master and verify the version fixture.BranchTo("misnamed"); fixture.AssertFullSemver(config, "1.0.1-misnamed.1+1"); } } [Test] public void ShouldPickUpVersionFromMasterAfterReleaseBranchMergedBack() { var config = new Config { Branches = new Dictionary<string, BranchConfig> { { "master", new BranchConfig() { TracksReleaseBranches = true, Regex = "master" } } } }; using (var fixture = new EmptyRepositoryFixture()) { // Create release branch fixture.MakeACommit(); fixture.BranchTo("release/1.0"); fixture.MakeACommit(); // merge release into master fixture.Checkout("master"); fixture.MergeNoFF("release/1.0"); fixture.AssertFullSemver(config, "1.0.1+2"); // create a misnamed feature branch (i.e. it uses the default config) from master and verify the version fixture.BranchTo("misnamed"); fixture.AssertFullSemver(config, "1.0.1-misnamed.1+2"); } } } } [Test] public void PickUpVersionFromMasterMarkedWithIsTracksReleaseBranches() { var config = new Config { VersioningMode = VersioningMode.ContinuousDelivery, Branches = new Dictionary<string, BranchConfig> { { "master", new BranchConfig() { Tag = "pre", TracksReleaseBranches = true, } }, { "release", new BranchConfig() { IsReleaseBranch = true, Tag = "rc", } } } }; using (var fixture = new EmptyRepositoryFixture()) { fixture.MakeACommit(); // create a release branch and tag a release fixture.BranchTo("release/0.10.0"); fixture.MakeACommit(); fixture.MakeACommit(); fixture.AssertFullSemver(config, "0.10.0-rc.1+2"); // switch to master and verify the version fixture.Checkout("master"); fixture.MakeACommit(); fixture.AssertFullSemver(config, "0.10.1-pre.1+1"); // create a feature branch from master and verify the version fixture.BranchTo("MyFeatureD"); fixture.AssertFullSemver(config, "0.10.1-MyFeatureD.1+1"); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using FluentAssertions; using Microsoft.Its.Domain.Testing; using Microsoft.Its.Recipes; using NUnit.Framework; using Sample.Domain; using Sample.Domain.Ordering; using System; using System.Reactive.Disposables; using System.Threading.Tasks; namespace Microsoft.Its.Domain.Tests { [TestFixture] public abstract class ReservationServiceTests { private CompositeDisposable disposables; protected abstract void Configure(Configuration configuration, Action onSave = null); protected abstract IEventSourcedRepository<TAggregate> CreateRepository<TAggregate>( Action onSave = null) where TAggregate : class, IEventSourced; private IReservationService CreateReservationService() { return Configuration.Current.ReservationService; } private IReservationQuery CreateReservationQuery() { return Configuration.Current.ReservationQuery(); } [SetUp] public void SetUp() { // disable authorization checks Command<Order>.AuthorizeDefault = (order, command) => true; Command<CustomerAccount>.AuthorizeDefault = (account, command) => true; var configuration = new Configuration(); Configure(configuration); disposables = new CompositeDisposable { ConfigurationContext.Establish(configuration), configuration, VirtualClock.Start() }; } [TearDown] public virtual void TearDown() { disposables.Dispose(); } [Test] public void When_a_command_reserves_a_unique_value_then_a_subsequent_request_by_the_same_owner_succeeds() { // arrange var username = Any.CamelCaseName(5); // act var account1 = new CustomerAccount(); var principal = new Customer { Name = Any.CamelCaseName() }; account1.Apply(new RequestUserName { UserName = username, Principal = principal }); account1.ConfirmSave(); var account2 = new CustomerAccount(); var secondAttempt = account2.Validate(new RequestUserName { UserName = username, Principal = principal }); // assert secondAttempt.ShouldBeValid(); } [Test] public void When_a_command_reserves_a_unique_value_then_a_subsequent_request_by_a_different_owner_fails() { // arrange var username = Any.CamelCaseName(5); // act var account1 = new CustomerAccount(); account1.Apply(new RequestUserName { UserName = username, Principal = new Customer { Name = Any.CamelCaseName() } }); account1.ConfirmSave(); var account2 = new CustomerAccount(); var secondPrincipal = new Customer { Name = Any.CamelCaseName() }; var secondAttempt = account2.Validate(new RequestUserName { UserName = username, Principal = secondPrincipal }); // assert secondAttempt.ShouldBeInvalid(string.Format("The user name {0} is taken. Please choose another.", username)); } [Test] public async Task When_a_value_is_confirmed_then_it_can_be_re_reserved_using_the_same_owner_token_because_idempotency() { // arrange var value = Any.FullName(); var ownerToken = Any.Guid().ToString(); var scope = "default-scope"; var reservationService = CreateReservationService(); await reservationService.Reserve(value, scope, ownerToken); await reservationService.Confirm(value, scope, ownerToken); // act var succeeded = await reservationService.Reserve(value, scope, ownerToken); // assert succeeded.Should().BeTrue("because idempotency"); } [Test] public async Task When_a_value_is_confirmed_then_an_attempt_using_a_different_owner_token_to_reserve_it_again_throws() { // arrange var username = Any.Email(); var ownerToken = Any.Email(); var scope = "default-scope"; var reservationService = CreateReservationService(); await reservationService.Reserve(username, scope, ownerToken); await reservationService.Confirm(username, scope, ownerToken); // act var succeeded = await reservationService.Reserve(username, scope, ownerToken + "!"); // assert succeeded.Should().BeFalse(); } [Test] public async Task A_reservation_cannot_be_confirmed_using_the_wrong_owner_token() { // arrange var value = Any.FullName(); var ownerToken = Any.Guid().ToString(); var scope = "default-scope"; var reservationService = CreateReservationService(); await reservationService.Reserve(value, scope, ownerToken, TimeSpan.FromMinutes(5)); // act var wrongOwnerToken = Any.Guid(); var confirmed = reservationService.Confirm(value, scope, wrongOwnerToken.ToString()).Result; // assert confirmed.Should().BeFalse(); } [Test] public async Task When_Confirm_is_called_for_a_nonexistent_reservation_then_it_returns_false() { var reservationService = CreateReservationService(); var value = await reservationService.Confirm(Any.CamelCaseName(), Any.CamelCaseName(), Any.CamelCaseName()); value.Should().BeFalse(); } [Test] public async Task A_reservation_can_be_cancelled_using_its_owner_token() { // arrange var value = Any.FullName(); var ownerToken = Any.Guid().ToString(); var scope = "default-scope"; var reservationService = CreateReservationService(); await reservationService.Reserve(value, scope, ownerToken, TimeSpan.FromMinutes(5)); // act await reservationService.Cancel( value: value, scope: scope, ownerToken: ownerToken); // assert // check that someone else can now reserve the same value var succeeded = await reservationService.Reserve(value, scope, Any.Guid().ToString(), TimeSpan.FromMinutes(5)); succeeded.Should().BeTrue(); } [Test] public async Task An_attempt_to_cancel_a_reservation_without_the_correct_owner_token_fails() { // arrange var value = Any.FullName(); var ownerToken = Any.Guid().ToString(); var scope = "default-scope"; var reservationService = CreateReservationService(); await reservationService.Reserve(value, scope, ownerToken, TimeSpan.FromMinutes(5)); // act var wrongOwnerToken = Any.Guid().ToString(); var cancelled = reservationService.Cancel(value, scope, wrongOwnerToken).Result; // assert cancelled.Should().BeFalse(); } [Test] public async Task If_a_fixed_quantity_of_resource_had_been_depleted_then_reservations_cant_be_made() { var reservationService = CreateReservationService(); // given a fixed quantity of some resource where the resource has been used var ownerToken = Any.Guid().ToString(); var promoCode = "promo-code-" + Any.Guid(); var reservedValue = Any.Guid().ToString(); var userConfirmationCode = Any.Guid().ToString(); await reservationService.Reserve(reservedValue, promoCode, reservedValue, TimeSpan.FromDays(-1)); //act var result = await reservationService.ReserveAny( scope: promoCode, ownerToken: ownerToken, lease: TimeSpan.FromMinutes(-2), confirmationToken: userConfirmationCode); result.Should().Be(reservedValue); await reservationService.Confirm(userConfirmationCode, promoCode, ownerToken); //assert result = await reservationService.ReserveAny( scope: promoCode, ownerToken: Any.FullName(), lease: TimeSpan.FromMinutes(2), confirmationToken: Any.Guid().ToString()); result.Should().BeNull(); } [Test] public async Task Confirmation_token_cant_be_used_twice_by_different_owners_for_the_same_resource() { var reservationService = CreateReservationService(); // given a fixed quantity of some resource where the resource has been used var word = Any.Word(); var ownerToken = Any.Guid().ToString(); var promoCode = "promo-code-" + word; var reservedValue = Any.Guid().ToString(); var confirmationToken = Any.Guid().ToString(); await reservationService.Reserve(reservedValue, promoCode, reservedValue, TimeSpan.FromDays(-1)); await reservationService.Reserve(Any.Guid().ToString(), promoCode, reservedValue, TimeSpan.FromDays(-1)); //act await reservationService.ReserveAny( scope: promoCode, ownerToken: ownerToken, confirmationToken: confirmationToken); //assert var result = await reservationService.ReserveAny( scope: promoCode, ownerToken: Any.FullName(), lease: TimeSpan.FromMinutes(2), confirmationToken: confirmationToken); result.Should().BeNull(); } [Test] public async Task When_confirmation_token_is_used_twice_for_the_same_unconfirmed_reservation_then_ReserveAny_extends_the_lease() { var reservationService = CreateReservationService(); // given a fixed quantity of some resource where the resource has been used //todo:(this needs to be done via an interface rather then just calling reserve multiple times) var word = Any.Word(); var ownerToken = Any.Guid().ToString(); var promoCode = "promo-code-" + word; var reservedValue = Any.Guid().ToString(); var confirmationToken = Any.Guid().ToString(); await reservationService.Reserve(reservedValue, promoCode, reservedValue, TimeSpan.FromDays(-1)); await reservationService.Reserve(Any.Guid().ToString(), promoCode, reservedValue, TimeSpan.FromDays(-1)); //act var firstAttempt = await reservationService.ReserveAny( scope: promoCode, ownerToken: ownerToken, confirmationToken: confirmationToken); //assert var secondAttempt = await reservationService.ReserveAny( scope: promoCode, ownerToken: ownerToken, lease: TimeSpan.FromMinutes(2), confirmationToken: confirmationToken); secondAttempt.Should() .NotBeNull() .And .Be(firstAttempt); } [Test] public async Task When_ReserveAny_is_called_for_a_scope_that_has_no_entries_at_all_then_it_returns_false() { var reservationService = CreateReservationService(); var value = await reservationService.ReserveAny(Any.CamelCaseName(), Any.CamelCaseName(), TimeSpan.FromMinutes(1)); value.Should().BeNull(); } [Test] public async Task When_a_command_reserves_a_unique_value_but_it_expires_then_a_subsequent_request_by_a_different_actor_succeeds() { // arrange var username = Any.CamelCaseName(5); var scope = "UserName"; await CreateReservationService().Reserve(username, scope, Any.CamelCaseName(), TimeSpan.FromMinutes(30)); // act VirtualClock.Current.AdvanceBy(TimeSpan.FromMinutes(32)); var attempt = new CustomerAccount() .Validate(new RequestUserName { UserName = username, Principal = new Customer { Name = Any.CamelCaseName() } }); // assert attempt.ShouldBeValid(); var reservation = await CreateReservationQuery().GetReservedValue(username, scope); reservation.Expiration.Should().Be(Clock.Now().AddMinutes(1)); } [Test] public async Task Reservations_can_be_placed_for_one_of_a_fixed_quantity_of_a_resource() { var reservationService = CreateReservationService(); // given a fixed quantity of some resource, e.g. promo codes: var ownerToken = "ownerToken-" + Any.Guid(); var promoCode = "promo-code-" + Any.Guid(); var reservedValue = "reservedValue-" + Any.Guid(); var confirmationToken = "userConfirmationCode-" + Any.Guid(); await reservationService.Reserve(reservedValue, promoCode, reservedValue, TimeSpan.FromDays(-1)); //act var result = await reservationService.ReserveAny( scope: promoCode, ownerToken: ownerToken, lease: TimeSpan.FromMinutes(2), confirmationToken: confirmationToken); result.Should().Be(reservedValue); await reservationService.Confirm(confirmationToken, promoCode, ownerToken); // assert var reservation = await CreateReservationQuery().GetReservedValue(reservedValue, promoCode); reservation.Expiration.Should().NotHaveValue(); } [Test] public async Task The_value_returned_by_the_reservation_service_can_be_used_for_confirmation() { var reservationService = CreateReservationService(); // given a fixed quantity of some resource, e.g. promo codes: var ownerToken = "owner-token-" + Any.Email(); var promoCode = "promo-code-" + Any.Guid(); var reservedValue = Any.Email(); await reservationService.Reserve(reservedValue, scope: promoCode, ownerToken: ownerToken, lease: TimeSpan.FromDays(-1)); //act var value = await reservationService.ReserveAny( scope: promoCode, ownerToken: ownerToken, lease: TimeSpan.FromMinutes(2)); value.Should().NotBeNull(); await reservationService.Confirm(value, promoCode, ownerToken); // assert var reservation = await CreateReservationQuery().GetReservedValue(reservedValue, promoCode); reservation.Expiration.Should().NotHaveValue(); reservation.ConfirmationToken.Should().Be(value); } [Test] public async Task When_the_aggregate_is_saved_then_the_reservation_is_confirmed() { // arrange var username = Any.Email(); var account = new CustomerAccount(); account.Apply(new RequestUserName { UserName = username, Principal = new Customer(username) }); Configuration.Current.EventBus.Subscribe(new UserNameConfirmer()); var repository = CreateRepository<CustomerAccount>(); // act await repository.Save(account); // assert var reservation = await CreateReservationQuery().GetReservedValue(username, "UserName"); reservation.Expiration.Should().NotHaveValue(); } } public class UserNameConfirmer : IHaveConsequencesWhen<CustomerAccount.UserNameAcquired> { public void HaveConsequences(CustomerAccount.UserNameAcquired @event) { Configuration.Current.ReservationService.Confirm( @event.UserName, "UserName", @event.UserName).Wait(); } } }
using System; using System.Collections.Generic; using System.Text; using System.Linq; using PlanningPoker.Enums; using Template10.Mvvm; using Windows.UI.Xaml; namespace PlanningPoker.ViewModels { public class SettingsPageViewModel : ViewModelBase { public SettingsPartViewModel SettingsPartViewModel { get; } = new SettingsPartViewModel(); public AboutPartViewModel AboutPartViewModel { get; } = new AboutPartViewModel(); } public class SettingsPartViewModel : ViewModelBase { Services.SettingsServices.SettingsService _settings; /// <summary> /// Initializes a new instance of the <see cref="SettingsPartViewModel" /> class. /// </summary> public SettingsPartViewModel() { if (!Windows.ApplicationModel.DesignMode.DesignModeEnabled) { _settings = Services.SettingsServices.SettingsService.Instance; } } /// <summary> /// Gets or sets the default planning deck. /// </summary> /// <value> /// The default planning deck. /// </value> public PlanningDeck DefaultPlanningDeck { get { return _settings.DefaultPlanningDeck; } set { _settings.DefaultPlanningDeck = value; base.RaisePropertyChanged(); } } /// <summary> /// Gets or sets a value indicating whether [use shell back button]. /// </summary> /// <value> /// <c>true</c> if [use shell back button]; otherwise, <c>false</c>. /// </value> public bool UseShellBackButton { get { return _settings.UseShellBackButton; } set { _settings.UseShellBackButton = value; base.RaisePropertyChanged(); } } /// <summary> /// Gets or sets a value indicating whether [use light theme button]. /// </summary> /// <value> /// <c>true</c> if [use light theme button]; otherwise, <c>false</c>. /// </value> public bool UseLightThemeButton { get { return _settings.AppTheme.Equals(ApplicationTheme.Light); } set { _settings.AppTheme = value ? ApplicationTheme.Light : ApplicationTheme.Dark; base.RaisePropertyChanged(); } } /// <summary> /// Gets or sets a value indicating whether [use automatic hide selected card button]. /// </summary> /// <value> /// <c>true</c> if [use automatic hide selected card button]; otherwise, <c>false</c>. /// </value> public bool UseAutoHideSelectedCardButton { get { return _settings.UseAutoHideSelectedCardButton; } set { _settings.UseAutoHideSelectedCardButton = value; base.RaisePropertyChanged(); } } /// <summary> /// Gets the available planning decks. /// </summary> /// <value> /// The decks. /// </value> public List<PlanningDeck> Decks { get; } = Enum.GetValues(typeof(PlanningDeck)).Cast<PlanningDeck>().ToList<PlanningDeck>(); } public class AboutPartViewModel : ViewModelBase { public Uri Logo => Windows.ApplicationModel.Package.Current.Logo; public string DisplayName => Windows.ApplicationModel.Package.Current.DisplayName; public string Publisher => Windows.ApplicationModel.Package.Current.PublisherDisplayName; public string Version { get { var v = Windows.ApplicationModel.Package.Current.Id.Version; return $"{v.Major}.{v.Minor}.{v.Build}.{v.Revision}"; } } public Uri RateMe => new Uri("ms-windows-store://review/?ProductId=9WZDNCRFK20H"); /// <summary> /// Reviews the this application. /// </summary> public async void ReviewThisApp() { await Windows.System.Launcher.LaunchUriAsync(RateMe); } /// <summary> /// Supports the and feedback. /// </summary> public void SupportAndFeedback() { string emailTo = "[email protected]"; string subject = $"Feedback and Support for '{DisplayName}'"; StringBuilder body = new StringBuilder(); body.AppendLine().AppendLine(); body.AppendLine($"{DisplayName} v{Version}").AppendLine().AppendLine(); ComposeEmail(subject, body.ToString(), emailTo); } /// <summary> /// Shares the this application. /// </summary> public void ShareThisApp() { Uri link = new Uri("https://www.microsoft.com/store/apps/9WZDNCRFK20H/"); string subject = $"Checkout '{DisplayName}' for Windows 10"; StringBuilder body = new StringBuilder(); body.AppendLine(link.ToString()).AppendLine(); ComposeEmail(subject, body.ToString()); } /// <summary> /// Contributes to project. /// </summary> public async void ContributeToProject() { Uri link = new Uri("https://github.com/MaverickDevelopment/Scrum-Planning-Poker"); await Windows.System.Launcher.LaunchUriAsync(link); } /// <summary> /// Composes the email. /// </summary> /// <param name="subject">The subject.</param> /// <param name="body">The body.</param> private async void ComposeEmail(string subject, string body) { ComposeEmail(subject, body, string.Empty); } /// <summary> /// Composes the email. /// </summary> /// <param name="subject">The subject.</param> /// <param name="body">The body.</param> /// <param name="to">To.</param> private async void ComposeEmail(string subject, string body, string to) { //REFERENCE: https://msdn.microsoft.com/en-us/library/windows/apps/xaml/mt269391.aspx var emailMessage = new Windows.ApplicationModel.Email.EmailMessage(); if (!string.IsNullOrWhiteSpace(to)) { var emailRecipient = new Windows.ApplicationModel.Email.EmailRecipient(to); emailMessage.To.Add(emailRecipient); } emailMessage.Subject = subject; emailMessage.Body = body; await Windows.ApplicationModel.Email.EmailManager.ShowComposeNewEmailAsync(emailMessage); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; using System.Collections.Generic; using System.Collections; using Xunit; namespace System.DirectoryServices.Tests { public partial class DirectoryServicesTests { internal static bool IsLdapConfigurationExist => LdapConfiguration.Configuration != null; internal static bool IsActiveDirectoryServer => IsLdapConfigurationExist && LdapConfiguration.Configuration.IsActiveDirectoryServer; [ConditionalFact(nameof(IsLdapConfigurationExist))] public void TestOU() // adding and removing organization unit { using (DirectoryEntry de = CreateRootEntry()) { string ouName = "NetCoreDevs"; // ensure cleanup before doing the creation. DeleteOU(de, ouName); CreateOU(de, ouName, ".Net Core Developers Unit"); try { SearchOUByName(de, ouName); } finally { // Clean up the added ou DeleteOU(de, ouName); } } } [ConditionalFact(nameof(IsLdapConfigurationExist))] public void TestOrganizationalRole() // adding and removing users to/from the ou { using (DirectoryEntry de = CreateRootEntry()) { DeleteOU(de, "CoreFxRootOU"); using (DirectoryEntry rootOU = CreateOU(de, "CoreFxRootOU", "CoreFx Root OU")) { try { DirectoryEntry child1OU = CreateOU(rootOU, "CoreFxChild1OU", "CoreFx Child OU 1"); DirectoryEntry child2OU = CreateOU(rootOU, "CoreFxChild2OU", "CoreFx Child OU 2"); CreateOrganizationalRole(child1OU, "user.ou1.1", "User 1 is in CoreFx ou 1", "1 111 111 1111"); CreateOrganizationalRole(child1OU, "user.ou1.2", "User 2 is in CoreFx ou 1", "1 222 222 2222"); CreateOrganizationalRole(child2OU, "user.ou2.1", "User 1 is in CoreFx ou 2", "1 333 333 3333"); CreateOrganizationalRole(child2OU, "user.ou2.2", "User 2 is in CoreFx ou 2", "1 333 333 3333"); // now let's search for the added data: SearchOUByName(rootOU, "CoreFxChild1OU"); SearchOUByName(rootOU, "CoreFxChild2OU"); SearchOrganizationalRole(child1OU, "user.ou1.1"); SearchOrganizationalRole(child1OU, "user.ou1.2"); SearchOrganizationalRole(child2OU, "user.ou2.1"); SearchOrganizationalRole(child2OU, "user.ou2.2"); } finally { // rootOU.DeleteTree(); doesn't work as getting "A protocol error occurred. (Exception from HRESULT: 0x80072021)" DeleteOU(de, "CoreFxRootOU"); } } } } [ConditionalFact(nameof(IsLdapConfigurationExist))] public void TestPropertyCaching() { using (DirectoryEntry de = CreateRootEntry()) { DeleteOU(de, "CachingOU"); using (DirectoryEntry rootOU = CreateOU(de, "CachingOU", "Caching OU")) { try { using (DirectoryEntry userEntry = CreateOrganizationalRole(rootOU, "caching.user.1", "User 1 in caching OU", "1 111 111 1111")) { Assert.True(userEntry.UsePropertyCache); SearchOrganizationalRole(rootOU, "caching.user.1"); string originalPhone = (string) userEntry.Properties["telephoneNumber"].Value; string newPhone = "1 222 222 2222"; userEntry.Properties["telephoneNumber"].Value = newPhone; using (DirectoryEntry sameUserEntry = GetOrganizationalRole(rootOU, "caching.user.1")) { Assert.Equal(originalPhone, (string) sameUserEntry.Properties["telephoneNumber"].Value); } userEntry.CommitChanges(); using (DirectoryEntry sameUserEntry = GetOrganizationalRole(rootOU, "caching.user.1")) { Assert.Equal(newPhone, (string) sameUserEntry.Properties["telephoneNumber"].Value); } userEntry.UsePropertyCache = false; Assert.False(userEntry.UsePropertyCache); userEntry.Properties["telephoneNumber"].Value = originalPhone; using (DirectoryEntry sameUserEntry = GetOrganizationalRole(rootOU, "caching.user.1")) { Assert.Equal(originalPhone, (string) sameUserEntry.Properties["telephoneNumber"].Value); } } } finally { DeleteOU(de, "CachingOU"); } } } } [ConditionalFact(nameof(IsLdapConfigurationExist))] public void TestMoveTo() { using (DirectoryEntry de = CreateRootEntry()) { DeleteOU(de, "MoveingOU"); try { using (DirectoryEntry rootOU = CreateOU(de, "MoveingOU", "Moving Root OU")) { using (DirectoryEntry fromOU = CreateOU(rootOU, "MoveFromOU", "Moving From OU")) using (DirectoryEntry toOU = CreateOU(rootOU, "MoveToOU", "Moving To OU")) { DirectoryEntry user = CreateOrganizationalRole(fromOU, "user.move.1", "User to move across OU's", "1 111 111 1111"); SearchOrganizationalRole(fromOU, "user.move.1"); user.MoveTo(toOU); user.CommitChanges(); SearchOrganizationalRole(toOU, "user.move.1"); Assert.Throws<DirectoryServicesCOMException>(() => SearchOrganizationalRole(fromOU, "user.move.1")); user.MoveTo(fromOU, "cn=user.moved.1"); user.CommitChanges(); SearchOrganizationalRole(fromOU, "user.moved.1"); Assert.Throws<DirectoryServicesCOMException>(() => SearchOrganizationalRole(fromOU, "user.move.1")); Assert.Throws<DirectoryServicesCOMException>(() => SearchOrganizationalRole(toOU, "user.move.1")); Assert.Throws<DirectoryServicesCOMException>(() => user.MoveTo(toOU, "user.move.2")); } } } finally { DeleteOU(de, "MoveingOU"); } } } [ConditionalFact(nameof(IsLdapConfigurationExist))] public void TestCopyTo() { using (DirectoryEntry de = CreateRootEntry()) { DeleteOU(de, "CopyingOU"); try { using (DirectoryEntry rootOU = CreateOU(de, "CopyingOU", "Copying Root OU")) { using (DirectoryEntry fromOU = CreateOU(rootOU, "CopyFromOU", "Copying From OU")) using (DirectoryEntry toOU = CreateOU(rootOU, "CopyToOU", "Copying To OU")) { DirectoryEntry user = CreateOrganizationalRole(fromOU, "user.move.1", "User to copy across OU's", "1 111 111 1111"); SearchOrganizationalRole(fromOU, "user.move.1"); // The Lightweight Directory Access Protocol (LDAP) provider does not currently support the CopyTo(DirectoryEntry) method. Assert.Throws<NotImplementedException>(() => user.CopyTo(toOU)); Assert.Throws<NotImplementedException>(() => user.CopyTo(toOU, "user.move.2")); } } } finally { DeleteOU(de, "CopyingOU"); } } } [ConditionalFact(nameof(IsLdapConfigurationExist))] public void TestRename() { using (DirectoryEntry de = CreateRootEntry()) { DeleteOU(de, "RenamingOU"); try { using (DirectoryEntry rootOU = CreateOU(de, "RenamingOU", "Renaming Root OU")) { DirectoryEntry user = CreateOrganizationalRole(rootOU, "user.before.rename", "User to rename", "1 111 111 1111"); SearchOrganizationalRole(rootOU, "user.before.rename"); user.Rename("cn=user.after.rename"); user.CommitChanges(); Assert.Throws<DirectoryServicesCOMException>(() => SearchOrganizationalRole(rootOU, "user.before.rename")); SearchOrganizationalRole(rootOU, "user.after.rename"); Assert.Throws<DirectoryServicesCOMException>(() => user.Rename("user.after.after.rename")); } } finally { DeleteOU(de, "RenamingOU"); } } } [ConditionalFact(nameof(IsLdapConfigurationExist))] public void TestParent() { using (DirectoryEntry de = CreateRootEntry()) { DeleteOU(de, "GrandParent"); try { using (DirectoryEntry grandOU = CreateOU(de, "GrandParent", "Grand Parent OU")) using (DirectoryEntry parentOU = CreateOU(grandOU, "Parent", "Parent OU")) using (DirectoryEntry childOU = CreateOU(parentOU, "Child", "Child OU")) { SearchOUByName(de, "GrandParent"); SearchOUByName(grandOU, "Parent"); SearchOUByName(parentOU, "Child"); Assert.Equal(de.Name, grandOU.Parent.Name); Assert.Equal(grandOU.Name, parentOU.Parent.Name); Assert.Equal(parentOU.Name, childOU.Parent.Name); } } finally { DeleteOU(de, "GrandParent"); } } } [ConditionalFact(nameof(IsLdapConfigurationExist))] public void TestDeleteTree() { using (DirectoryEntry de = CreateRootEntry()) { DeleteOU(de, "RootToDelete"); try { using (DirectoryEntry rootOU = CreateOU(de, "RootToDelete", "Root OU")) using (DirectoryEntry childOU = CreateOU(rootOU, "Child1", "Root Child 1 OU")) using (DirectoryEntry anotherChildOU = CreateOU(rootOU, "Child2", "Root Child 2 OU")) using (DirectoryEntry grandChildOU = CreateOU(childOU, "GrandChild", "Grand Child OU")) using (DirectoryEntry user1 = CreateOrganizationalRole(grandChildOU, "user.grandChild.1", "Grand Child User", "1 111 111 1111")) using (DirectoryEntry user2 = CreateOrganizationalRole(grandChildOU, "user.grandChild.2", "Grand Child User", "1 222 222 2222")) { SearchOUByName(de, "RootToDelete"); SearchOUByName(rootOU, "Child1"); SearchOUByName(rootOU, "Child2"); SearchOUByName(childOU, "GrandChild"); SearchOrganizationalRole(grandChildOU, "user.grandChild.1"); if (LdapConfiguration.Configuration.IsActiveDirectoryServer) { rootOU.DeleteTree(); Assert.Throws<DirectoryServicesCOMException>(() => SearchOUByName(de, "RootToDelete")); Assert.Throws<DirectoryServicesCOMException>(() => SearchOUByName(rootOU, "Child1")); Assert.Throws<DirectoryServicesCOMException>(() => SearchOUByName(rootOU, "Child2")); Assert.Throws<DirectoryServicesCOMException>(() => SearchOUByName(childOU, "GrandChild")); Assert.Throws<DirectoryServicesCOMException>(() => SearchOrganizationalRole(grandChildOU, "user.grandChild.1")); } else { // on non Active Directory Servers, DeleteTree() throws DirectoryServicesCOMException : A protocol error occurred. (Exception from HRESULT: 0x80072021) Assert.Throws<DirectoryServicesCOMException>(() => rootOU.DeleteTree()); } } } finally { DeleteOU(de, "RootToDelete"); } } } [ConditionalFact(nameof(IsLdapConfigurationExist))] public void TestInvalidServerPath() { using (DirectoryEntry de = new DirectoryEntry("SomeWrongPath")) { Assert.Throws<COMException>(() => { foreach (var e in de.Children) {} } ); using (DirectorySearcher ds = new DirectorySearcher(de)) { ds.Filter = $"(objectClass=*)"; Assert.Throws<COMException>(() => ds.FindAll() ); } } } [ConditionalFact(nameof(IsLdapConfigurationExist))] public void TestMissingUserAndPasswordInfo() { using (DirectoryEntry de = new DirectoryEntry(LdapConfiguration.Configuration.LdapPath)) { CheckSpecificException(() => { foreach (var e in de.Children) {} } ); using (DirectorySearcher ds = new DirectorySearcher(de)) { ds.Filter = $"(objectClass=*)"; CheckSpecificException(() => ds.FindAll()); } } } [ConditionalFact(nameof(IsLdapConfigurationExist))] public void TestInvalidUserAndPassword() { using (DirectoryEntry de = new DirectoryEntry(LdapConfiguration.Configuration.LdapPath, "wrongUser", "wrongPassword")) { CheckSpecificException(() => { foreach (var e in de.Children) {} }); using (DirectorySearcher ds = new DirectorySearcher(de)) { ds.Filter = $"(objectClass=*)"; CheckSpecificException(() => ds.FindAll() ); } } using (DirectoryEntry de = new DirectoryEntry( LdapConfiguration.Configuration.LdapPath, LdapConfiguration.Configuration.UserName, "wrongPassword" )) { CheckSpecificException(() => { foreach (var e in de.Children) {} } ); using (DirectorySearcher ds = new DirectorySearcher(de)) { ds.Filter = $"(objectClass=*)"; CheckSpecificException(() => ds.FindAll() ); } } } [ConditionalFact(nameof(IsLdapConfigurationExist))] public void TestInvalidSearchFilter() { using (DirectoryEntry de = new DirectoryEntry( LdapConfiguration.Configuration.LdapPath, LdapConfiguration.Configuration.UserName, "wrongPassword" )) { using (DirectorySearcher ds = new DirectorySearcher(de)) { ds.Filter = $"(objectClass=*))"; // invalid search filter CheckSpecificException(() => ds.FindOne() ); } } } [ConditionalFact(nameof(IsLdapConfigurationExist))] public void TestUnAllowedProperty() { using (DirectoryEntry de = CreateRootEntry()) { DeleteOU(de, "NegativeRoot"); try { using (DirectoryEntry rootOU = CreateOU(de, "NegativeRoot", "Negative Test Root OU")) { DirectoryEntry entry = rootOU.Children.Add($"cn=MyNamedObject","Class"); entry.Properties["objectClass"].Value = "namedObject"; entry.Properties["cn"].Value = "MyNamedObject"; entry.Properties["description"].Value = "description"; // description is not allowed in the schema Assert.Throws<DirectoryServicesCOMException>(() => entry.CommitChanges()); } } finally { DeleteOU(de, "NegativeRoot"); } } } [ConditionalFact(nameof(IsLdapConfigurationExist))] public void TestSearch() { using (DirectoryEntry de = CreateRootEntry()) { DeleteOU(de, "SearchRoot"); try { using (DirectoryEntry rootOU = CreateOU(de, "SearchRoot", "Root OU")) using (DirectoryEntry childOU = CreateOU(rootOU, "Search.Child1", "Root Child 1 OU")) using (DirectoryEntry anotherChildOU = CreateOU(rootOU, "Search.Child2", "Root Child 2 OU")) using (DirectoryEntry grandChildOU = CreateOU(childOU, "Search.GrandChild", "Grand Child OU")) using (DirectoryEntry user1 = CreateOrganizationalRole(grandChildOU, "user.search.grandChild.1", "Grand Child User", "1 111 111 1111")) using (DirectoryEntry user2 = CreateOrganizationalRole(grandChildOU, "user.search.grandChild.2", "Grand Child User", "1 222 222 2222")) { user1.Properties["postalCode"].Value = 98052; user1.Properties["postalAddress"].Value = "12345 SE 1st Street, City1, State1"; user1.CommitChanges(); user2.Properties["postalCode"].Value = 98088; user2.Properties["postalAddress"].Value = "67890 SE 2nd Street, City2, State2"; user2.CommitChanges(); using (DirectorySearcher ds = new DirectorySearcher(rootOU)) { ds.ClientTimeout = new TimeSpan(0, 2, 0); ds.Filter = "(objectClass=organizationalUnit)"; Assert.Equal(4, ds.FindAll().Count); ds.Filter = "(objectClass=organizationalRole)"; Assert.Equal(2, ds.FindAll().Count); ds.Filter = "(ou=SearchRoot)"; Assert.Equal(1, ds.FindAll().Count); ds.Filter = "(ou=Search.Child1)"; Assert.Equal(1, ds.FindAll().Count); ds.Filter = "(ou=Search.Child2)"; Assert.Equal(1, ds.FindAll().Count); ds.Filter = "(ou=Search.GrandChild)"; Assert.Equal(1, ds.FindAll().Count); ds.Filter = "(description=Grand Child OU)"; Assert.Equal(1, ds.FindAll().Count); ds.Filter = "(description=*)"; Assert.Equal(6, ds.FindAll().Count); ds.Filter = "(&(description=*)(objectClass=organizationalUnit))"; Assert.Equal(4, ds.FindAll().Count); ds.Filter = "(&(description=*)(objectClass=organizationalRole))"; Assert.Equal(2, ds.FindAll().Count); ds.Filter = "(&(description=No Description)(objectClass=organizationalRole))"; Assert.Equal(0, ds.FindAll().Count); ds.Filter = "(postalCode=*)"; Assert.Equal(2, ds.FindAll().Count); ds.Filter = "(postalCode=98052)"; Assert.Equal(1, ds.FindAll().Count); SearchResult sr = ds.FindOne(); Assert.Equal("98052", sr.Properties["postalCode"][0]); ds.Filter = "(postalCode=98088)"; Assert.Equal(1, ds.FindAll().Count); sr = ds.FindOne(); Assert.Equal("98088", sr.Properties["postalCode"][0]); } } } finally { DeleteOU(de, "SearchRoot"); } } } [ConditionalFact(nameof(IsLdapConfigurationExist))] public void TestAttributesWithDifferentTypes() { // Windows server looks not supporting extensibleObject. // It throw exception with the message "The specified directory service attribute or value does not exist." if (IsActiveDirectoryServer) return; using (DirectoryEntry de = CreateRootEntry()) { DeleteOU(de, "AttributesRoot"); try { using (DirectoryEntry rootOU = CreateOU(de, "AttributesRoot", "Attributes Root OU")) { DirectoryEntry cnEntry = rootOU.Children.Add($"cn=CustomUser","Class"); cnEntry.Properties["objectClass"].Value = new string [] { "extensibleObject", "organizationalRole" }; cnEntry.Properties["cn"].Value = "CustomUser"; cnEntry.Properties["description"].Value = "Some Custom User"; cnEntry.Properties["telephoneNumber"].Value = "1 111 111 11111"; cnEntry.Properties["changeNumber"].Value = 101; cnEntry.Properties["deleteOldRDN"].Value = true; cnEntry.CommitChanges(); using (DirectorySearcher ds = new DirectorySearcher(de)) { ds.ClientTimeout = new TimeSpan(0, 2, 0); ds.Filter = $"(cn=CustomUser)"; SearchResult sr = ds.FindOne(); if (sr == null) { throw new DirectoryServicesCOMException($"Couldn't find CustomUser in the entry {de.Name}"); } Assert.Equal((object)true, sr.Properties["deleteOldRDN"][0]); Assert.Equal(101, sr.Properties["changeNumber"][0]); Assert.Equal("Some Custom User", sr.Properties["description"][0]); Assert.Equal("1 111 111 11111", sr.Properties["telephoneNumber"][0]); } } } finally { DeleteOU(de, "AttributesRoot"); } } } private void CheckSpecificException(Action blockToExecute) { Exception exception = Record.Exception(blockToExecute); Assert.NotNull(exception); if (IsActiveDirectoryServer) Assert.IsType<DirectoryServicesCOMException>(exception); else Assert.IsType<COMException>(exception); } private DirectoryEntry CreateOU(DirectoryEntry de, string ou, string description) { DirectoryEntry ouCoreDevs = de.Children.Add($"ou={ou}","Class"); ouCoreDevs.Properties["objectClass"].Value = "organizationalUnit"; // has to be organizationalUnit ouCoreDevs.Properties["description"].Value = description; ouCoreDevs.Properties["ou"].Value = ou; ouCoreDevs.CommitChanges(); return ouCoreDevs; } private DirectoryEntry CreateOrganizationalRole(DirectoryEntry ouEntry, string cn, string description, string phone) { DirectoryEntry cnEntry = ouEntry.Children.Add($"cn={cn}","Class"); cnEntry.Properties["objectClass"].Value = "organizationalRole"; cnEntry.Properties["cn"].Value = cn; cnEntry.Properties["description"].Value = description; cnEntry.Properties["ou"].Value = ouEntry.Name; cnEntry.Properties["telephoneNumber"].Value = phone; cnEntry.CommitChanges(); return cnEntry; } private void DeleteOU(DirectoryEntry parentDe, string ou) { try { // We didn't use DirectoryEntry.DeleteTree as it fails on OpenDJ with "A protocol error occurred. (Exception from HRESULT: 0x80072021)" // Also on AD servers DirectoryEntry.Children.Remove(de) will fail if the de is not a leaf entry. so we had to do it recursively. DirectoryEntry de = parentDe.Children.Find($"ou={ou}"); DeleteDirectoryEntry(parentDe, de); } catch { // ignore the error if the test failed early and couldn't create the OU we are trying to delete } } private void DeleteDirectoryEntry(DirectoryEntry parent, DirectoryEntry de) { foreach (DirectoryEntry child in de.Children) { DeleteDirectoryEntry(de, child); } parent.Children.Remove(de); parent.CommitChanges(); } private void SearchOUByName(DirectoryEntry de, string ouName) { using (DirectorySearcher ds = new DirectorySearcher(de)) { ds.ClientTimeout = new TimeSpan(0, 2, 0); ds.Filter = $"(&(objectClass=organizationalUnit)(ou={ouName}))"; ds.PropertiesToLoad.Add("ou"); SearchResult sr = ds.FindOne(); if (sr == null) { throw new DirectoryServicesCOMException($"Couldn't find {ouName} in the entry {de.Name}"); } Assert.Equal(ouName, sr.Properties["ou"][0]); } } private void SearchOrganizationalRole(DirectoryEntry de, string cnName) { using (DirectorySearcher ds = new DirectorySearcher(de)) { ds.ClientTimeout = new TimeSpan(0, 2, 0); ds.Filter = $"(&(objectClass=organizationalRole)(cn={cnName}))"; ds.PropertiesToLoad.Add("cn"); SearchResult sr = ds.FindOne(); if (sr == null) { throw new DirectoryServicesCOMException($"Couldn't find {cnName} in the entry {de.Name}"); } Assert.Equal(cnName, sr.Properties["cn"][0]); } } private DirectoryEntry GetOrganizationalRole(DirectoryEntry de, string cnName) { using (DirectorySearcher ds = new DirectorySearcher(de)) { ds.ClientTimeout = new TimeSpan(0, 2, 0); ds.Filter = $"(&(objectClass=organizationalRole)(cn={cnName}))"; ds.PropertiesToLoad.Add("cn"); SearchResult sr = ds.FindOne(); return sr.GetDirectoryEntry(); } } private DirectoryEntry CreateRootEntry() { return new DirectoryEntry(LdapConfiguration.Configuration.LdapPath, LdapConfiguration.Configuration.UserName, LdapConfiguration.Configuration.Password, LdapConfiguration.Configuration.AuthenticationTypes); } } }
// =========================================================== // Copyright (c) 2014-2015, Enrico Da Ros/kendar.org // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // =========================================================== using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using CoroutinesLib.Shared; using CoroutinesLib.TestHelpers; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; namespace CoroutinesLib.Test { [TestClass] public class CoroutinesManagerTest_Waiting { #region Coroutines waiting public IEnumerable<ICoroutineResult> WaitAndReturnSingleValue(int waitCount) { while (waitCount > 0) { yield return CoroutineResult.Wait; waitCount--; } yield return CoroutineResult.Return("RESULT"); } public string _coroutineSingleResult; public IEnumerable<ICoroutineResult> CoroutineWaitingForSingleResult(int waitCount = 1) { string result = null; yield return CoroutineResult.Wait; yield return CoroutineResult.RunAndGetResult(WaitAndReturnSingleValue(waitCount),"WaitAndReturnSingleValue") .OnComplete<string>((r) => { result = r; }).AndWait(); _coroutineSingleResult = result; } public IEnumerable<ICoroutineResult> ReturnSeveralItemsAndWaitInBetween(int waitCount) { int results = 0; while (waitCount > 0) { yield return CoroutineResult.Wait; yield return CoroutineResult.YieldReturn(results); waitCount--; results++; } } public int _coroutineResultsCount; public int _partialCoroutineResultsCount; public bool _completed = false; public IEnumerable<ICoroutineResult> CoroutineWaitingForSeveralItems(int waitCount = 1) { _coroutineResultsCount = 0; _completed = false; var result = 0; yield return CoroutineResult.Wait; yield return CoroutineResult.ForEachItem(ReturnSeveralItemsAndWaitInBetween(waitCount),"ReturnSeveralItemsAndWaitInBetween") .Do((r) => { Console.Write(" _"); _partialCoroutineResultsCount++; result++; return true; }) .OnComplete(() => { Console.WriteLine(" X"); _completed = true; }) .WithTimeout(TimeSpan.FromDays(10)) .AndWait(); Console.WriteLine("U"); if (_completed) _coroutineResultsCount = result; } [TestMethod] public void ItShouldBePossibleToWaitForCoroutineCallingFunctionThatWait() { var coroutine = new Mock<ICoroutineThread>(); coroutine.Setup(a => a.Execute()) .Returns(CoroutineWaitingForSingleResult(10)); var target = new CoroutinesManager(); target.TestInitialize(); target.StartCoroutine(coroutine.Object); target.TestRun(20); Assert.AreEqual("RESULT", _coroutineSingleResult); } [TestMethod] public void ItShouldBePossibleToWaitForEnEntireForEach() { _completed = false; var coroutine = new Mock<ICoroutineThread>(); coroutine.Setup(a => a.Execute()) .Returns(CoroutineWaitingForSeveralItems(10)); var target = new CoroutinesManager(); target.TestInitialize(); target.StartCoroutine(coroutine.Object); target.TestRun(3); //Initialize the call target.TestRun(20); //Set results Assert.AreEqual(10, _partialCoroutineResultsCount); Assert.IsTrue(_completed); target.TestRun(2); //Copy the completed Assert.AreEqual(10, _coroutineResultsCount); } [TestMethod] public void WaitForTaskToComplete() { const int waitTime = 100; var coroutine = new Mock<ICoroutineThread>(); coroutine.Setup(a => a.Execute()) .Returns(CoroutineWaitingForTask(waitTime)); var target = new CoroutinesManager(); target.TestInitialize(); var rft = new RunnerForTest(target); target.StartCoroutine(coroutine.Object); target.TestRun(); //Initialize rft.RunCycleFor(waitTime*2); target.TestRun(); //CleanUp Assert.IsTrue(_taskStarted); Assert.IsTrue(_taskRun); Assert.IsTrue(_completed); } private bool _taskRun; private bool _taskStarted; public IEnumerable<ICoroutineResult> CoroutineWaitingForTask(int wait = 100) { _taskRun = false; _taskStarted = false; _completed = false; var completed = false; yield return CoroutineResult.Wait; yield return CoroutineResult.RunTask(Task.Factory.StartNew(() => { _taskStarted = true; Thread.Sleep(wait); _taskRun = true; }),"CoroutineWaitingForTask") .OnComplete(() => { completed = true; }).AndWait(); if (completed) _completed = true; } public IEnumerable<ICoroutineResult> CoroutineWaitingHavingTimeout() { _taskRun = false; _taskStarted = false; _completed = false; var completed = false; yield return CoroutineResult.Wait; yield return CoroutineResult.RunTask(Task.Factory.StartNew(() => { _taskStarted = true; Thread.Sleep(300); _taskRun = true; }),"CoroutineWaitingForTask") .OnComplete(() => { completed = true; }) .WithTimeout(10) .AndWait(); if (completed) _completed = true; } [TestMethod] public void ItShouldBePossibleToWaitForATaskToCompleteWithTimeoutError() { var coroutine = new Mock<ICoroutineThread>(); coroutine.Setup(a => a.Execute()) .Returns(CoroutineWaitingHavingTimeout()); coroutine.Setup(o => o.OnError(It.IsAny<Exception>())).Returns(true); var target = new CoroutinesManager(); target.TestInitialize(); var rft = new RunnerForTest(target); target.StartCoroutine(coroutine.Object); target.TestRun(); rft.RunCycleFor(200); target.TestRun(); Assert.IsTrue(_taskStarted); Assert.IsFalse(_taskRun); coroutine.Verify(a => a.OnError(It.IsAny<Exception>()), Times.Once); } public IEnumerable<ICoroutineResult> CoroutineWaitingHavingTimeoutNotExploding() { _taskRun = false; _taskStarted = false; _completed = false; var completed = false; yield return CoroutineResult.Wait; yield return CoroutineResult.RunTask(Task.Factory.StartNew(() => { _taskStarted = true; Thread.Sleep(100); _taskRun = true; }),"CoroutineWaitingHavingTimeoutNotExploding") .OnComplete(() => { completed = true; }) .WithTimeout(1000) .AndWait(); if (completed) _completed = true; } [TestMethod] public void ItShouldBePossibleToWaitForATaskToCompleteWithinTimeout() { _taskStarted = false; _taskRun = false; _completed = false; var coroutine = new Mock<ICoroutineThread>(); coroutine.Setup(a => a.Execute()) .Returns(CoroutineWaitingHavingTimeoutNotExploding()); var target = new CoroutinesManager(); target.TestInitialize(); var rft = new RunnerForTest(target); target.StartCoroutine(coroutine.Object); target.TestRun(); rft.RunCycleFor(200); target.TestRun(); Assert.IsTrue(_taskStarted); Assert.IsTrue(_taskRun); Assert.IsTrue(_completed); coroutine.Verify(a => a.OnError(It.IsAny<Exception>()), Times.Never); } #endregion } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Globalization; using System.Net; using System.Runtime.InteropServices; using Microsoft.Win32; using OpenLiveWriter.Interop.Windows; namespace OpenLiveWriter.CoreServices { /// <summary> /// Class the holds information about a Urls content type. /// </summary> public class UrlContentTypeInfo { public UrlContentTypeInfo(string contentType, string url) : this(contentType, null, url, -1) { } public UrlContentTypeInfo(string contentType, string contentEncoding, string url, int contentLength) { m_contentType = contentType; m_contentEncoding = contentEncoding; m_url = url; _contentLength = contentLength; } /// <summary> /// The content type of the given Url /// </summary> public string ContentType { get { return m_contentType; } } private string m_contentType; /// <summary> /// The Url (after redirects) that actually provided the content type information /// </summary> public string FinalUrl { get { return m_url; } } private string m_url; /// <summary> /// The content encoding provided for this url (if known). /// </summary> public string ContentEncoding { get { return m_contentEncoding; } } private string m_contentEncoding; /// <summary> /// The content length provided for the url (if known). /// </summary> public int ContentLength { get { return _contentLength; } } private int _contentLength = -1; } /// <summary> /// Helper for determining and using content type information /// </summary> public class ContentTypeHelper { /// <summary> /// Determine the content type of a URL using only inexpensive operations like looking /// in the cache or guessing based upon extension. This may not always return /// the correct content type, especially for redirected URLs. /// </summary> /// <param name="url">The url for which to check content type</param> /// <returns>The content type</returns> public static UrlContentTypeInfo InexpensivelyGetUrlContentType(string url) { UrlContentTypeInfo contentTypeInfo = null; contentTypeInfo = GetContentTypeFromBrowserCache(url); if (contentTypeInfo == null) { string contentType = GuessContentTypeLocally(url); contentTypeInfo = new UrlContentTypeInfo(contentType, url); } return contentTypeInfo; } /// <summary> /// Determine the content type of a URL using inexpensive operations as well as /// potentially using network IO to determine content type. This will return the /// correct content type. /// </summary> /// <param name="url">The url for which to check content type</param> /// <returns>The content type</returns> public static UrlContentTypeInfo ExpensivelyGetUrlContentType(string url) { return ExpensivelyGetUrlContentType(url, -1); } /// <summary> /// Determine the content type of a URL using inexpensive operations as well as /// potentially using network IO to determine content type. This will return the /// correct content type. /// </summary> /// <param name="url">The url for which to check content type</param> /// <param name="timeOutMs">MS to execute before timing out</param> /// <returns>The content type</returns> public static UrlContentTypeInfo ExpensivelyGetUrlContentType(string url, int timeOutMs) { string contentType = null; UrlContentTypeInfo urlContentTypeInfo = null; // If the url ends with a pdf, treat it as a PDF file no matter what the server says! if (UrlHelper.GetExtensionForUrl(url) == ".pdf") { contentType = GuessContentTypeLocally(url); return new UrlContentTypeInfo(contentType, url); } urlContentTypeInfo = GetContentTypeFromBrowserCache(url); if (urlContentTypeInfo != null) return urlContentTypeInfo; urlContentTypeInfo = GetContentTypeUsingNetworkIO(url, timeOutMs); if (urlContentTypeInfo != null) return urlContentTypeInfo; contentType = GuessContentTypeLocally(url); if (contentType != null) return new UrlContentTypeInfo(contentType, url); return null; } /// <summary> /// Looks up the content type in browser cache /// </summary> /// <param name="url">The url for which to check content type</param> /// <returns>The content type</returns> private static UrlContentTypeInfo GetContentTypeFromBrowserCache(string url) { UrlContentTypeInfo contentType = null; // throw out the query string and other bits of the url, if we can if (UrlHelper.IsUrl(url)) { Uri uri = new Uri(url); // by using the absolute uri, we're more likely to hit the cache url = UrlHelper.SafeToAbsoluteUri(uri); } // Get the header for this URL out of the cache and see if we // can get the content type out of the header Internet_Cache_Entry_Info info; if (WinInet.GetUrlCacheEntryInfo(url, out info)) { // Get the header string for the info struct string header = Marshal.PtrToStringAnsi(info.lpHeaderInfo); // scan through the lines until we find the content type line if (header != null) { string contentTypeString = null; string contentLengthString = null; string contentEncodingString = null; string[] lines = header.Split('\n'); foreach (string line in lines) { if (line.IndexOf(":", StringComparison.OrdinalIgnoreCase) > -1) { string[] parts = line.Split(':'); if (parts[0].ToUpperInvariant() == "CONTENT-TYPE") { // be aware the character encoding can be appended to the end of this line // following a semicolon if (parts[0].IndexOf(";", StringComparison.OrdinalIgnoreCase) > -1) { string[] subParts = parts[0].Split(';'); contentTypeString = subParts[0].Trim(); contentEncodingString = subParts[1].Trim(); } else contentTypeString = parts[1].Trim(); } else if (parts[0].ToUpperInvariant() == "CONTENT-LENGTH") { contentLengthString = parts[1].Trim(); } if (contentTypeString != null && contentLengthString != null) break; } } contentType = new UrlContentTypeInfo(contentTypeString, contentEncodingString, url, int.Parse(contentLengthString, CultureInfo.InvariantCulture)); } } return contentType; } /// <summary> /// Guesses the content type using the URL's extension. This is easily fooled by redirected /// URLs, so should only be used as a last resort. /// </summary> /// <param name="url">The url for which to check content type</param> /// <returns>The content type</returns> private static string GuessContentTypeLocally(string url) { string contentType = null; string extension = UrlHelper.GetExtensionForUrl(url); if (extension != string.Empty) { // If that didn't work, let's try looking up based upon extension using (RegistryKey key = Registry.ClassesRoot.OpenSubKey(extension)) { if (key != null) contentType = (string)key.GetValue("Content Type"); } } // If we couldn't figure it out from the registry, guess if (contentType == null) contentType = GuessContentType(url); return contentType; } /// <summary> /// Guess the content type from looking at the extension of a URL /// </summary> /// <param name="url">The url from which to guess</param> /// <returns>The content type</returns> private static string GuessContentType(string url) { string contentType = null; bool isFileUrl = UrlHelper.IsFileUrl(url); switch (UrlHelper.GetExtensionForUrl(url).ToUpperInvariant()) { case(".HTM"): case(".HTML"): case(".JSP"): case(".ASP"): case(".ASPX"): case(".CFM"): case(".DBM"): case(".PHP"): case(".PL"): case(".SHTML"): contentType = MimeHelper.TEXT_HTML; break; case(".DLL"): if (isFileUrl) contentType = MimeHelper.APP_OCTET_STREAM; else contentType = MimeHelper.TEXT_HTML; break; // if it has no extension, but is a url, its probably a page. case(""): if (url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) { contentType = MimeHelper.TEXT_HTML; } else if (UrlHelper.IsUrl(url) && !UrlHelper.IsFileUrl(url)) { contentType = MimeHelper.APP_OCTET_STREAM; } else contentType = MimeHelper.CONTENTTYPE_UNKNOWN; break; case(".AVI"): case(".MPG"): case(".MPEG"): case(".M3U"): case(".PLS"): case(".MOV"): case(".SWF"): case(".DOC"): case(".XLS"): case(".PPT"): case(".PDF"): case(".RM"): case(".RA"): case(".RAM"): case(".RMVB"): case(".RP"): case(".RT"): case(".ZIP"): case(".EXE"): case(".MHT"): case(".URL"): case(".CFS"): case(".LNK"): case(".MP4"): case(".SMI"): case(".SMIL"): case(".CSS"): case(".ASX"): case(".ASF"): case(".MP3"): case(".PS"): case(".RTF"): case(".WAX"): case(".WVX"): case(".WMA"): case(".AU"): case(".WAV"): case(".AIF"): case(".AIFF"): case(".AIFC"): case(".IEF"): case(".SND"): case(".WMV"): contentType = MimeHelper.APP_OCTET_STREAM; break; case(".JPG"): case(".JPEG"): contentType = MimeHelper.IMAGE_JPG; break; case(".GIF"): contentType = MimeHelper.IMAGE_GIF; break; case(".PNG"): contentType = MimeHelper.IMAGE_PNG; break; case(".BMP"): contentType = MimeHelper.IMAGE_BMP; break; case(".TIF"): contentType = MimeHelper.IMAGE_TIF; break; case("ICO"): contentType = MimeHelper.IMAGE_ICON; break; case(".TXT"): contentType = MimeHelper.TEXT_PLAIN; break; default: // If its a local file, guess that its a file if we don't already know that if (UrlHelper.IsUrl(url) && new Uri(url).IsFile) contentType = MimeHelper.APP_OCTET_STREAM; else contentType = MimeHelper.TEXT_HTML; break; } return contentType; } /// <summary> /// Retrieve the content type by requesting the content type from the server hosting the URL /// </summary> /// <param name="url">The url for which to check content type</param> /// <param name="timeOutMs">The duration in MS that the operation will execute before failing</param> /// <returns>The content type</returns> private static UrlContentTypeInfo GetContentTypeUsingNetworkIO(string url, int timeOutMs) { UrlContentTypeInfo contentType = null; if (UrlHelper.IsFileUrl(url)) { string content = GuessContentTypeLocally(url); if (content != null) contentType = new UrlContentTypeInfo(content, url); } if (contentType == null) { WebRequestWithCache webRequest = new WebRequestWithCache(url); WebResponse response; if (timeOutMs == -1) response = webRequest.GetHeadOnly(); else response = webRequest.GetHeadOnly(timeOutMs); if (response != null && response.ContentType != null && response.ContentType != string.Empty) { string contentTypeString = response.ContentType; string contentEncodingString = null; if (contentTypeString.IndexOf(";", StringComparison.OrdinalIgnoreCase) > 0) { string[] contentTypeParts = contentTypeString.Split(';'); contentTypeString = contentTypeParts[0]; contentEncodingString = contentTypeParts[1]; } contentType = new UrlContentTypeInfo(contentTypeString, contentEncodingString, UrlHelper.SafeToAbsoluteUri(response.ResponseUri), Convert.ToInt32(response.ContentLength)); } } return contentType; } } }
// // Authors: // Christian Hergert <[email protected]> // Ben Motmans <[email protected]> // // Copyright (C) 2005 Mosaix Communications, Inc. // Copyright (c) 2007 Ben Motmans // // 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.Threading; using System.Collections.Generic; using MonoDevelop.Database.Sql; using MonoDevelop.Core; using MonoDevelop.Ide; using MonoDevelop.Ide.Gui.Pads; using MonoDevelop.Components.Commands; using MonoDevelop.Ide.Gui.Components; namespace MonoDevelop.Database.ConnectionManager { public class ProcedureNodeBuilder : TypeNodeBuilder { public ProcedureNodeBuilder () : base () { } public override Type NodeDataType { get { return typeof (ProcedureNode); } } public override string ContextMenuAddinPath { get { return "/MonoDevelop/Database/ContextMenu/ConnectionManagerPad/ProcedureNode"; } } public override Type CommandHandlerType { get { return typeof (ProcedureNodeCommandHandler); } } public override void GetNodeAttributes (ITreeNavigator treeNavigator, object dataObject, ref NodeAttributes attributes) { attributes |= NodeAttributes.AllowRename; } public override string GetNodeName (ITreeNavigator thisNode, object dataObject) { ProcedureNode node = dataObject as ProcedureNode; return node.Procedure.Name; } public override void BuildNode (ITreeBuilder builder, object dataObject, NodeInfo nodeInfo) { ProcedureNode node = dataObject as ProcedureNode; nodeInfo.Label = node.Procedure.Name; if (node.Procedure.IsFunction) nodeInfo.Icon = Context.GetIcon ("md-db-function"); else nodeInfo.Icon = Context.GetIcon ("md-db-procedure"); } public override void BuildChildNodes (ITreeBuilder builder, object dataObject) { ThreadPool.QueueUserWorkItem (new WaitCallback (BuildChildNodesThreaded), dataObject); } private void BuildChildNodesThreaded (object state) { ProcedureNode node = state as ProcedureNode; ITreeBuilder builder = Context.GetTreeBuilder (state); ISchemaProvider provider = node.ConnectionContext.SchemaProvider; if (provider.IsSchemaActionSupported (SchemaType.Constraint, SchemaActions.Schema)) DispatchService.GuiDispatch (delegate { builder.AddChild (new ParametersNode (node.ConnectionContext, node.Procedure)); builder.Expanded = true; }); } public override bool HasChildNodes (ITreeBuilder builder, object dataObject) { ProcedureNode node = dataObject as ProcedureNode; return node.ConnectionContext.SchemaProvider.IsSchemaActionSupported (SchemaType.ProcedureParameter, SchemaActions.Schema); } } public class ProcedureNodeCommandHandler : NodeCommandHandler { public override DragOperation CanDragNode () { return DragOperation.None; } public override void RenameItem (string newName) { ProcedureNode node = (ProcedureNode)CurrentNode.DataItem; if (node.Procedure.Name != newName) ThreadPool.QueueUserWorkItem (new WaitCallback (RenameItemThreaded), new object[]{ node, newName }); } private void RenameItemThreaded (object state) { object[] objs = state as object[]; ProcedureNode node = objs[0] as ProcedureNode; string newName = objs[1] as string; IEditSchemaProvider provider = (IEditSchemaProvider)node.Procedure.SchemaProvider; if (provider.IsValidName (newName)) { provider.RenameProcedure (node.Procedure, newName); node.Refresh (); } else { DispatchService.GuiDispatch (delegate () { MessageService.ShowError (String.Format ( "Unable to rename procedure '{0}' to '{1}'!", node.Procedure.Name, newName )); }); } node.Refresh (); } protected void OnRefreshParent () { if (CurrentNode.MoveToParent ()) { BaseNode node = CurrentNode.DataItem as BaseNode; node.Refresh (); } } [CommandHandler (ConnectionManagerCommands.AlterProcedure)] protected void OnAlterProcedure () { ProcedureNode node = CurrentNode.DataItem as ProcedureNode; IDbFactory fac = node.ConnectionContext.DbFactory; IEditSchemaProvider schemaProvider = (IEditSchemaProvider)node.ConnectionContext.SchemaProvider; ProcedureSchema alterProc = (ProcedureSchema)node.Procedure.Clone (); if (fac.GuiProvider.ShowProcedureEditorDialog (schemaProvider, alterProc, false)) ThreadPool.QueueUserWorkItem (new WaitCallback (OnAlterProcedureThreaded), alterProc); } private void OnAlterProcedureThreaded (object state) { ProcedureNode node = CurrentNode.DataItem as ProcedureNode; IDbFactory fac = node.ConnectionContext.DbFactory; IEditSchemaProvider schemaProvider = (IEditSchemaProvider)node.ConnectionContext.SchemaProvider; ProcedureAlterSchema alterSchema = new ProcedureAlterSchema (node.Procedure, (ProcedureSchema)((ProcedureSchema)state).Clone ()); schemaProvider.AlterProcedure (alterSchema); OnRefreshParent (); } [CommandHandler (ConnectionManagerCommands.DropProcedure)] protected void OnDropProcedure () { ProcedureNode node = (ProcedureNode)CurrentNode.DataItem; AlertButton dropButton = new AlertButton (AddinCatalog.GetString ("Drop"), Gtk.Stock.Delete); if (MessageService.Confirm ( AddinCatalog.GetString ("Are you sure you want to drop procedure '{0}'", node.Procedure.Name), dropButton )) { ThreadPool.QueueUserWorkItem (new WaitCallback (OnDropProcedureThreaded), CurrentNode.DataItem); } } private void OnDropProcedureThreaded (object state) { ProcedureNode node = (ProcedureNode)state; IEditSchemaProvider provider = (IEditSchemaProvider)node.ConnectionContext.SchemaProvider; provider.DropProcedure (node.Procedure); OnRefreshParent (); } [CommandHandler (MonoDevelop.Ide.Commands.EditCommands.Rename)] protected void OnRenameProcedure () { Tree.StartLabelEdit (); } [CommandUpdateHandler (ConnectionManagerCommands.DropProcedure)] protected void OnUpdateDropProcedure (CommandInfo info) { BaseNode node = (BaseNode)CurrentNode.DataItem; //info.Enabled = node.ConnectionContext.DbFactory.IsActionSupported ("Procedure", SchemaActions.Drop); } [CommandUpdateHandler (MonoDevelop.Ide.Commands.EditCommands.Rename)] protected void OnUpdateRenameProcedure (CommandInfo info) { BaseNode node = (BaseNode)CurrentNode.DataItem; //info.Enabled = node.ConnectionContext.DbFactory.IsActionSupported ("Procedure", SchemaActions.Rename); } [CommandUpdateHandler (ConnectionManagerCommands.AlterProcedure)] protected void OnUpdateAlterProcedure (CommandInfo info) { BaseNode node = (BaseNode)CurrentNode.DataItem; //info.Enabled = node.ConnectionContext.DbFactory.IsActionSupported ("Procedure", SchemaActions.Alter); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Web.UI.WebControls.WebControl.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Web.UI.WebControls { public partial class WebControl : System.Web.UI.Control, System.Web.UI.IAttributeAccessor { #region Methods and constructors protected virtual new void AddAttributesToRender(System.Web.UI.HtmlTextWriter writer) { } public void ApplyStyle(Style s) { } public void CopyBaseAttributes(System.Web.UI.WebControls.WebControl controlSrc) { } protected virtual new Style CreateControlStyle() { return default(Style); } protected override void LoadViewState(Object savedState) { } public void MergeStyle(Style s) { } protected internal override void Render(System.Web.UI.HtmlTextWriter writer) { } public virtual new void RenderBeginTag(System.Web.UI.HtmlTextWriter writer) { } protected internal virtual new void RenderContents(System.Web.UI.HtmlTextWriter writer) { } public virtual new void RenderEndTag(System.Web.UI.HtmlTextWriter writer) { } protected override Object SaveViewState() { return default(Object); } string System.Web.UI.IAttributeAccessor.GetAttribute(string name) { return default(string); } void System.Web.UI.IAttributeAccessor.SetAttribute(string name, string value) { } protected override void TrackViewState() { } public WebControl(System.Web.UI.HtmlTextWriterTag tag) { } protected WebControl(string tag) { } protected WebControl() { } #endregion #region Properties and indexers public virtual new string AccessKey { get { return default(string); } set { } } public System.Web.UI.AttributeCollection Attributes { get { return default(System.Web.UI.AttributeCollection); } } public virtual new System.Drawing.Color BackColor { get { return default(System.Drawing.Color); } set { } } public virtual new System.Drawing.Color BorderColor { get { return default(System.Drawing.Color); } set { } } public virtual new BorderStyle BorderStyle { get { return default(BorderStyle); } set { } } public virtual new Unit BorderWidth { get { return default(Unit); } set { } } public Style ControlStyle { get { return default(Style); } } public bool ControlStyleCreated { get { return default(bool); } } public virtual new string CssClass { get { return default(string); } set { } } public static string DisabledCssClass { get { return default(string); } set { } } public virtual new bool Enabled { get { return default(bool); } set { } } public override bool EnableTheming { get { return default(bool); } set { } } public virtual new FontInfo Font { get { return default(FontInfo); } } public virtual new System.Drawing.Color ForeColor { get { return default(System.Drawing.Color); } set { } } public bool HasAttributes { get { return default(bool); } } public virtual new Unit Height { get { return default(Unit); } set { } } internal protected bool IsEnabled { get { return default(bool); } } public override string SkinID { get { return default(string); } set { } } public System.Web.UI.CssStyleCollection Style { get { return default(System.Web.UI.CssStyleCollection); } } public virtual new bool SupportsDisabledAttribute { get { return default(bool); } } public virtual new short TabIndex { get { return default(short); } set { } } protected virtual new System.Web.UI.HtmlTextWriterTag TagKey { get { return default(System.Web.UI.HtmlTextWriterTag); } } protected virtual new string TagName { get { return default(string); } } public virtual new string ToolTip { get { return default(string); } set { } } public virtual new Unit Width { get { return default(Unit); } set { } } #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. /****************************************************************************** * 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 TestNotZAndNotCByte() { var test = new BooleanTwoComparisonOpTest__TestNotZAndNotCByte(); 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 BooleanTwoComparisonOpTest__TestNotZAndNotCByte { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Byte); private const int Op2ElementCount = VectorSize / 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 BooleanTwoComparisonOpTest__DataTable<Byte, Byte> _dataTable; static BooleanTwoComparisonOpTest__TestNotZAndNotCByte() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize); } public BooleanTwoComparisonOpTest__TestNotZAndNotCByte() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); } _dataTable = new BooleanTwoComparisonOpTest__DataTable<Byte, Byte>(_data1, _data2, VectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse41.TestNotZAndNotC( Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_Load() { var result = Sse41.TestNotZAndNotC( Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_LoadAligned() { var result = Sse41.TestNotZAndNotC( Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { var method = typeof(Sse41).GetMethod(nameof(Sse41.TestNotZAndNotC), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }); if (method != null) { var result = method.Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunReflectionScenario_Load() { var method = typeof(Sse41).GetMethod(nameof(Sse41.TestNotZAndNotC), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }); if (method != null) { var result = method.Invoke(null, new object[] { Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunReflectionScenario_LoadAligned() {var method = typeof(Sse41).GetMethod(nameof(Sse41.TestNotZAndNotC), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }); if (method != null) { var result = method.Invoke(null, new object[] { Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunClsVarScenario() { var result = Sse41.TestNotZAndNotC( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr); var result = Sse41.TestNotZAndNotC(left, right); ValidateResult(left, right, result); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)); var result = Sse41.TestNotZAndNotC(left, right); ValidateResult(left, right, result); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)); var result = Sse41.TestNotZAndNotC(left, right); ValidateResult(left, right, result); } public void RunLclFldScenario() { var test = new BooleanTwoComparisonOpTest__TestNotZAndNotCByte(); var result = Sse41.TestNotZAndNotC(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunFldScenario() { var result = Sse41.TestNotZAndNotC(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Byte> left, Vector128<Byte> right, bool result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* left, void* right, bool result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Byte[] left, Byte[] right, bool result, [CallerMemberName] string method = "") { var expectedResult1 = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult1 &= (((left[i] & right[i]) == 0)); } var expectedResult2 = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult2 &= (((~left[i] & right[i]) == 0)); } if (((expectedResult1 == false) && (expectedResult2 == false)) != result) { Succeeded = false; Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.TestNotZAndNotC)}<Byte>(Vector128<Byte>, Vector128<Byte>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// // ClassicTrackInfoDisplay.cs // // Author: // Aaron Bockover <[email protected]> // // Copyright (C) 2007-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using Gdk; using Gtk; using Cairo; using Hyena.Gui; using Banshee.Collection; using Banshee.Collection.Gui; namespace Banshee.Gui.Widgets { public class ClassicTrackInfoDisplay : TrackInfoDisplay { private Gdk.Window event_window; private ArtworkPopup popup; private uint popup_timeout_id; private bool in_popup; private bool in_thumbnail_region; private Pango.Layout first_line_layout; private Pango.Layout second_line_layout; public ClassicTrackInfoDisplay () : base () { ArtworkSpacing = 10; } protected ClassicTrackInfoDisplay (IntPtr native) : base (native) { } protected override void Dispose (bool disposing) { if (disposing) { HidePopup (); } base.Dispose (disposing); } protected override int ArtworkSizeRequest { get { return artwork_size ?? base.ArtworkSizeRequest; } } private int? artwork_size; public int ArtworkSize { get { return ArtworkSizeRequest; } set { artwork_size = value; } } public int ArtworkSpacing { get; set; } #region Widget Window Management protected override void OnRealized () { base.OnRealized (); WindowAttr attributes = new WindowAttr (); attributes.WindowType = Gdk.WindowType.Child; attributes.X = Allocation.X; attributes.Y = Allocation.Y; attributes.Width = Allocation.Width; attributes.Height = Allocation.Height; attributes.Wclass = WindowWindowClass.InputOnly; attributes.EventMask = (int)( EventMask.PointerMotionMask | EventMask.EnterNotifyMask | EventMask.LeaveNotifyMask | EventMask.ExposureMask); WindowAttributesType attributes_mask = WindowAttributesType.X | WindowAttributesType.Y | WindowAttributesType.Wmclass; event_window = new Gdk.Window (Window, attributes, attributes_mask); event_window.UserData = Handle; } protected override void OnUnrealized () { IsRealized = false; event_window.UserData = IntPtr.Zero; event_window.Destroy (); event_window = null; base.OnUnrealized (); } protected override void OnMapped () { event_window.Show (); base.OnMapped (); } protected override void OnUnmapped () { event_window.Hide (); base.OnUnmapped (); } protected override void OnSizeAllocated (Gdk.Rectangle allocation) { base.OnSizeAllocated (allocation); if (IsRealized) { event_window.MoveResize (allocation); } } protected override void OnGetPreferredHeight (out int minimum_height, out int natural_height) { minimum_height = ComputeWidgetHeight (); natural_height = minimum_height; } private int ComputeWidgetHeight () { int width, height; Pango.Layout layout = new Pango.Layout (PangoContext); layout.SetText ("W"); layout.GetPixelSize (out width, out height); layout.Dispose (); return 2 * height; } protected override void OnThemeChanged () { if (first_line_layout != null) { first_line_layout.FontDescription.Dispose (); first_line_layout.Dispose (); first_line_layout = null; } if (second_line_layout != null) { second_line_layout.FontDescription.Dispose (); second_line_layout.Dispose (); second_line_layout = null; } } #endregion #region Drawing protected override void RenderTrackInfo (Context cr, TrackInfo track, bool renderTrack, bool renderArtistAlbum) { if (track == null) { return; } double offset = ArtworkSizeRequest + ArtworkSpacing, y = 0; double x = offset; double width = Allocation.Width - offset; int fl_width, fl_height, sl_width, sl_height; int pango_width = (int)(width * Pango.Scale.PangoScale); if (first_line_layout == null) { first_line_layout = CairoExtensions.CreateLayout (this, cr); first_line_layout.Ellipsize = Pango.EllipsizeMode.End; } if (second_line_layout == null) { second_line_layout = CairoExtensions.CreateLayout (this, cr); second_line_layout.Ellipsize = Pango.EllipsizeMode.End; } // Set up the text layouts first_line_layout.Width = pango_width; second_line_layout.Width = pango_width; // Compute the layout coordinates first_line_layout.SetMarkup (GetFirstLineText (track)); first_line_layout.GetPixelSize (out fl_width, out fl_height); second_line_layout.SetMarkup (GetSecondLineText (track)); second_line_layout.GetPixelSize (out sl_width, out sl_height); if (fl_height + sl_height > Allocation.Height) { SetSizeRequest (-1, fl_height + sl_height); } y = (Allocation.Height - (fl_height + sl_height)) / 2; // Render the layouts cr.Antialias = Cairo.Antialias.Default; if (renderTrack) { cr.MoveTo (x, y); Pango.CairoHelper.ShowLayout (cr, first_line_layout); } if (!renderArtistAlbum) { return; } cr.MoveTo (x, y + fl_height); Pango.CairoHelper.ShowLayout (cr, second_line_layout); } #endregion #region Interaction Events protected override bool OnEnterNotifyEvent (EventCrossing evnt) { in_thumbnail_region = evnt.X <= Allocation.Height; return ShowHideCoverArt (); } protected override bool OnLeaveNotifyEvent (EventCrossing evnt) { in_thumbnail_region = false; return ShowHideCoverArt (); } protected override bool OnMotionNotifyEvent (EventMotion evnt) { in_thumbnail_region = evnt.X <= Allocation.Height; return ShowHideCoverArt (); } private void OnPopupEnterNotifyEvent (object o, EnterNotifyEventArgs args) { in_popup = true; } private void OnPopupLeaveNotifyEvent (object o, LeaveNotifyEventArgs args) { in_popup = false; HidePopup (); } private bool ShowHideCoverArt () { if (!in_thumbnail_region) { if (popup_timeout_id > 0) { GLib.Source.Remove (popup_timeout_id); popup_timeout_id = 0; } GLib.Timeout.Add (100, delegate { if (!in_popup) { HidePopup (); } return false; }); } else { if (popup_timeout_id > 0) { return false; } popup_timeout_id = GLib.Timeout.Add (500, delegate { if (in_thumbnail_region) { UpdatePopup (); } popup_timeout_id = 0; return false; }); } return true; } #endregion #region Popup Window protected override void OnArtworkChanged () { UpdatePopup (); } private bool UpdatePopup () { if (CurrentTrack == null || ArtworkManager == null || !in_thumbnail_region) { HidePopup (); return false; } Gdk.Pixbuf pixbuf = ArtworkManager.LookupPixbuf (CurrentTrack.ArtworkId); if (pixbuf == null) { HidePopup (); return false; } if (popup == null) { popup = new ArtworkPopup (); popup.EnterNotifyEvent += OnPopupEnterNotifyEvent; popup.LeaveNotifyEvent += OnPopupLeaveNotifyEvent; } popup.Label = String.Format ("{0} - {1}", CurrentTrack.DisplayArtistName, CurrentTrack.DisplayAlbumTitle); if (popup.Image != null) { ArtworkManager.DisposePixbuf (popup.Image); } popup.Image = pixbuf; if (in_thumbnail_region) { popup.Show (); } return true; } private void HidePopup () { if (popup != null) { ArtworkManager.DisposePixbuf (popup.Image); popup.Destroy (); popup.EnterNotifyEvent -= OnPopupEnterNotifyEvent; popup.LeaveNotifyEvent -= OnPopupLeaveNotifyEvent; popup = null; } } #endregion } }
// // 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.Network; using Microsoft.WindowsAzure.Management.Network.Models; namespace Microsoft.WindowsAzure.Management.Network { /// <summary> /// The Service Management API includes operations for managing the virtual /// networks for your subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157182.aspx for /// more information) /// </summary> public static partial class ReservedIPOperationsExtensions { /// <summary> /// The Associate Reserved IP operation associates a Reserved IP with a /// service. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.IReservedIPOperations. /// </param> /// <param name='reservedIpName'> /// Required. The name of the reserved IP. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to associate Reserved IP. /// </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 also includes error /// information regarding the failure. /// </returns> public static OperationStatusResponse Associate(this IReservedIPOperations operations, string reservedIpName, NetworkReservedIPMobilityParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IReservedIPOperations)s).AssociateAsync(reservedIpName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Associate Reserved IP operation associates a Reserved IP with a /// service. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.IReservedIPOperations. /// </param> /// <param name='reservedIpName'> /// Required. The name of the reserved IP. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to associate Reserved IP. /// </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 also includes error /// information regarding the failure. /// </returns> public static Task<OperationStatusResponse> AssociateAsync(this IReservedIPOperations operations, string reservedIpName, NetworkReservedIPMobilityParameters parameters) { return operations.AssociateAsync(reservedIpName, parameters, CancellationToken.None); } /// <summary> /// The BeginAssociate begins to associate a Reserved IP with a service. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.IReservedIPOperations. /// </param> /// <param name='reservedIpName'> /// Required. The name of the reserved IP. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Begin associating Reserved IP. /// </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 also includes error /// information regarding the failure. /// </returns> public static OperationStatusResponse BeginAssociating(this IReservedIPOperations operations, string reservedIpName, NetworkReservedIPMobilityParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IReservedIPOperations)s).BeginAssociatingAsync(reservedIpName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The BeginAssociate begins to associate a Reserved IP with a service. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.IReservedIPOperations. /// </param> /// <param name='reservedIpName'> /// Required. The name of the reserved IP. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Begin associating Reserved IP. /// </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 also includes error /// information regarding the failure. /// </returns> public static Task<OperationStatusResponse> BeginAssociatingAsync(this IReservedIPOperations operations, string reservedIpName, NetworkReservedIPMobilityParameters parameters) { return operations.BeginAssociatingAsync(reservedIpName, parameters, CancellationToken.None); } /// <summary> /// The Begin Creating Reserved IP operation creates a reserved IP from /// your the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.IReservedIPOperations. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Begin Creating Reserved IP /// operation. /// </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 also includes error /// information regarding the failure. /// </returns> public static OperationStatusResponse BeginCreating(this IReservedIPOperations operations, NetworkReservedIPCreateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IReservedIPOperations)s).BeginCreatingAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Begin Creating Reserved IP operation creates a reserved IP from /// your the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.IReservedIPOperations. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Begin Creating Reserved IP /// operation. /// </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 also includes error /// information regarding the failure. /// </returns> public static Task<OperationStatusResponse> BeginCreatingAsync(this IReservedIPOperations operations, NetworkReservedIPCreateParameters parameters) { return operations.BeginCreatingAsync(parameters, CancellationToken.None); } /// <summary> /// The Begin Deleting Reserved IP operation removes a reserved IP from /// your the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.IReservedIPOperations. /// </param> /// <param name='ipName'> /// Required. The name of the reserved IP. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse BeginDeleting(this IReservedIPOperations operations, string ipName) { return Task.Factory.StartNew((object s) => { return ((IReservedIPOperations)s).BeginDeletingAsync(ipName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Begin Deleting Reserved IP operation removes a reserved IP from /// your the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.IReservedIPOperations. /// </param> /// <param name='ipName'> /// Required. The name of the reserved IP. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> BeginDeletingAsync(this IReservedIPOperations operations, string ipName) { return operations.BeginDeletingAsync(ipName, CancellationToken.None); } /// <summary> /// The BeginDisassociate begins to disassociate a Reserved IP from a /// service. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.IReservedIPOperations. /// </param> /// <param name='reservedIpName'> /// Required. The name of the reserved IP. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Begin disassociating Reserved /// IP. /// </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 also includes error /// information regarding the failure. /// </returns> public static OperationStatusResponse BeginDisassociating(this IReservedIPOperations operations, string reservedIpName, NetworkReservedIPMobilityParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IReservedIPOperations)s).BeginDisassociatingAsync(reservedIpName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The BeginDisassociate begins to disassociate a Reserved IP from a /// service. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.IReservedIPOperations. /// </param> /// <param name='reservedIpName'> /// Required. The name of the reserved IP. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Begin disassociating Reserved /// IP. /// </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 also includes error /// information regarding the failure. /// </returns> public static Task<OperationStatusResponse> BeginDisassociatingAsync(this IReservedIPOperations operations, string reservedIpName, NetworkReservedIPMobilityParameters parameters) { return operations.BeginDisassociatingAsync(reservedIpName, parameters, CancellationToken.None); } /// <summary> /// The Create Reserved IP operation creates a reserved IP from your /// the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.IReservedIPOperations. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Create Reserved IP operation. /// </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 also includes error /// information regarding the failure. /// </returns> public static OperationStatusResponse Create(this IReservedIPOperations operations, NetworkReservedIPCreateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IReservedIPOperations)s).CreateAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Create Reserved IP operation creates a reserved IP from your /// the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.IReservedIPOperations. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Create Reserved IP operation. /// </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 also includes error /// information regarding the failure. /// </returns> public static Task<OperationStatusResponse> CreateAsync(this IReservedIPOperations operations, NetworkReservedIPCreateParameters parameters) { return operations.CreateAsync(parameters, CancellationToken.None); } /// <summary> /// The Delete Reserved IP operation removes a reserved IP from your /// the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.IReservedIPOperations. /// </param> /// <param name='ipName'> /// Required. The name of the reserved IP. /// </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 also includes error /// information regarding the failure. /// </returns> public static OperationStatusResponse Delete(this IReservedIPOperations operations, string ipName) { return Task.Factory.StartNew((object s) => { return ((IReservedIPOperations)s).DeleteAsync(ipName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Delete Reserved IP operation removes a reserved IP from your /// the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.IReservedIPOperations. /// </param> /// <param name='ipName'> /// Required. The name of the reserved IP. /// </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 also includes error /// information regarding the failure. /// </returns> public static Task<OperationStatusResponse> DeleteAsync(this IReservedIPOperations operations, string ipName) { return operations.DeleteAsync(ipName, CancellationToken.None); } /// <summary> /// The Disassociate Reserved IP operation disassociates a Reserved IP /// from a service. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.IReservedIPOperations. /// </param> /// <param name='reservedIpName'> /// Required. The name of the reserved IP. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to disassociate Reserved IP. /// </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 also includes error /// information regarding the failure. /// </returns> public static OperationStatusResponse Disassociate(this IReservedIPOperations operations, string reservedIpName, NetworkReservedIPMobilityParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IReservedIPOperations)s).DisassociateAsync(reservedIpName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Disassociate Reserved IP operation disassociates a Reserved IP /// from a service. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.IReservedIPOperations. /// </param> /// <param name='reservedIpName'> /// Required. The name of the reserved IP. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to disassociate Reserved IP. /// </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 also includes error /// information regarding the failure. /// </returns> public static Task<OperationStatusResponse> DisassociateAsync(this IReservedIPOperations operations, string reservedIpName, NetworkReservedIPMobilityParameters parameters) { return operations.DisassociateAsync(reservedIpName, parameters, CancellationToken.None); } /// <summary> /// The Get Reserved IP operation retrieves the details for the virtual /// IP reserved for the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.IReservedIPOperations. /// </param> /// <param name='ipName'> /// Required. The name of the reserved IP to retrieve. /// </param> /// <returns> /// A reserved IP associated with your subscription. /// </returns> public static NetworkReservedIPGetResponse Get(this IReservedIPOperations operations, string ipName) { return Task.Factory.StartNew((object s) => { return ((IReservedIPOperations)s).GetAsync(ipName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get Reserved IP operation retrieves the details for the virtual /// IP reserved for the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.IReservedIPOperations. /// </param> /// <param name='ipName'> /// Required. The name of the reserved IP to retrieve. /// </param> /// <returns> /// A reserved IP associated with your subscription. /// </returns> public static Task<NetworkReservedIPGetResponse> GetAsync(this IReservedIPOperations operations, string ipName) { return operations.GetAsync(ipName, CancellationToken.None); } /// <summary> /// The List Reserved IP operation retrieves all of the virtual IPs /// reserved for the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.IReservedIPOperations. /// </param> /// <returns> /// The response structure for the Server List operation. /// </returns> public static NetworkReservedIPListResponse List(this IReservedIPOperations operations) { return Task.Factory.StartNew((object s) => { return ((IReservedIPOperations)s).ListAsync(); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The List Reserved IP operation retrieves all of the virtual IPs /// reserved for the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.IReservedIPOperations. /// </param> /// <returns> /// The response structure for the Server List operation. /// </returns> public static Task<NetworkReservedIPListResponse> ListAsync(this IReservedIPOperations operations) { return operations.ListAsync(CancellationToken.None); } } }
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using WebApplication.Data; namespace WebApplication.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("00000000000000_CreateIdentitySchema")] partial class CreateIdentitySchema { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "1.0.0-rc2-20901"); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b => { b.Property<string>("Id"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedName") .HasName("RoleNameIndex"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.HasIndex("UserId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider"); b.Property<string>("Name"); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("WebApplication.Models.ApplicationUser", b => { b.Property<string>("Id"); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasAnnotation("MaxLength", 256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedUserName") .HasAnnotation("MaxLength", 256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .HasName("UserNameIndex"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b => { b.HasOne("WebApplication.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b => { b.HasOne("WebApplication.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("WebApplication.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); } } }
/* * Copyright 2005 OpenXRI Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace DotNetXri.Client.Resolve { using java.io.ByteArrayInputStream; using java.io.InputStream; using java.net.URI; using java.util.ArrayList; using junit.framework.Test; using junit.framework.TestCase; using junit.framework.TestSuite; using junit.textui.TestRunner; using org.openxri.XRI; using org.openxri.resolve.exception.PartialResolutionException; using org.openxri.xml.CanonicalID; using org.openxri.xml.SEPElement; using org.openxri.xml.Service; using org.openxri.xml.Status; using org.openxri.xml.Tags; using org.openxri.xml.XRD; using org.openxri.xml.XRDS; public class ResolverTest :TestCase { public static void main(string[] oArgs) { // Pass control to the non-graphical test runner TestRunner.run(suite()); } public static Test suite() { return new TestSuite(typeof(ResolverTest)); } public void testResolve() { string qxri; try { Resolver resolver = setupResolver(); qxri = "@xrid*test*freeid*null-provider"; qxri = "=les.chasen"; qxri = "=kermit*\u65e5\u672c\u7248"; XRI xri = XRI.fromIRINormalForm(qxri); ResolverFlags flags = new ResolverFlags(); flags.setUric(true); flags.setHttps(false); resolver.resolveSEPToXRD(xri, null, null, flags, new ResolverState()); ArrayList uris = resolver.resolveSEPToURIList(qxri, new TrustType(), null, "text/xml", true); } catch (Exception e) { e.printStackTrace(); fail("Not expecting an exception here: " + e); } } public void testCID() { string qxri; try { Resolver resolver = setupResolver(); qxri = "@xrid*test*live.unit.tests*0003-badcid*kid"; XRI xri = XRI.fromIRINormalForm(qxri); ResolverFlags flags = new ResolverFlags(); XRDS xrds = resolver.resolveAuthToXRDS(xri, flags, new ResolverState()); // Logger.Info(xrds); assertTrue("Expected 5 XRDs", xrds.getNumChildren() == 5); assertTrue("subseg[3] should be *0003-badcid", xrds.getDescriptorAt(3).getQuery().Equals("*0003-badcid")); Status s3 = xrds.getDescriptorAt(3).getStatus(); assertTrue("subseg[3].status.cid should be 'failed'", s3.getCID().Equals("failed")); Status s4 = xrds.getDescriptorAt(4).getStatus(); assertTrue("subseg[4].status.cid should be 'failed'", s4.getCID().Equals("failed")); qxri = "@xrid*test*live.unit.tests*0001-simple"; xri = XRI.fromIRINormalForm(qxri); xrds = resolver.resolveAuthToXRDS(xri, flags, new ResolverState()); assertTrue("Expected 4 XRDs", xrds.getNumChildren() == 4); XRD xrd3 = xrds.getDescriptorAt(3); assertTrue("subseg[3] should be *0001-simple", xrd3.getQuery().Equals("*0001-simple")); assertTrue("subseg[3] should be CID verified", xrd3.getStatus().getCID().Equals(Status.CID_VERIFIED)); assertTrue("subseg[3] should be CEID verified", xrd3.getStatus().getCEID().Equals(Status.CID_VERIFIED)); } catch (Exception e) { fail("Not expecting an exception here: " + e); e.printStackTrace(); } } public void testLiveRef() { string qxri; try { Resolver resolver = setupResolver(); qxri = "@xrid*test*live.unit.tests*0002-ref"; XRI xri = XRI.fromIRINormalForm(qxri); ResolverFlags flags = new ResolverFlags(); XRDS xrds = resolver.resolveAuthToXRDS(xri, flags, new ResolverState()); assertTrue("There should be 5 child elements", xrds.getNumChildren() == 5); assertTrue("The last child should be an XRDS element because it followed a Ref", xrds.isXRDSAt(4)); } catch (PartialResolutionException e) { fail("Not expecting PRE. PartialXRDS=" + e.getPartialXRDS()); } catch (Exception e) { fail("Not expecting an exception here: " + e); } } public void testLiveRedirect() { string qxri = "@xrid*test*live.unit.tests*0004-redirect/(+blog)"; try { Resolver resolver = setupResolver(); XRI xri = XRI.fromIRINormalForm(qxri); ResolverFlags flags = new ResolverFlags(); XRDS xrds = resolver.resolveSEPToXRDS(xri, null, null, flags, new ResolverState()); Logger.Info(xrds); assertTrue("There should be 8 child elements", xrds.getNumChildren() == 8); assertTrue("The first child should be an XRD element", xrds.isXRDAt(0)); assertTrue("The second child should be an XRD element", xrds.isXRDAt(1)); assertTrue("The third child should be an XRD element", xrds.isXRDAt(2)); assertTrue("The fourth child should be an XRD element", xrds.isXRDAt(3)); assertTrue("The fifth child should be an XRDS element because it followed a Redirect", xrds.isXRDSAt(4)); XRDS redirXRDS = xrds.getXRDSAt(4); assertTrue("Wrong redirect followed in the fifth child", redirXRDS.getRedirect().Equals("http://auth.xrid.net/!330/")); assertTrue("The fifth child should have 2 children", redirXRDS.getNumChildren() == 2); assertTrue("The fifth child's first child should be an XRD", redirXRDS.isXRDAt(0)); assertTrue("The fifth child's second child should be an XRDS", redirXRDS.isXRDSAt(1)); redirXRDS = redirXRDS.getXRDSAt(1); assertTrue("Wrong redirect followed in the fifth child's second child", redirXRDS.getRedirect().Equals("http://does.not.exist/")); assertFalse("Fifth child should have failed", redirXRDS.getFinalXRD().getStatusCode().Equals(Status.SUCCESS)); assertTrue("The sixth child should be an XRDS element because it followed a Redirect", xrds.isXRDSAt(5)); redirXRDS = xrds.getXRDSAt(5); assertTrue("Wrong redirect followed in the sixth child", redirXRDS.getRedirect().Equals("http://auth.xrid.net/!333/")); assertTrue("The seventh child should be an XRDS element because it followed a Redirect", xrds.isXRDSAt(6)); redirXRDS = xrds.getXRDSAt(6); assertTrue("Wrong redirect followed on the seventh child", redirXRDS.getRedirect().Equals("http://auth.xrid.net/!331/")); assertTrue("Seventh child should have succeeded", redirXRDS.getFinalXRD().getStatusCode().Equals(Status.SUCCESS)); assertTrue("The eighth child should be an XRDS element because it followed a Service-level Redirect", xrds.isXRDSAt(7)); redirXRDS = xrds.getXRDSAt(7); assertTrue("Wrong redirect followed on the eighth child", redirXRDS.getRedirect().Equals("http://auth.xrid.net/!332/")); assertTrue("Eighth child should have succeeded", redirXRDS.getFinalXRD().getStatusCode().Equals(Status.SUCCESS)); assertTrue("Should be one selected Service on eighth child", redirXRDS.getFinalXRD().getSelectedServices().getList().Count == 1); Service srv = (Service)redirXRDS.getFinalXRD().getSelectedServices().getList().get(0); assertTrue("In correct URI in selected service on eighth child", srv.getURIAt(0).getUriString().Equals("http://my.blog.com")); } catch (Exception e) { e.printStackTrace(); fail("Not expecting exception: " + e); } } public void testConstructURI() { Resolver resolver = new Resolver(); string qxri = "xri://@a*b*c/d/e?f=g"; try { URI sepURI = new URI("http://example.com/hello"); string result = resolver.constructURI(sepURI, "local", new XRI(qxri)); assertTrue("Invalid constructed URI for append=local '" + result + "'", result.Equals(sepURI.toString() + "/d/e?f=g")); result = resolver.constructURI(sepURI, "qxri", new XRI(qxri)); assertTrue("Invalid constructed URI for append=qxri '" + result + "'", result.Equals(sepURI.toString() + "@a*b*c/d/e?f=g")); Logger.Info("result = " + result); } catch (Exception oEx) { fail("Got wrong exception while trying to resolve IRI " + oEx); } } public static XRD createAuthRoot(string uri) { XRD xrd = new XRD(); // construct an authority resolution service Service srv = new Service(); TrustType tt = new TrustType(); // default trust type string authMediaType = Tags.CONTENT_TYPE_XRDS + ";" + tt.getParameterPair(); srv.addMediaType(authMediaType, null, false); srv.addType(Tags.SERVICE_AUTH_RES); srv.addURI(uri); // add it to the XRD xrd.addService(srv); return xrd; } public static Resolver setupResolver() { // instantiate a Resolver obj Resolver resolver = new Resolver(); // configure roots XRD eqRoot = createAuthRoot("http://equal.xri.net/"); eqRoot.setCanonicalID(new CanonicalID("=")); Status eqRootStatus = new Status(Status.SUCCESS); eqRootStatus.setCID(Status.CID_VERIFIED); eqRoot.setStatus(eqRootStatus); resolver.setAuthority("=", eqRoot); XRD atRoot = createAuthRoot("http://at.xri.net/"); atRoot.setCanonicalID(new CanonicalID("@")); Status atRootStatus = new Status(Status.SUCCESS); atRootStatus.setCID(Status.CID_VERIFIED); atRoot.setStatus(atRootStatus); resolver.setAuthority("@", atRoot); return resolver; } } }
#if (UNITY_WINRT || UNITY_WP_8_1) && !UNITY_EDITOR && !UNITY_WP8 #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Serialization { /// <summary> /// Maps a JSON property to a .NET member or constructor parameter. /// </summary> public class JsonProperty { internal Required? _required; internal bool _hasExplicitDefaultValue; internal object _defaultValue; private string _propertyName; private bool _skipPropertyNameEscape; // use to cache contract during deserialization internal JsonContract PropertyContract { get; set; } /// <summary> /// Gets or sets the name of the property. /// </summary> /// <value>The name of the property.</value> public string PropertyName { get { return _propertyName; } set { _propertyName = value; CalculateSkipPropertyNameEscape(); } } private void CalculateSkipPropertyNameEscape() { if (_propertyName == null) { _skipPropertyNameEscape = false; } else { _skipPropertyNameEscape = true; foreach (char c in _propertyName) { if (!char.IsLetterOrDigit(c) && c != '_' && c != '@') { _skipPropertyNameEscape = false; break; } } } } /// <summary> /// Gets or sets the type that declared this property. /// </summary> /// <value>The type that declared this property.</value> public Type DeclaringType { get; set; } /// <summary> /// Gets or sets the order of serialization and deserialization of a member. /// </summary> /// <value>The numeric order of serialization or deserialization.</value> public int? Order { get; set; } /// <summary> /// Gets or sets the name of the underlying member or parameter. /// </summary> /// <value>The name of the underlying member or parameter.</value> public string UnderlyingName { get; set; } /// <summary> /// Gets the <see cref="IValueProvider"/> that will get and set the <see cref="JsonProperty"/> during serialization. /// </summary> /// <value>The <see cref="IValueProvider"/> that will get and set the <see cref="JsonProperty"/> during serialization.</value> public IValueProvider ValueProvider { get; set; } /// <summary> /// Gets or sets the type of the property. /// </summary> /// <value>The type of the property.</value> public Type PropertyType { get; set; } /// <summary> /// Gets or sets the <see cref="JsonConverter" /> for the property. /// If set this converter takes presidence over the contract converter for the property type. /// </summary> /// <value>The converter.</value> public JsonConverter Converter { get; set; } /// <summary> /// Gets the member converter. /// </summary> /// <value>The member converter.</value> public JsonConverter MemberConverter { get; set; } /// <summary> /// Gets a value indicating whether this <see cref="JsonProperty"/> is ignored. /// </summary> /// <value><c>true</c> if ignored; otherwise, <c>false</c>.</value> public bool Ignored { get; set; } /// <summary> /// Gets a value indicating whether this <see cref="JsonProperty"/> is readable. /// </summary> /// <value><c>true</c> if readable; otherwise, <c>false</c>.</value> public bool Readable { get; set; } /// <summary> /// Gets a value indicating whether this <see cref="JsonProperty"/> is writable. /// </summary> /// <value><c>true</c> if writable; otherwise, <c>false</c>.</value> public bool Writable { get; set; } /// <summary> /// Gets a value indicating whether this <see cref="JsonProperty"/> has a member attribute. /// </summary> /// <value><c>true</c> if has a member attribute; otherwise, <c>false</c>.</value> public bool HasMemberAttribute { get; set; } /// <summary> /// Gets the default value. /// </summary> /// <value>The default value.</value> public object DefaultValue { get { return _defaultValue; } set { _hasExplicitDefaultValue = true; _defaultValue = value; } } internal object GetResolvedDefaultValue() { if (!_hasExplicitDefaultValue && PropertyType != null) return ReflectionUtils.GetDefaultValue(PropertyType); return _defaultValue; } /// <summary> /// Gets a value indicating whether this <see cref="JsonProperty"/> is required. /// </summary> /// <value>A value indicating whether this <see cref="JsonProperty"/> is required.</value> public Required Required { get { return _required ?? Required.Default; } set { _required = value; } } /// <summary> /// Gets a value indicating whether this property preserves object references. /// </summary> /// <value> /// <c>true</c> if this instance is reference; otherwise, <c>false</c>. /// </value> public bool? IsReference { get; set; } /// <summary> /// Gets the property null value handling. /// </summary> /// <value>The null value handling.</value> public NullValueHandling? NullValueHandling { get; set; } /// <summary> /// Gets the property default value handling. /// </summary> /// <value>The default value handling.</value> public DefaultValueHandling? DefaultValueHandling { get; set; } /// <summary> /// Gets the property reference loop handling. /// </summary> /// <value>The reference loop handling.</value> public ReferenceLoopHandling? ReferenceLoopHandling { get; set; } /// <summary> /// Gets the property object creation handling. /// </summary> /// <value>The object creation handling.</value> public ObjectCreationHandling? ObjectCreationHandling { get; set; } /// <summary> /// Gets or sets the type name handling. /// </summary> /// <value>The type name handling.</value> public TypeNameHandling? TypeNameHandling { get; set; } /// <summary> /// Gets or sets a predicate used to determine whether the property should be serialize. /// </summary> /// <value>A predicate used to determine whether the property should be serialize.</value> public Predicate<object> ShouldSerialize { get; set; } /// <summary> /// Gets or sets a predicate used to determine whether the property should be serialized. /// </summary> /// <value>A predicate used to determine whether the property should be serialized.</value> public Predicate<object> GetIsSpecified { get; set; } /// <summary> /// Gets or sets an action used to set whether the property has been deserialized. /// </summary> /// <value>An action used to set whether the property has been deserialized.</value> public Action<object, object> SetIsSpecified { get; set; } /// <summary> /// Returns a <see cref="String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="String"/> that represents this instance. /// </returns> public override string ToString() { return PropertyName; } /// <summary> /// Gets or sets the converter used when serializing the property's collection items. /// </summary> /// <value>The collection's items converter.</value> public JsonConverter ItemConverter { get; set; } /// <summary> /// Gets or sets whether this property's collection items are serialized as a reference. /// </summary> /// <value>Whether this property's collection items are serialized as a reference.</value> public bool? ItemIsReference { get; set; } /// <summary> /// Gets or sets the the type name handling used when serializing the property's collection items. /// </summary> /// <value>The collection's items type name handling.</value> public TypeNameHandling? ItemTypeNameHandling { get; set; } /// <summary> /// Gets or sets the the reference loop handling used when serializing the property's collection items. /// </summary> /// <value>The collection's items reference loop handling.</value> public ReferenceLoopHandling? ItemReferenceLoopHandling { get; set; } internal void WritePropertyName(JsonWriter writer) { if (_skipPropertyNameEscape) writer.WritePropertyName(PropertyName, false); else writer.WritePropertyName(PropertyName); } } } #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.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Test.Utilities; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.CodeQuality.CSharp.Analyzers.ApiDesignGuidelines.CSharpPassSystemUriObjectsInsteadOfStringsAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.CodeQuality.VisualBasic.Analyzers.ApiDesignGuidelines.BasicPassSystemUriObjectsInsteadOfStringsAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests { public class PassSystemUriObjectsInsteadOfStringsTests { [Fact] public async Task CA2234NoWarningWithUrl() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class A : IComparable { public static void Method() { Method(1); } public static void Method(int url) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } "); } [Fact] public async Task CA2234NoWarningWithUri() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class A : IComparable { public static void Method() { Method(1); } public static void Method(int uri) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } "); } [Fact] public async Task CA2234NoWarningWithUrn() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class A : IComparable { public static void Method() { Method(1); } public static void Method(int urn) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } "); } [Fact] public async Task CA2234NoWarningWithUriButNoString() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class A : IComparable { public static void Method() { Method(1); } public static void Method(int urn) { } public static void Method(Uri uri) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } "); } [Fact] public async Task CA2234NoWarningWithStringButNoUri() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class A : IComparable { public static void Method() { Method(""test""); } public static void Method(string uri) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } "); } [Fact] public async Task CA2234NoWarningWithStringButNoUrl() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class A : IComparable { public static void Method() { Method(""test""); } public static void Method(string url) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } "); } [Fact] public async Task CA2234NoWarningWithStringButNoUrn() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class A : IComparable { public static void Method() { Method(""test""); } public static void Method(string urn) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } "); } [Fact] public async Task CA2234WarningWithUri() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class A : IComparable { public static void Method() { Method(""test""); } public static void Method(string uri) { } public static void Method(Uri uri) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } ", GetCA2234CSharpResultAt(8, 13, "A.Method()", "A.Method(Uri)", "A.Method(string)")); } [Fact] public async Task CA2234WarningWithUrl() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class A : IComparable { public static void Method() { Method(""test""); } public static void Method(string url) { } public static void Method(Uri uri) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } ", GetCA2234CSharpResultAt(8, 13, "A.Method()", "A.Method(Uri)", "A.Method(string)")); } [Fact] public async Task CA2234WarningWithUrn() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class A : IComparable { public static void Method() { Method(""test""); } public static void Method(string urn) { } public static void Method(Uri uri) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } ", GetCA2234CSharpResultAt(8, 13, "A.Method()", "A.Method(Uri)", "A.Method(string)")); } [Fact] public async Task CA2234WarningWithCompoundUri() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class A : IComparable { public static void Method() { Method(""test""); } public static void Method(string myUri) { } public static void Method(Uri uri) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } ", GetCA2234CSharpResultAt(8, 13, "A.Method()", "A.Method(Uri)", "A.Method(string)")); } [Fact] public async Task CA2234NoWarningWithSubstring() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class A : IComparable { public static void Method() { Method(""test""); } public static void Method(string myuri) { } public static void Method(Uri uri) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } "); } [Fact] public async Task CA2234WarningWithMultipleParameter1() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class A : IComparable { public static void Method() { Method(""test"", ""test"", ""test""); } public static void Method(string param1, string param2, string lastUrl) { } public static void Method(string param1, string param2, Uri lastUrl) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } ", GetCA2234CSharpResultAt(8, 13, "A.Method()", "A.Method(string, string, Uri)", "A.Method(string, string, string)")); } [Fact] public async Task CA2234WarningWithMultipleParameter2() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class A : IComparable { public static void Method() { Method(""test"", 0, ""test""); } public static void Method(string firstUri, int i, string lastUrl) { } public static void Method(Uri uri, int i, string lastUrl) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } ", GetCA2234CSharpResultAt(8, 13, "A.Method()", "A.Method(Uri, int, string)", "A.Method(string, int, string)")); } [Fact] public async Task CA2234NoWarningForSelf() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class A : IComparable { public static void Method() { Method(""test"", null); } public static void Method(string firstUri, Uri lastUri) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } "); } [Fact] public async Task CA2234NoWarningForSelf2() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class A : IComparable { public static void Method() { Method(""test"", null); } public static void Method(string firstUri, Uri lastUri) { } public static void Method(int other, Uri lastUri) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } "); } [Fact] public async Task CA2234WarningWithMultipleUri() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class A : IComparable { public static void Method() { Method(""test"", null); } public static void Method(string firstUri, Uri lastUrl) { } public static void Method(Uri uri, Uri lastUrl) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } ", GetCA2234CSharpResultAt(8, 13, "A.Method()", "A.Method(Uri, Uri)", "A.Method(string, Uri)")); } [Fact] public async Task CA2234WarningWithMultipleOverload() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class A : IComparable { public static void Method() { Method(""test"", ""test2""); } public static void Method(string firstUri, string lastUrl) { } public static void Method(Uri uri, string lastUrl) { } public static void Method(string uri, Uri lastUrl) { } public static void Method(Uri uri, Uri lastUrl) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } ", GetCA2234CSharpResultAt(8, 13, "A.Method()", "A.Method(Uri, string)", "A.Method(string, string)") , GetCA2234CSharpResultAt(8, 13, "A.Method()", "A.Method(string, Uri)", "A.Method(string, string)")); } [Fact] public async Task CA2234NoWarningSignatureMismatchingNumberOfParameter() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class A : IComparable { public static void Method() { Method(""test"", null); } public static void Method(string firstUri, string lastUrl) { } public static void Method(Uri uri) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } "); } [Fact] public async Task CA2234NoWarningSignatureMismatchingParameterType() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class A : IComparable { public static void Method() { Method(""test"", null); } public static void Method(string firstUri, string lastUrl) { } public static void Method(Uri uri, int i) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } "); } [Fact] public async Task CA2234NoWarningNotPublic() { await VerifyCS.VerifyAnalyzerAsync(@" using System; internal class A : IComparable { public static void Method() { Method(""test""); } public static void Method(string uri) { } public static void Method(Uri uri) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } "); } [Fact] public async Task CA2234WarningVB() { // since VB and C# shares almost all code except to get method overload group expression // we only need to test that part await VerifyVB.VerifyAnalyzerAsync(@" Imports System Public Module A Public Sub Method() Method(""test"", 0, ""test"") End Sub Public Sub Method(firstUri As String, i As Integer, lastUrl As String) End Sub Public Sub Method(Uri As Uri, i As Integer, lastUrl As String) End Sub End Module ", GetCA2234BasicResultAt(6, 13, "A.Method()", "A.Method(Uri, Integer, String)", "A.Method(String, Integer, String)")); } [Fact, WorkItem(2688, "https://github.com/dotnet/roslyn-analyzers/issues/2688")] public async Task CA2234NoWarningInvocationInUriOverload() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class A : IComparable { public static void Method(string uri) { } public static void Method(Uri uri) { Method(uri.ToString()); } public int CompareTo(object obj) { throw new NotImplementedException(); } } "); } private static DiagnosticResult GetCA2234CSharpResultAt(int line, int column, params string[] args) => VerifyCS.Diagnostic() .WithLocation(line, column) .WithArguments(args); private static DiagnosticResult GetCA2234BasicResultAt(int line, int column, params string[] args) => VerifyVB.Diagnostic() .WithLocation(line, column) .WithArguments(args); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.Serialization; using System.Text; using System; using System.Runtime.InteropServices; namespace System.Text { // A Decoder is used to decode a sequence of blocks of bytes into a // sequence of blocks of characters. Following instantiation of a decoder, // sequential blocks of bytes are converted into blocks of characters through // calls to the GetChars method. The decoder maintains state between the // conversions, allowing it to correctly decode byte sequences that span // adjacent blocks. // // Instances of specific implementations of the Decoder abstract base // class are typically obtained through calls to the GetDecoder method // of Encoding objects. internal class DecoderNLS : Decoder { // Remember our encoding private Encoding _encoding; private bool _mustFlush; internal bool _throwOnOverflow; internal int _bytesUsed; internal DecoderNLS(Encoding encoding) { _encoding = encoding; _fallback = this._encoding.DecoderFallback; this.Reset(); } // This is used by our child deserializers internal DecoderNLS() { _encoding = null; this.Reset(); } public override void Reset() { _fallbackBuffer?.Reset(); } public override int GetCharCount(byte[] bytes, int index, int count) { return GetCharCount(bytes, index, count, false); } public override unsafe int GetCharCount(byte[] bytes, int index, int count, bool flush) { // Validate Parameters if (bytes == null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); // Just call pointer version fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes)) return GetCharCount(pBytes + index, count, flush); } public unsafe override int GetCharCount(byte* bytes, int count, bool flush) { // Validate parameters if (bytes == null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); // Remember the flush _mustFlush = flush; _throwOnOverflow = true; // By default just call the encoding version, no flush by default return _encoding.GetCharCount(bytes, count, this); } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { return GetChars(bytes, byteIndex, byteCount, chars, charIndex, false); } public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException(nameof(charIndex), SR.ArgumentOutOfRange_Index); int charCount = chars.Length - charIndex; // Just call pointer version fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes)) fixed (char* pChars = &MemoryMarshal.GetReference((Span<char>)chars)) // Remember that charCount is # to decode, not size of array return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush); } public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)), SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); // Remember our flush _mustFlush = flush; _throwOnOverflow = true; // By default just call the encodings version return _encoding.GetChars(bytes, byteCount, chars, charCount, this); } // This method is used when the output buffer might not be big enough. // Just call the pointer version. (This gets chars) public override unsafe void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { // Validate parameters if (bytes == null || chars == null) throw new ArgumentNullException((bytes == null ? nameof(bytes) : nameof(chars)), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); // Just call the pointer version (public overrides can't do this) fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes)) { fixed (char* pChars = &MemoryMarshal.GetReference((Span<char>)chars)) { Convert(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush, out bytesUsed, out charsUsed, out completed); } } } // This is the version that used pointers. We call the base encoding worker function // after setting our appropriate internal variables. This is getting chars public unsafe override void Convert(byte* bytes, int byteCount, char* chars, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { // Validate input parameters if (chars == null || bytes == null) throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); // We don't want to throw _mustFlush = flush; _throwOnOverflow = false; _bytesUsed = 0; // Do conversion charsUsed = _encoding.GetChars(bytes, byteCount, chars, charCount, this); bytesUsed = _bytesUsed; // Its completed if they've used what they wanted AND if they didn't want flush or if we are flushed completed = (bytesUsed == byteCount) && (!flush || !this.HasState) && (_fallbackBuffer == null || _fallbackBuffer.Remaining == 0); // Our data thingy are now full, we can return } public bool MustFlush { get { return _mustFlush; } } // Anything left in our decoder? internal virtual bool HasState { get { return false; } } // Allow encoding to clear our must flush instead of throwing (in ThrowCharsOverflow) internal void ClearMustFlush() { _mustFlush = false; } } }
// Deployment Framework for BizTalk // Copyright (C) 2008-14 Thomas F. Abraham, 2004-08 Scott Colestock // This source file is subject to the Microsoft Public License (Ms-PL). // See http://www.opensource.org/licenses/ms-pl.html. // All other rights reserved. using System; using log4net; using log4net.helpers; using log4net.Core; using log4net.Util; using System.Runtime.Serialization; using System.Globalization; namespace log4net.Ext.Serializable { [Serializable] public class SLog : ILoggerWrapper, ISerializable, ILog { #region Private members private enum ConfigMethod {None,RegistryConfigurator, AppConfigConfigurator}; private ILogger _logger; private string _fullName; private string _loggerName; private PropertiesDictionary _properties = new PropertiesDictionary(); private ConfigMethod _configMethod = ConfigMethod.None; private string _domainName; private readonly static Type _slogType = typeof(SLog); #endregion #region Serialization Constructor private SLog(SerializationInfo info, StreamingContext context) { _loggerName = (string)info.GetValue("loggerName",typeof(string)); _domainName = (string)info.GetValue("domainName",typeof(string)); _properties = (PropertiesDictionary)info.GetValue("properties",typeof(PropertiesDictionary)); SLogManager.CreateDomainIfNeeded(_domainName); // We don't want to go through SLogManager, because we want to inject THIS deserialized // instance into SLogManager's map. _logger = LogManager.GetLogger(_domainName,_loggerName).Logger; _configMethod = (ConfigMethod)info.GetValue("configMethod",typeof(int)); if(_configMethod == ConfigMethod.RegistryConfigurator) { log4net.Ext.Config.RegistryConfigurator.ConfigureAndWatch(_domainName,_domainName); } if(_configMethod == ConfigMethod.AppConfigConfigurator) { log4net.Ext.Config.AppConfigConfigurator.ConfigureAndWatch(_domainName, _domainName); //log4net.Config.XmlConfigurator.Configure(); } // Get this deserialized instance to the wrapper map so it will be used by others asking for a // logger of the same name. SLogManager.AddToMap(_logger,this); //System.Diagnostics.Trace.WriteLine("Deserializing SLog..." + this.GetHashCode() + ":" + descount++); } //private static int descount = 0; #endregion #region Public Instance Constructors public SLog(ILogger logger) { _logger = logger; _fullName = this.GetType().FullName; _loggerName = logger.Name; _domainName = logger.Repository.Name; } #endregion Public Instance Constructors #region Public Properties and methods [Obsolete("This member was discovered to not be threadsafe. Use the PropertiesCollectionEx class and associated overrides for Info/Log/Warn/Debug instead.")] public log4net.Util.PropertiesDictionary Properties {get{return _properties;}} // Offered as a convenience to add a item called InstanceId to the standard // properties collection. Used currently by the Paul Bunyan appender to populate // the context field. [Obsolete("This member was discovered to not be threadsafe. Use the PropertiesCollectionEx class and associated overrides for Info/Log/Warn/Debug instead.")] public string InstanceId { get { return (string)_properties["InstanceId"]; } set { _properties["InstanceId"] = value; } } /// <summary> /// This logger offers the ability to use at least one configurator, so it can store /// state information about how log4net was configured to be used if the appdomain is recycled. /// </summary> /// <param name="registryPath"></param> public void RegistryConfigurator() { _configMethod = ConfigMethod.RegistryConfigurator; // Here, we are making our domain name be equal to the registry path used for configuration. log4net.Ext.Config.RegistryConfigurator.ConfigureAndWatch(_domainName,_domainName); } public void AppConfigConfigurator() { _configMethod = ConfigMethod.AppConfigConfigurator; // Here, we are making our domain name be equal to the App.Settings key used for configuration. log4net.Ext.Config.AppConfigConfigurator.ConfigureAndWatch(_domainName,_domainName); //log4net.Config.XmlConfigurator.Configure(); } #endregion #region Implementation of ILog private LoggingEventData CreateEventData( Level level, object message, Exception t, PropertiesCollectionEx props) { LoggingEventData data = new LoggingEventData(); data.Message = message.ToString(); data.ExceptionString = t==null?null:t.ToString(); data.Properties = props == null ?null:props.PropertiesCollection; data.LocationInfo = new LocationInfo(_slogType); data.Domain = _domainName; data.LoggerName = _logger.Name; data.Level = level; data.TimeStamp = DateTime.Now; return data; } public void Debug(object message) { Debug(null,message, null); } public void Debug(PropertiesCollectionEx props, object message) { Debug(props,message,null); } public void Debug(object message, System.Exception t) { Debug(null,message,t); } public void Debug(PropertiesCollectionEx props,object message, System.Exception t) { if (_logger.IsEnabledFor(log4net.Core.Level.Debug)) { LoggingEvent loggingEvent = new LoggingEvent(CreateEventData(Level.Debug,message,t,props)); _logger.Log(loggingEvent); } } void log4net.ILog.DebugFormat(IFormatProvider provider, string format, params object[] args) { Logger.Log(_slogType, log4net.Core.Level.Debug, String.Format(provider, format, args), null); } void log4net.ILog.DebugFormat(string format, params object[] args) { Logger.Log(_slogType, log4net.Core.Level.Debug, String.Format(CultureInfo.InvariantCulture, format, args), null); } void log4net.ILog.DebugFormat(string format, object arg0) { Logger.Log(_slogType, log4net.Core.Level.Debug, String.Format(CultureInfo.InvariantCulture, format, arg0), null); } void log4net.ILog.DebugFormat(string format, object arg0, object arg1) { Logger.Log(_slogType, log4net.Core.Level.Debug, String.Format(CultureInfo.InvariantCulture, format, arg0, arg1), null); } void log4net.ILog.DebugFormat(string format, object arg0, object arg1, object arg2) { Logger.Log(_slogType, log4net.Core.Level.Debug, String.Format(CultureInfo.InvariantCulture, format, arg0, arg1, arg2), null); } public void DebugFormat(PropertiesCollectionEx props, string format, params object[] args) { if (_logger.IsEnabledFor(log4net.Core.Level.Debug)) { LoggingEvent loggingEvent = new LoggingEvent(CreateEventData(Level.Debug,String.Format(format, args),null,props)); _logger.Log(loggingEvent); } } public void Info(object message) { Info(null,message,null); } public void Info(PropertiesCollectionEx props,object message) { Info(props,message,null); } public void Info(object message, System.Exception t) { Info(null,message,t); } public void Info(PropertiesCollectionEx props,object message,System.Exception t) { if (_logger.IsEnabledFor(log4net.Core.Level.Info)) { LoggingEvent loggingEvent = new LoggingEvent(CreateEventData(Level.Info,message,t,props)); _logger.Log(loggingEvent); } } void log4net.ILog.InfoFormat(IFormatProvider provider, string format, params object[] args) { Logger.Log(_slogType, log4net.Core.Level.Info, String.Format(provider, format, args), null); } void log4net.ILog.InfoFormat(string format, params object[] args) { Logger.Log(_slogType, log4net.Core.Level.Info, String.Format(CultureInfo.InvariantCulture, format, args), null); } void log4net.ILog.InfoFormat(string format, object arg0) { Logger.Log(_slogType, log4net.Core.Level.Info, String.Format(CultureInfo.InvariantCulture, format, arg0), null); } void log4net.ILog.InfoFormat(string format, object arg0, object arg1) { Logger.Log(_slogType, log4net.Core.Level.Info, String.Format(CultureInfo.InvariantCulture, format, arg0, arg1), null); } void log4net.ILog.InfoFormat(string format, object arg0, object arg1, object arg2) { Logger.Log(_slogType, log4net.Core.Level.Info, String.Format(CultureInfo.InvariantCulture, format, arg0, arg1, arg2), null); } public void InfoFormat(PropertiesCollectionEx props, string format, params object[] args) { if (_logger.IsEnabledFor(log4net.Core.Level.Info)) { LoggingEvent loggingEvent = new LoggingEvent(CreateEventData(Level.Info,String.Format(format, args),null,props)); _logger.Log(loggingEvent); } } public void Warn(object message) { Warn(null,message, null); } public void Warn(PropertiesCollectionEx props,object message) { Warn(props,message, null); } public void Warn(object message, System.Exception t) { Warn(null,message, t); } public void Warn(PropertiesCollectionEx props, object message, System.Exception t) { if (_logger.IsEnabledFor(log4net.Core.Level.Warn)) { LoggingEvent loggingEvent = new LoggingEvent(CreateEventData(Level.Warn,message,t,props)); _logger.Log(loggingEvent); } } void log4net.ILog.WarnFormat(IFormatProvider provider, string format, params object[] args) { Logger.Log(_slogType, log4net.Core.Level.Warn, String.Format(provider, format, args), null); } void log4net.ILog.WarnFormat(string format, params object[] args) { Logger.Log(_slogType, log4net.Core.Level.Warn, String.Format(CultureInfo.InvariantCulture, format, args), null); } void log4net.ILog.WarnFormat(string format, object arg0) { Logger.Log(_slogType, log4net.Core.Level.Warn, String.Format(CultureInfo.InvariantCulture, format, arg0), null); } void log4net.ILog.WarnFormat(string format, object arg0, object arg1) { Logger.Log(_slogType, log4net.Core.Level.Warn, String.Format(CultureInfo.InvariantCulture, format, arg0, arg1), null); } void log4net.ILog.WarnFormat(string format, object arg0, object arg1, object arg2) { Logger.Log(_slogType, log4net.Core.Level.Warn, String.Format(CultureInfo.InvariantCulture, format, arg0, arg1, arg2), null); } public void WarnFormat(PropertiesCollectionEx props, string format, params object[] args) { if (_logger.IsEnabledFor(log4net.Core.Level.Warn)) { LoggingEvent loggingEvent = new LoggingEvent(CreateEventData(Level.Warn,String.Format(format, args),null,props)); _logger.Log(loggingEvent); } } public void Error(object message) { Error(null,message, null); } public void Error(PropertiesCollectionEx props,object message) { Error(props,message, null); } public void Error(object message, System.Exception t) { Error(null, message, t); } public void Error(PropertiesCollectionEx props, object message, System.Exception t) { if (_logger.IsEnabledFor(log4net.Core.Level.Error)) { LoggingEvent loggingEvent = new LoggingEvent(CreateEventData(Level.Error,message,t, props)); _logger.Log(loggingEvent); } } void log4net.ILog.ErrorFormat(IFormatProvider provider, string format, params object[] args) { Logger.Log(_slogType, log4net.Core.Level.Error, String.Format(provider, format, args), null); } void log4net.ILog.ErrorFormat(string format, params object[] args) { Logger.Log(_slogType, log4net.Core.Level.Error, String.Format(CultureInfo.InvariantCulture, format, args), null); } void log4net.ILog.ErrorFormat(string format, object arg0) { Logger.Log(_slogType, log4net.Core.Level.Error, String.Format(CultureInfo.InvariantCulture, format, arg0), null); } void log4net.ILog.ErrorFormat(string format, object arg0, object arg1) { Logger.Log(_slogType, log4net.Core.Level.Error, String.Format(CultureInfo.InvariantCulture, format, arg0, arg1), null); } void log4net.ILog.ErrorFormat(string format, object arg0, object arg1, object arg2) { Logger.Log(_slogType, log4net.Core.Level.Error, String.Format(CultureInfo.InvariantCulture, format, arg0, arg1, arg2), null); } public void ErrorFormat(PropertiesCollectionEx props, string format, params object[] args) { if (_logger.IsEnabledFor(log4net.Core.Level.Error)) { LoggingEvent loggingEvent = new LoggingEvent(CreateEventData(Level.Error,String.Format(format, args),null,props)); _logger.Log(loggingEvent); } } public void Fatal(object message) { Fatal(null, message, null); } public void Fatal(PropertiesCollectionEx props,object message) { Fatal(props, message, null); } public void Fatal(object message, System.Exception t) { Fatal(null,message,t); } public void Fatal(PropertiesCollectionEx props,object message, System.Exception t) { if (_logger.IsEnabledFor(log4net.Core.Level.Fatal)) { LoggingEvent loggingEvent = new LoggingEvent(CreateEventData(Level.Fatal,message,t,props)); _logger.Log(loggingEvent); } } void log4net.ILog.FatalFormat(IFormatProvider provider, string format, params object[] args) { Logger.Log(_slogType, log4net.Core.Level.Fatal, String.Format(provider, format, args), null); } void log4net.ILog.FatalFormat(string format, params object[] args) { Logger.Log(_slogType, log4net.Core.Level.Fatal, String.Format(CultureInfo.InvariantCulture, format, args), null); } void log4net.ILog.FatalFormat(string format, object arg0) { Logger.Log(_slogType, log4net.Core.Level.Fatal, String.Format(CultureInfo.InvariantCulture, format, arg0), null); } void log4net.ILog.FatalFormat(string format, object arg0, object arg1) { Logger.Log(_slogType, log4net.Core.Level.Fatal, String.Format(CultureInfo.InvariantCulture, format, arg0, arg1), null); } void log4net.ILog.FatalFormat(string format, object arg0, object arg1, object arg2) { Logger.Log(_slogType, log4net.Core.Level.Fatal, String.Format(CultureInfo.InvariantCulture, format, arg0, arg1, arg2), null); } public void FatalFormat(PropertiesCollectionEx props, string format, params object[] args) { if (_logger.IsEnabledFor(log4net.Core.Level.Fatal)) { LoggingEvent loggingEvent = new LoggingEvent(CreateEventData(Level.Fatal,String.Format(format, args),null,props)); _logger.Log(loggingEvent); } } public bool IsErrorEnabled { get { return _logger.IsEnabledFor(log4net.Core.Level.Error); } } public bool IsFatalEnabled { get { return _logger.IsEnabledFor(log4net.Core.Level.Fatal); } } public bool IsWarnEnabled { get { return _logger.IsEnabledFor(log4net.Core.Level.Warn); } } public bool IsInfoEnabled { get { return _logger.IsEnabledFor(log4net.Core.Level.Info); } } public bool IsDebugEnabled { get { return _logger.IsEnabledFor(log4net.Core.Level.Debug); } } #endregion Implementation of ILog #region ILoggerWrapper Members public ILogger Logger { get { return _logger; } } #endregion #region ISerializable Members public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("loggerName",_loggerName); info.AddValue("properties",_properties); info.AddValue("configMethod",(int)_configMethod); info.AddValue("domainName",_domainName); //System.Diagnostics.Trace.WriteLine("Serializing SLog..." + this.GetHashCode() + ":" + sercount++); } //private static int sercount=0; #endregion } }
// // - ServiceProvider.cs - // // Copyright 2005, 2006, 2010 Carbonfrost Systems, Inc. (http://carbonfrost.com) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Carbonfrost.Commons.Shared.Runtime; namespace Carbonfrost.Commons.Shared { public static class ServiceProvider { static readonly IServiceProvider _null = new NullServiceProvider(); static readonly object _rootInit = new object(); static readonly string rootType; static IServiceProvider _root; public static IServiceProvider Null { get { return _null; } } public static IServiceProvider Root { get { EnsureRootInit(); return _root; } } static readonly ThreadLocal<Stack<IServiceProvider>> _current = new ThreadLocal<Stack<IServiceProvider>>(() => new Stack<IServiceProvider>()); public static IServiceProvider Current { get { if (_current.Value.Count == 0) return ServiceProvider.Root; else return _current.Value.Peek(); } } static void EnsureRootInit() { if (Monitor.TryEnter(_rootInit)) { try { if (rootType.Length > 0) { _root = Activation.CreateInstance<IServiceProvider>( Type.GetType(rootType)); } } catch (Exception ex) { Traceables.RootServiceProviderInitFailure(rootType, ex); } finally { Monitor.Exit(_rootInit); } if (_root == null) { _root = new FrameworkServiceContainer(); } } } static ServiceProvider() { ServiceProvider.rootType = Convert.ToString(AppDomain.CurrentDomain.GetData(AppDomainProperty.RootServiceProvider)) ?? string.Empty; } public static T GetService<T>(this IServiceProvider serviceProvider) { if (serviceProvider == null) throw new ArgumentNullException("serviceProvider"); // $NON-NLS-1 T t = (T) serviceProvider.GetService(typeof(T)); if (object.Equals(t, default(T))) throw RuntimeFailure.ServiceNotFound(typeof(T)); return t; } public static T TryGetService<T>(this IServiceProvider serviceProvider, T defaultService = default(T)) { if (serviceProvider == null) throw new ArgumentNullException("serviceProvider"); // $NON-NLS-1 T t = (T) serviceProvider.GetService(typeof(T)); if (object.Equals(t, default(T))) return defaultService; else return t; } public static IEnumerable<T> GetServices<T>(this IServiceProviderExtension serviceProvider) { if (serviceProvider == null) throw new ArgumentNullException("serviceProvider"); // $NON-NLS-1 var result = serviceProvider.GetServices(typeof(T)); if (result == null) return Empty<T>.Array; else return result.Cast<T>(); } public static IServiceProviderExtension Extend(this IServiceProvider serviceProvider) { if (serviceProvider == null) throw new ArgumentNullException("serviceProvider"); IServiceProviderExtension e = serviceProvider as IServiceProviderExtension; if (e != null) return e; return new ServiceProviderExtension(serviceProvider); } public static IServiceProvider FromValue(object value) { if (value == null) throw new ArgumentNullException("value"); IServiceProvider s = value as IServiceProvider; if (s == null) return new ServiceProviderValue(value); else return s; } public static IServiceProvider Filtered(IServiceProvider serviceProvider, Func<Type, bool> typeFilter) { if (serviceProvider == null || serviceProvider == Null) return Null; if (typeFilter == null) return serviceProvider; return new FilteredServiceProvider(typeFilter, serviceProvider); } public static IServiceProvider Filtered(IServiceProvider serviceProvider, params Type[] types) { if (serviceProvider == null || serviceProvider == Null) return Null; if (types == null || types.Length == 0) return serviceProvider; ICollection<Type> myTypes; if (types.Length > 8) myTypes = new HashSet<Type>(types); else myTypes = new List<Type>(types); return Filtered(serviceProvider, t => myTypes.Contains(t)); } public static IServiceProvider FromValue(object value, params Type[] types) { if (value == null) throw new ArgumentNullException("value"); return Filtered(FromValue(value), types); } public static IServiceProvider Compose(IEnumerable<IServiceProvider> items) { return Utility.OptimalComposite(items, i => new CompositeServiceProvider(i), Null); } public static IServiceProvider Compose(IEnumerable<IServiceProviderExtension> items) { return Utility.OptimalComposite(items, i => new CompositeServiceProviderExtension(i), (IServiceProviderExtension) Null); } public static IServiceProvider Compose(params IServiceProvider[] items) { return Utility.OptimalComposite(items, i => new CompositeServiceProvider(i), Null); } public static IServiceProviderExtension Compose(params IServiceProviderExtension[] items) { return Utility.OptimalComposite(items, i => new CompositeServiceProviderExtension(i), (IServiceProviderExtension) Null); } // Nested type definitions class NullServiceProvider : IServiceProviderExtension { public object GetService(Type serviceType) { if (serviceType == null) throw new ArgumentNullException("serviceType"); // $NON-NLS-1 return null; } public object GetService(string serviceName) { Require.NotNullOrEmptyString("serviceName", serviceName); // $NON-NLS-1 return null; } public IEnumerable<object> GetServices(Type serviceType) { if (serviceType == null) throw new ArgumentNullException("serviceType"); return Empty<object>.Array; } } class CompositeServiceProvider : IServiceProvider { private readonly IReadOnlyCollection<IServiceProvider> items; public CompositeServiceProvider(IReadOnlyCollection<IServiceProvider> items) { this.items = items; } public object GetService(Type serviceType) { if (serviceType == null) throw new ArgumentNullException("serviceType"); foreach (var s in items) { object result = s.GetService(serviceType); if (result != null) return result; } return null; } } class ServiceProviderExtension : IServiceProviderExtension { private readonly IServiceProvider item; public ServiceProviderExtension(IServiceProvider item) { this.item = item; } public object GetService(string serviceName) { return null; } public IEnumerable<object> GetServices(Type serviceType) { if (serviceType == null) throw new ArgumentNullException("serviceType"); yield return item.GetService(serviceType); } public object GetService(Type serviceType) { if (serviceType == null) throw new ArgumentNullException("serviceType"); return item.GetService(serviceType); } } sealed class ServiceProviderValue : IServiceProvider { private readonly object value; public ServiceProviderValue(object value) { this.value = value; } public object GetService(Type serviceType) { if (serviceType == null) throw new ArgumentNullException("serviceType"); return value.TryAdapt(serviceType, null); } } sealed class FilteredServiceProvider : IServiceProvider { private readonly Func<Type, bool> types; private readonly IServiceProvider sp; public FilteredServiceProvider(Func<Type, bool> types, IServiceProvider sp) { this.sp = sp; this.types = types; } public object GetService(Type serviceType) { if (serviceType == null) throw new ArgumentNullException("serviceType"); if (types(serviceType)) return sp.GetService(serviceType); else return null; } } class CompositeServiceProviderExtension : CompositeServiceProvider, IServiceProviderExtension { private readonly IReadOnlyCollection<IServiceProviderExtension> items; public CompositeServiceProviderExtension(IReadOnlyCollection<IServiceProviderExtension> items) : base(items) { this.items = items; } public object GetService(string serviceName) { if (serviceName == null) throw new ArgumentNullException("serviceName"); if (serviceName.Length == 0) throw Failure.EmptyString("serviceName"); return items.FirstNonNull(i => i.GetService(serviceName)); } public IEnumerable<object> GetServices(Type serviceType) { if (serviceType == null) throw new ArgumentNullException("serviceType"); return items.SelectMany(t => t.GetServices(serviceType)); } } internal static void PushCurrent(IServiceProvider serviceProvider) { _current.Value.Push(serviceProvider); } internal static void PopCurrent() { _current.Value.Pop(); } } }
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Lucene.Net.Codecs.Bloom { using System; using System.Diagnostics; using System.Linq; using Store; using Util; /// <summary> /// A class used to represent a set of many, potentially large, values (e.g. many /// long strings such as URLs), using a significantly smaller amount of memory. /// /// The set is "lossy" in that it cannot definitively state that is does contain /// a value but it <em>can</em> definitively say if a value is <em>not</em> in /// the set. It can therefore be used as a Bloom Filter. /// /// Another application of the set is that it can be used to perform fuzzy counting because /// it can estimate reasonably accurately how many unique values are contained in the set. /// /// This class is NOT threadsafe. /// /// Internally a Bitset is used to record values and once a client has finished recording /// a stream of values the {@link #downsize(float)} method can be used to create a suitably smaller set that /// is sized appropriately for the number of values recorded and desired saturation levels. /// /// @lucene.experimental /// </summary> public class FuzzySet { public static readonly int VERSION_SPI = 1; // HashFunction used to be loaded through a SPI public static readonly int VERSION_START = VERSION_SPI; public static readonly int VERSION_CURRENT = 2; public static HashFunction HashFunctionForVersion(int version) { if (version < VERSION_START) throw new ArgumentException("Version " + version + " is too old, expected at least " + VERSION_START); if (version > VERSION_CURRENT) throw new ArgumentException("Version " + version + " is too new, expected at most " + VERSION_CURRENT); return MurmurHash2.INSTANCE; } /// <remarks> /// Result from {@link FuzzySet#contains(BytesRef)}: /// can never return definitively YES (always MAYBE), /// but can sometimes definitely return NO. /// </remarks> public enum ContainsResult { Maybe, No }; private readonly HashFunction _hashFunction; private readonly FixedBitSet _filter; private readonly int _bloomSize; //The sizes of BitSet used are all numbers that, when expressed in binary form, //are all ones. This is to enable fast downsizing from one bitset to another //by simply ANDing each set index in one bitset with the size of the target bitset // - this provides a fast modulo of the number. Values previously accumulated in // a large bitset and then mapped to a smaller set can be looked up using a single // AND operation of the query term's hash rather than needing to perform a 2-step // translation of the query term that mirrors the stored content's reprojections. private static int[] _usableBitSetSizes; private static int[] UsableBitSetSizes { get { if (_usableBitSetSizes == null) InitializeUsableBitSetSizes(); return _usableBitSetSizes; } set { _usableBitSetSizes = value; } } private static void InitializeUsableBitSetSizes() { UsableBitSetSizes = new int[30]; const int mask = 1; var size = mask; for (var i = 0; i < UsableBitSetSizes.Length; i++) { size = (size << 1) | mask; UsableBitSetSizes[i] = size; } } /// <summary> /// Rounds down required maxNumberOfBits to the nearest number that is made up /// of all ones as a binary number. /// Use this method where controlling memory use is paramount. /// </summary> public static int GetNearestSetSize(int maxNumberOfBits) { var result = UsableBitSetSizes[0]; foreach (var t in UsableBitSetSizes.Where(t => t <= maxNumberOfBits)) { result = t; } return result; } /// <summary> /// Use this method to choose a set size where accuracy (low content saturation) is more important /// than deciding how much memory to throw at the problem. /// </summary> /// <param name="maxNumberOfValuesExpected"></param> /// <param name="desiredSaturation">A number between 0 and 1 expressing the % of bits set once all values have been recorded</param> /// <returns>The size of the set nearest to the required size</returns> public static int GetNearestSetSize(int maxNumberOfValuesExpected, float desiredSaturation) { // Iterate around the various scales of bitset from smallest to largest looking for the first that // satisfies value volumes at the chosen saturation level foreach (var t in from t in UsableBitSetSizes let numSetBitsAtDesiredSaturation = (int) (t*desiredSaturation) let estimatedNumUniqueValues = GetEstimatedNumberUniqueValuesAllowingForCollisions( t, numSetBitsAtDesiredSaturation) where estimatedNumUniqueValues > maxNumberOfValuesExpected select t) { return t; } return -1; } public static FuzzySet CreateSetBasedOnMaxMemory(int maxNumBytes) { var setSize = GetNearestSetSize(maxNumBytes); return new FuzzySet(new FixedBitSet(setSize + 1), setSize, HashFunctionForVersion(VERSION_CURRENT)); } public static FuzzySet CreateSetBasedOnQuality(int maxNumUniqueValues, float desiredMaxSaturation) { var setSize = GetNearestSetSize(maxNumUniqueValues, desiredMaxSaturation); return new FuzzySet(new FixedBitSet(setSize + 1), setSize, HashFunctionForVersion(VERSION_CURRENT)); } private FuzzySet(FixedBitSet filter, int bloomSize, HashFunction hashFunction) { _filter = filter; _bloomSize = bloomSize; _hashFunction = hashFunction; } /// <summary> /// The main method required for a Bloom filter which, given a value determines set membership. /// Unlike a conventional set, the fuzzy set returns NO or MAYBE rather than true or false. /// </summary> /// <returns>NO or MAYBE</returns> public ContainsResult Contains(BytesRef value) { var hash = _hashFunction.Hash(value); if (hash < 0) { hash = hash*-1; } return MayContainValue(hash); } /// <summary> /// Serializes the data set to file using the following format: /// <ul> /// <li>FuzzySet --&gt;FuzzySetVersion,HashFunctionName,BloomSize, /// NumBitSetWords,BitSetWord<sup>NumBitSetWords</sup></li> /// <li>HashFunctionName --&gt; {@link DataOutput#writeString(String) String} The /// name of a ServiceProvider registered {@link HashFunction}</li> /// <li>FuzzySetVersion --&gt; {@link DataOutput#writeInt Uint32} The version number of the {@link FuzzySet} class</li> /// <li>BloomSize --&gt; {@link DataOutput#writeInt Uint32} The modulo value used /// to project hashes into the field's Bitset</li> /// <li>NumBitSetWords --&gt; {@link DataOutput#writeInt Uint32} The number of /// longs (as returned from {@link FixedBitSet#getBits})</li> /// <li>BitSetWord --&gt; {@link DataOutput#writeLong Long} A long from the array /// returned by {@link FixedBitSet#getBits}</li> /// </ul> /// @param out Data output stream /// @ If there is a low-level I/O error /// </summary> public void Serialize(DataOutput output) { output.WriteInt(VERSION_CURRENT); output.WriteInt(_bloomSize); var bits = _filter.Bits; output.WriteInt(bits.Length); foreach (var t in bits) { // Can't used VLong encoding because cant cope with negative numbers // output by FixedBitSet output.WriteLong(t); } } public static FuzzySet Deserialize(DataInput input) { var version = input.ReadInt(); if (version == VERSION_SPI) input.ReadString(); var hashFunction = HashFunctionForVersion(version); var bloomSize = input.ReadInt(); var numLongs = input.ReadInt(); var longs = new long[numLongs]; for (var i = 0; i < numLongs; i++) { longs[i] = input.ReadLong(); } var bits = new FixedBitSet(longs, bloomSize + 1); return new FuzzySet(bits, bloomSize, hashFunction); } private ContainsResult MayContainValue(int positiveHash) { Debug.Assert((positiveHash >= 0)); // Bloom sizes are always base 2 and so can be ANDed for a fast modulo var pos = positiveHash & _bloomSize; return _filter.Get(pos) ? ContainsResult.Maybe : ContainsResult.No; } /// <summary> /// Records a value in the set. The referenced bytes are hashed and then modulo n'd where n is the /// chosen size of the internal bitset. /// </summary> /// <param name="value">The Key value to be hashed</param> public void AddValue(BytesRef value) { var hash = _hashFunction.Hash(value); if (hash < 0) { hash = hash*-1; } // Bitmasking using bloomSize is effectively a modulo operation. var bloomPos = hash & _bloomSize; _filter.Set(bloomPos); } /// <param name="targetMaxSaturation"> /// A number between 0 and 1 describing the % of bits that would ideally be set in the result. /// Lower values have better accuracy but require more space. /// </param> /// <return>A smaller FuzzySet or null if the current set is already over-saturated</return> public FuzzySet Downsize(float targetMaxSaturation) { var numBitsSet = _filter.Cardinality(); FixedBitSet rightSizedBitSet; var rightSizedBitSetSize = _bloomSize; //Hopefully find a smaller size bitset into which we can project accumulated values while maintaining desired saturation level foreach (var candidateBitsetSize in from candidateBitsetSize in UsableBitSetSizes let candidateSaturation = numBitsSet /(float) candidateBitsetSize where candidateSaturation <= targetMaxSaturation select candidateBitsetSize) { rightSizedBitSetSize = candidateBitsetSize; break; } // Re-project the numbers to a smaller space if necessary if (rightSizedBitSetSize < _bloomSize) { // Reset the choice of bitset to the smaller version rightSizedBitSet = new FixedBitSet(rightSizedBitSetSize + 1); // Map across the bits from the large set to the smaller one var bitIndex = 0; do { bitIndex = _filter.NextSetBit(bitIndex); if (bitIndex < 0) continue; // Project the larger number into a smaller one effectively // modulo-ing by using the target bitset size as a mask var downSizedBitIndex = bitIndex & rightSizedBitSetSize; rightSizedBitSet.Set(downSizedBitIndex); bitIndex++; } while ((bitIndex >= 0) && (bitIndex <= _bloomSize)); } else { return null; } return new FuzzySet(rightSizedBitSet, rightSizedBitSetSize, _hashFunction); } public int GetEstimatedUniqueValues() { return GetEstimatedNumberUniqueValuesAllowingForCollisions(_bloomSize, _filter.Cardinality()); } // Given a set size and a the number of set bits, produces an estimate of the number of unique values recorded public static int GetEstimatedNumberUniqueValuesAllowingForCollisions( int setSize, int numRecordedBits) { double setSizeAsDouble = setSize; double numRecordedBitsAsDouble = numRecordedBits; var saturation = numRecordedBitsAsDouble/setSizeAsDouble; var logInverseSaturation = Math.Log(1 - saturation)*-1; return (int) (setSizeAsDouble*logInverseSaturation); } public float GetSaturation() { var numBitsSet = _filter.Cardinality(); return numBitsSet/(float) _bloomSize; } public long RamBytesUsed() { return RamUsageEstimator.SizeOf(_filter.GetBits()); } } }