context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using Helios.Util; namespace Helios.Buffers { /// <summary> /// Concrete ByteBuffer implementation that uses a simple backing array /// </summary> public class ByteBuffer : AbstractByteBuf { protected byte[] Buffer; private int _capacity; public static ByteBuffer AllocateDirect(int capacity, int maxCapacity = Int32.MaxValue) { return new ByteBuffer(capacity, maxCapacity); } /// <summary> /// Copy constructor /// </summary> internal protected ByteBuffer(byte[] buffer, int initialCapacity, int maxCapacity) : base(maxCapacity) { if (initialCapacity < 0) throw new ArgumentOutOfRangeException("initialCapacity", "initialCapacity must be at least 0"); if (maxCapacity < 0) throw new ArgumentOutOfRangeException("maxCapacity", "maxCapacity must be at least 0"); if (initialCapacity > maxCapacity) throw new ArgumentException(string.Format("initialCapacity {0} must be less than maxCapacity {1}", initialCapacity, maxCapacity)); Buffer = buffer; _capacity = initialCapacity; } protected ByteBuffer(int initialCapacity, int maxCapacity) : this(new byte[initialCapacity], initialCapacity, maxCapacity) { } public override int Capacity { get { return _capacity; } } public override IByteBuf AdjustCapacity(int newCapacity) { if (newCapacity > MaxCapacity) throw new ArgumentOutOfRangeException("newCapacity", string.Format("capacity({0}) must be less than MaxCapacity({1})", newCapacity, MaxCapacity)); var newBuffer = new byte[newCapacity]; //expand if (newCapacity > Capacity) { Array.Copy(Buffer, ReaderIndex, newBuffer, 0, ReadableBytes); SetIndex(0, ReadableBytes); } else //shrink { Array.Copy(Buffer, ReaderIndex, newBuffer, 0, newCapacity); if (ReaderIndex < newCapacity) { if (WriterIndex > newCapacity) { SetWriterIndex(newCapacity); } else { SetWriterIndex(ReadableBytes); } SetReaderIndex(0); } else { SetIndex(newCapacity, newCapacity); } } Buffer = newBuffer; _capacity = newCapacity; return this; } public override IByteBufAllocator Allocator { get { throw new NotImplementedException(); } } protected override byte _GetByte(int index) { return Buffer[index]; } protected override short _GetShort(int index) { return BitConverter.ToInt16(Buffer.Slice(index, 2), 0); } protected override int _GetInt(int index) { return BitConverter.ToInt32(Buffer.Slice(index, 4), 0); } protected override long _GetLong(int index) { return BitConverter.ToInt64(Buffer.Slice(index, 8), 0); } public override IByteBuf ReadBytes(int length) { CheckReadableBytes(length); if (length == 0) return Unpooled.Empty; var buf = new byte[length]; Array.Copy(Buffer, ReaderIndex, buf, 0, length); ReaderIndex += length; return new ByteBuffer(buf, length, length).SetWriterIndex(length); } public override IByteBuf GetBytes(int index, IByteBuf destination, int dstIndex, int length) { CheckDstIndex(index, length, dstIndex, destination.WritableBytes); destination.SetBytes(dstIndex, Buffer.Slice(index, length), 0, length); return this; } public override IByteBuf GetBytes(int index, byte[] destination, int dstIndex, int length) { CheckDstIndex(index, length, dstIndex, destination.Length); System.Array.Copy(Buffer, index, destination, dstIndex, length); return this; } protected override IByteBuf _SetByte(int index, int value) { Buffer.SetValue((byte)value, index); return this; } protected override IByteBuf _SetShort(int index, int value) { unchecked { Buffer.SetRange(index, BitConverter.GetBytes((short)(value))); } return this; } protected override IByteBuf _SetInt(int index, int value) { Buffer.SetRange(index, BitConverter.GetBytes(value)); return this; } protected override IByteBuf _SetLong(int index, long value) { Buffer.SetRange(index, BitConverter.GetBytes(value)); return this; } public override IByteBuf SetBytes(int index, IByteBuf src, int srcIndex, int length) { CheckSrcIndex(index, length, srcIndex, src.ReadableBytes); if (src.HasArray) { Buffer.SetRange(index, src.InternalArray().Slice(srcIndex, length)); } else { src.ReadBytes(Buffer, srcIndex, length); } return this; } public override IByteBuf SetBytes(int index, byte[] src, int srcIndex, int length) { CheckSrcIndex(index, length, srcIndex, src.Length); System.Array.Copy(src, srcIndex, Buffer, index, length); return this; } public override bool HasArray { get { return true; } } public override byte[] InternalArray() { return Buffer; } public override bool IsDirect { get { return true; } } public override IByteBuf Unwrap() { return null; } public override ByteBuffer InternalNioBuffer(int index, int length) { return (ByteBuffer)(Duplicate()).Clear().SetIndex(index, length); } public override IByteBuf CompactIfNecessary() { return Compact(); } public override IByteBuf Compact() { var buffer = new byte[Capacity]; Array.Copy(Buffer, ReaderIndex, buffer, 0, ReadableBytes); Buffer = buffer; SetIndex(0, ReadableBytes); return this; } /// <summary> /// Duplicate for <see cref="ByteBuffer"/> instances actually creates a deep clone, rather than a proxy /// </summary> public IByteBuf DeepDuplicate() { var buffer = new byte[Capacity]; Array.Copy(Buffer, ReaderIndex, buffer, 0, ReadableBytes); return new ByteBuffer(buffer, Capacity, MaxCapacity).SetIndex(ReaderIndex, WriterIndex); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace HoundRace.Web.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// // PhotoImageView.cs // // Author: // Larry Ewing <[email protected]> // Ruben Vermeersch <[email protected]> // Stephane Delcroix <[email protected]> // // Copyright (C) 2004-2010 Novell, Inc. // Copyright (C) 2004-2007 Larry Ewing // Copyright (C) 2008-2010 Ruben Vermeersch // Copyright (C) 2007-2009 Stephane Delcroix // // 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 FSpot.Core; using FSpot.Loaders; using Hyena; using Gdk; using TagLib.Image; namespace FSpot.Widgets { public class PhotoImageView : ImageView { #region public API protected PhotoImageView (IntPtr raw) : base (raw) { } public PhotoImageView (IBrowsableCollection query) : this (new BrowsablePointer (query, -1)) { } public PhotoImageView (BrowsablePointer item) : base () { Accelerometer.OrientationChanged += HandleOrientationChanged; Preferences.SettingChanged += OnPreferencesChanged; this.item = item; item.Changed += HandlePhotoItemChanged; } public BrowsablePointer Item { get { return item; } } public IBrowsableCollection Query { get { return item.Collection; } } public Loupe Loupe { get { return loupe; } } public Gdk.Pixbuf CompletePixbuf () { //FIXME: this should be an async call if (loader != null) while (loader.Loading) Gtk.Application.RunIteration (); return this.Pixbuf; } public void Reload () { if (Item == null || !Item.IsValid) return; HandlePhotoItemChanged (this, null); } // Zoom scaled between 0.0 and 1.0 public double NormalizedZoom { get { return (Zoom - MIN_ZOOM) / (MAX_ZOOM - MIN_ZOOM); } set { Zoom = (value * (MAX_ZOOM - MIN_ZOOM)) + MIN_ZOOM; } } public event EventHandler PhotoChanged; #endregion #region Gtk widgetry protected override void OnStyleSet (Gtk.Style previous) { CheckPattern = new CheckPattern (this.Style.Backgrounds [(int)Gtk.StateType.Normal]); } protected override bool OnKeyPressEvent (Gdk.EventKey evnt) { if ((evnt.State & (ModifierType.Mod1Mask | ModifierType.ControlMask)) != 0) return base.OnKeyPressEvent (evnt); bool handled = true; // Scroll if image is zoomed in (scrollbars are visible) Gtk.ScrolledWindow scrolled_w = this.Parent as Gtk.ScrolledWindow; bool scrolled = scrolled_w != null && !this.Fit; // Go to the next/previous photo when not zoomed (no scrollbars) switch (evnt.Key) { case Gdk.Key.Up: case Gdk.Key.KP_Up: case Gdk.Key.Left: case Gdk.Key.KP_Left: case Gdk.Key.h: case Gdk.Key.H: case Gdk.Key.k: case Gdk.Key.K: if (scrolled) handled = false; else this.Item.MovePrevious (); break; case Gdk.Key.Page_Up: case Gdk.Key.KP_Page_Up: case Gdk.Key.BackSpace: case Gdk.Key.b: case Gdk.Key.B: this.Item.MovePrevious (); break; case Gdk.Key.Down: case Gdk.Key.KP_Down: case Gdk.Key.Right: case Gdk.Key.KP_Right: case Gdk.Key.j: case Gdk.Key.J: case Gdk.Key.l: case Gdk.Key.L: if (scrolled) handled = false; else this.Item.MoveNext (); break; case Gdk.Key.Page_Down: case Gdk.Key.KP_Page_Down: case Gdk.Key.space: case Gdk.Key.KP_Space: case Gdk.Key.n: case Gdk.Key.N: this.Item.MoveNext (); break; case Gdk.Key.Home: case Gdk.Key.KP_Home: this.Item.Index = 0; break; case Gdk.Key.r: case Gdk.Key.R: this.Item.Index = new Random().Next(0, this.Query.Count - 1); break; case Gdk.Key.End: case Gdk.Key.KP_End: this.Item.Index = this.Query.Count - 1; break; default: handled = false; break; } return handled || base.OnKeyPressEvent (evnt); } protected override void OnDestroyed () { if (loader != null) { loader.AreaUpdated -= HandlePixbufAreaUpdated; loader.AreaPrepared -= HandlePixbufPrepared; loader.Dispose (); } base.OnDestroyed (); } #endregion #region loader uint timer; IImageLoader loader; void Load (SafeUri uri) { timer = Log.DebugTimerStart (); if (loader != null) loader.Dispose (); loader = ImageLoader.Create (uri); loader.AreaPrepared += HandlePixbufPrepared; loader.AreaUpdated += HandlePixbufAreaUpdated; loader.Completed += HandleDone; loader.Load (uri); } void HandlePixbufPrepared (object sender, AreaPreparedEventArgs args) { IImageLoader loader = sender as IImageLoader; if (loader != this.loader) return; if (!ShowProgress) return; Gdk.Pixbuf prev = this.Pixbuf; this.Pixbuf = loader.Pixbuf; PixbufOrientation = Accelerometer.GetViewOrientation (loader.PixbufOrientation); if (prev != null) prev.Dispose (); this.ZoomFit (args.ReducedResolution); } void HandlePixbufAreaUpdated (object sender, AreaUpdatedEventArgs args) { IImageLoader loader = sender as IImageLoader; if (loader != this.loader) return; if (!ShowProgress) return; Gdk.Rectangle area = this.ImageCoordsToWindow (args.Area); this.QueueDrawArea (area.X, area.Y, area.Width, area.Height); } void HandleDone (object sender, System.EventArgs args) { Log.DebugTimerPrint (timer, "Loading image took {0}"); IImageLoader loader = sender as IImageLoader; if (loader != this.loader) return; Pixbuf prev = this.Pixbuf; if (Pixbuf != loader.Pixbuf) Pixbuf = loader.Pixbuf; if (Pixbuf == null) { // FIXME: Do we have test cases for this ??? // FIXME in some cases the image passes completely through the // pixbuf loader without properly loading... I'm not sure what to do about this other // than try to load the image one last time. try { Log.Warning ("Falling back to file loader"); Pixbuf = PhotoLoader.Load (item.Collection, item.Index); } catch (Exception e) { LoadErrorImage (e); } } if (loader.Pixbuf != null) //FIXME: this test in case the photo was loaded with the direct loader PixbufOrientation = Accelerometer.GetViewOrientation (loader.PixbufOrientation); else PixbufOrientation = ImageOrientation.TopLeft; if (Pixbuf == null) LoadErrorImage (null); else ZoomFit (); progressive_display = true; if (prev != this.Pixbuf && prev != null) prev.Dispose (); } #endregion protected BrowsablePointer item; protected Loupe loupe; protected Loupe sharpener; void HandleOrientationChanged (object sender, EventArgs e) { Reload (); } bool progressive_display = true; bool ShowProgress { get { return progressive_display; } } void LoadErrorImage (System.Exception e) { // FIXME we should check the exception type and do something // like offer the user a chance to locate the moved file and // update the db entry, but for now just set the error pixbuf Pixbuf old = Pixbuf; Pixbuf = new Pixbuf (PixbufUtils.ErrorPixbuf, 0, 0, PixbufUtils.ErrorPixbuf.Width, PixbufUtils.ErrorPixbuf.Height); if (old != null) old.Dispose (); PixbufOrientation = ImageOrientation.TopLeft; ZoomFit (false); } void HandlePhotoItemChanged (object sender, BrowsablePointerChangedEventArgs args) { // If it is just the position that changed fall out if (args != null && args.PreviousItem != null && Item.IsValid && (args.PreviousIndex != item.Index) && (this.Item.Current.DefaultVersion.Uri == args.PreviousItem.DefaultVersion.Uri)) return; // Don't reload if the image didn't change at all. if (args != null && args.Changes != null && !args.Changes.DataChanged && args.PreviousItem != null && Item.IsValid && this.Item.Current.DefaultVersion.Uri == args.PreviousItem.DefaultVersion.Uri) return; // Same image, don't load it progressively if (args != null && args.PreviousItem != null && Item.IsValid && Item.Current.DefaultVersion.Uri == args.PreviousItem.DefaultVersion.Uri) progressive_display = false; try { if (Item.IsValid) Load (Item.Current.DefaultVersion.Uri); else LoadErrorImage (null); } catch (System.Exception e) { Log.DebugException (e); LoadErrorImage (e); } Selection = Gdk.Rectangle.Zero; EventHandler eh = PhotoChanged; if (eh != null) eh (this, EventArgs.Empty); } private void HandleLoupeDestroy (object sender, EventArgs args) { if (sender == loupe) loupe = null; if (sender == sharpener) sharpener = null; } public void ShowHideLoupe () { if (loupe == null) { loupe = new Loupe (this); loupe.Destroyed += HandleLoupeDestroy; loupe.Show (); } else { loupe.Destroy (); } } public void ShowSharpener () { if (sharpener == null) { sharpener = new Sharpener (this); sharpener.Destroyed += HandleLoupeDestroy; } sharpener.Show (); } void OnPreferencesChanged (object sender, NotifyEventArgs args) { LoadPreference (args.Key); } void LoadPreference (String key) { switch (key) { case Preferences.COLOR_MANAGEMENT_DISPLAY_PROFILE: Reload (); break; } } protected override void ApplyColorTransform (Pixbuf pixbuf) { Cms.Profile screen_profile; if (FSpot.ColorManagement.Profiles.TryGetValue (Preferences.Get<string> (Preferences.COLOR_MANAGEMENT_DISPLAY_PROFILE), out screen_profile)) FSpot.ColorManagement.ApplyProfile (pixbuf, screen_profile); } bool crop_helpers = true; public bool CropHelpers { get { return crop_helpers; } set { if (crop_helpers == value) return; crop_helpers = value; QueueDraw (); } } protected override bool OnExposeEvent (EventExpose evnt) { if (!base.OnExposeEvent (evnt)) return false; if (!CanSelect || !CropHelpers || Selection == Rectangle.Zero) return true; using (Cairo.Context ctx = CairoHelper.Create (GdkWindow)) { ctx.SetSourceRGBA (.7, .7, .7, .8); ctx.SetDash (new double [] {10, 15}, 0); ctx.LineWidth = .8; for (int i=1; i<3; i++) { Point s = ImageCoordsToWindow (new Point (Selection.X + Selection.Width / 3 * i, Selection.Y)); Point e = ImageCoordsToWindow (new Point (Selection.X + Selection.Width / 3 * i, Selection.Y + Selection.Height)); ctx.MoveTo (s.X, s.Y); ctx.LineTo (e.X, e.Y); ctx.Stroke (); } for (int i=1; i<3; i++) { Point s = ImageCoordsToWindow (new Point (Selection.X, Selection.Y + Selection.Height / 3 * i)); Point e = ImageCoordsToWindow (new Point (Selection.X + Selection.Width, Selection.Y + Selection.Height / 3 * i)); ctx.MoveTo (s.X, s.Y); ctx.LineTo (e.X, e.Y); ctx.Stroke (); } } return true; } } }
// **************************************************************** // This is free software licensed under the NUnit license. You // may obtain a copy of the license as well as information regarding // copyright ownership at http://nunit.org/?p=license&r=2.4. // **************************************************************** namespace NUnit.Util.Tests { using System; using System.Collections; using Microsoft.Win32; using NUnit.Framework; /// <summary> /// This fixture is used to test both RecentProjects and /// its base class RecentFiles. If we add any other derived /// classes, the tests should be refactored. /// </summary> [TestFixture] public class RecentFilesTests { static readonly int MAX = RecentFilesService.MaxSize; static readonly int MIN = RecentFilesService.MinSize; RecentFilesService recentFiles; [SetUp] public void SetUp() { recentFiles = new RecentFilesService( new SettingsGroup( new MemorySettingsStorage() ) ); } #region Helper Methods // Set RecentFiles to a list of known values up // to a maximum. Most recent will be "1", next // "2", and so on... private void SetMockValues( int count ) { for( int num = count; num > 0; --num ) recentFiles.SetMostRecent( num.ToString() ); } // Check that the list is set right: 1, 2, ... private void CheckMockValues( int count ) { RecentFilesCollection files = recentFiles.Entries; Assert.AreEqual( count, files.Count, "Count" ); for( int index = 0; index < count; index++ ) Assert.AreEqual( (index + 1).ToString(), files[index].Path, "Item" ); } // Check that we can add count items correctly private void CheckAddItems( int count ) { SetMockValues( count ); Assert.AreEqual( "1", recentFiles.Entries[0].Path, "RecentFile" ); CheckMockValues( Math.Min( count, recentFiles.MaxFiles ) ); } // Check that the list contains a set of entries // in the order given and nothing else. private void CheckListContains( params int[] item ) { RecentFilesCollection files = recentFiles.Entries; Assert.AreEqual( item.Length, files.Count, "Count" ); for( int index = 0; index < files.Count; index++ ) Assert.AreEqual( item[index].ToString(), files[index].Path, "Item" ); } #endregion [Test] public void CountDefault() { Assert.AreEqual( RecentFilesService.DefaultSize, recentFiles.MaxFiles ); } [Test] public void CountOverMax() { recentFiles.MaxFiles = MAX + 1; Assert.AreEqual( MAX, recentFiles.MaxFiles ); } [Test] public void CountUnderMin() { recentFiles.MaxFiles = MIN - 1; Assert.AreEqual( MIN, recentFiles.MaxFiles ); } [Test] public void CountAtMax() { recentFiles.MaxFiles = MAX; Assert.AreEqual( MAX, recentFiles.MaxFiles ); } [Test] public void CountAtMin() { recentFiles.MaxFiles = MIN; Assert.AreEqual( MIN, recentFiles.MaxFiles ); } [Test] public void EmptyList() { Assert.IsNotNull( recentFiles.Entries, "Entries should never be null" ); Assert.AreEqual( 0, recentFiles.Count ); Assert.AreEqual( 0, recentFiles.Entries.Count ); } [Test] public void AddSingleItem() { CheckAddItems( 1 ); } [Test] public void AddMaxItems() { CheckAddItems( 5 ); } [Test] public void AddTooManyItems() { CheckAddItems( 10 ); } [Test] public void IncreaseSize() { recentFiles.MaxFiles = 10; CheckAddItems( 10 ); } [Test] public void ReduceSize() { recentFiles.MaxFiles = 3; CheckAddItems( 10 ); } [Test] public void IncreaseSizeAfterAdd() { SetMockValues(5); recentFiles.MaxFiles = 7; recentFiles.SetMostRecent( "30" ); recentFiles.SetMostRecent( "20" ); recentFiles.SetMostRecent( "10" ); CheckListContains( 10, 20, 30, 1, 2, 3, 4 ); } [Test] public void ReduceSizeAfterAdd() { SetMockValues( 5 ); recentFiles.MaxFiles = 3; CheckMockValues( 3 ); } [Test] public void ReorderLastProject() { SetMockValues( 5 ); recentFiles.SetMostRecent( "5" ); CheckListContains( 5, 1, 2, 3, 4 ); } [Test] public void ReorderSingleProject() { SetMockValues( 5 ); recentFiles.SetMostRecent( "3" ); CheckListContains( 3, 1, 2, 4, 5 ); } [Test] public void ReorderMultipleProjects() { SetMockValues( 5 ); recentFiles.SetMostRecent( "3" ); recentFiles.SetMostRecent( "5" ); recentFiles.SetMostRecent( "2" ); CheckListContains( 2, 5, 3, 1, 4 ); } [Test] public void ReorderSameProject() { SetMockValues( 5 ); recentFiles.SetMostRecent( "1" ); CheckListContains( 1, 2, 3, 4, 5 ); } [Test] public void ReorderWithListNotFull() { SetMockValues( 3 ); recentFiles.SetMostRecent( "3" ); CheckListContains( 3, 1, 2 ); } [Test] public void RemoveFirstProject() { SetMockValues( 3 ); recentFiles.Remove("1"); CheckListContains( 2, 3 ); } [Test] public void RemoveOneProject() { SetMockValues( 4 ); recentFiles.Remove("2"); CheckListContains( 1, 3, 4 ); } [Test] public void RemoveMultipleProjects() { SetMockValues( 5 ); recentFiles.Remove( "3" ); recentFiles.Remove( "1" ); recentFiles.Remove( "4" ); CheckListContains( 2, 5 ); } [Test] public void RemoveLastProject() { SetMockValues( 5 ); recentFiles.Remove("5"); CheckListContains( 1, 2, 3, 4 ); } } }
// Copyright 2020, 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 System; using System.Collections.Generic; using System.Linq; namespace FirebaseAdmin.Auth.Providers { /// <summary> /// Represents a SAML auth provider configuration. See /// <a href="http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html"> /// SAML technical overview</a>. /// </summary> public sealed class SamlProviderConfigArgs : AuthProviderConfigArgs<SamlProviderConfig> { /// <summary> /// Gets or sets the SAML IdP entity identifier. /// </summary> public string IdpEntityId { get; set; } /// <summary> /// Gets or sets the SAML IdP SSO URL. /// </summary> public string SsoUrl { get; set; } /// <summary> /// Gets or sets the collection of SAML IdP X.509 certificates issued by CA for this /// provider. Multiple certificates are accepted to prevent outages during IdP key /// rotation (for example ADFS rotates every 10 days). When the Auth server receives a SAML /// response, it will match the SAML response with the certificate on record. Otherwise the /// response is rejected. Developers are expected to manage the certificate updates as keys /// are rotated. /// </summary> public IEnumerable<string> X509Certificates { get; set; } /// <summary> /// Gets or sets the SAML relying party (service provider) entity ID. This is defined by /// the developer but needs to be provided to the SAML IdP. /// </summary> public string RpEntityId { get; set; } /// <summary> /// Gets or sets the SAML callback URL. This is fixed and must always be the same as the /// OAuth redirect URL provisioned by Firebase Auth, /// <c>https://project-id.firebaseapp.com/__/auth/handler</c> unless a custom /// <c>authDomain</c> is used. The callback URL should also be provided to the SAML IdP /// during configuration. /// </summary> public string CallbackUrl { get; set; } internal override AuthProviderConfig.Request ToCreateRequest() { var req = this.ToRequest(); if (string.IsNullOrEmpty(req.IdpConfig.IdpEntityId)) { throw new ArgumentException("IDP entity ID must not be null or empty."); } if (string.IsNullOrEmpty(req.IdpConfig.SsoUrl)) { throw new ArgumentException("SSO URL must not be null or empty."); } else if (!IsWellFormedUriString(req.IdpConfig.SsoUrl)) { throw new ArgumentException($"Malformed SSO URL: {req.IdpConfig.SsoUrl}"); } var certs = req.IdpConfig.IdpCertificates; if (certs == null || certs.Count() == 0) { throw new ArgumentException("X509 certificates must not be null or empty."); } else if (certs.Any((cert) => string.IsNullOrEmpty(cert.X509Certificate))) { throw new ArgumentException( "X509 certificates must not contain null or empty values."); } if (string.IsNullOrEmpty(req.SpConfig.SpEntityId)) { throw new ArgumentException("RP entity ID must not be null or empty."); } if (string.IsNullOrEmpty(req.SpConfig.CallbackUri)) { throw new ArgumentException("Callback URL must not be null or empty."); } else if (!IsWellFormedUriString(req.SpConfig.CallbackUri)) { throw new ArgumentException($"Malformed callback URL: {req.SpConfig.CallbackUri}"); } return req; } internal override AuthProviderConfig.Request ToUpdateRequest() { var req = this.ToRequest(); if (req.IdpConfig.HasValues) { this.ValidateIdpConfigForUpdate(req.IdpConfig); } else { req.IdpConfig = null; } if (req.SpConfig.HasValues) { this.ValidateSpConfigForUpdate(req.SpConfig); } else { req.SpConfig = null; } return req; } internal override ProviderConfigClient<SamlProviderConfig> GetClient() { return SamlProviderConfigClient.Instance; } private SamlProviderConfig.Request ToRequest() { return new SamlProviderConfig.Request() { DisplayName = this.DisplayName, Enabled = this.Enabled, IdpConfig = new SamlProviderConfig.IdpConfig() { IdpEntityId = this.IdpEntityId, SsoUrl = this.SsoUrl, IdpCertificates = this.X509Certificates? .Select((cert) => new SamlProviderConfig.IdpCertificate() { X509Certificate = cert, }), }, SpConfig = new SamlProviderConfig.SpConfig() { SpEntityId = this.RpEntityId, CallbackUri = this.CallbackUrl, }, }; } private void ValidateIdpConfigForUpdate(SamlProviderConfig.IdpConfig idpConfig) { if (idpConfig.IdpEntityId == string.Empty) { throw new ArgumentException("IDP entity ID must not be empty."); } var ssoUrl = idpConfig.SsoUrl; if (ssoUrl == string.Empty) { throw new ArgumentException("SSO URL must not be empty."); } else if (ssoUrl != null && !IsWellFormedUriString(ssoUrl)) { throw new ArgumentException($"Malformed SSO URL: {ssoUrl}"); } var certs = idpConfig.IdpCertificates; if (certs?.Count() == 0) { throw new ArgumentException("X509 certificates must not be empty."); } else if (certs?.Any((cert) => string.IsNullOrEmpty(cert.X509Certificate)) ?? false) { throw new ArgumentException( "X509 certificates must not contain null or empty values."); } } private void ValidateSpConfigForUpdate(SamlProviderConfig.SpConfig spConfig) { if (spConfig.SpEntityId == string.Empty) { throw new ArgumentException("RP entity ID must not be empty."); } var callbackUri = spConfig.CallbackUri; if (callbackUri == string.Empty) { throw new ArgumentException("Callback URL must not be empty."); } else if (callbackUri != null && !IsWellFormedUriString(callbackUri)) { throw new ArgumentException($"Malformed callback URL: {callbackUri}"); } } } }
using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace ActiveWare { /// <summary> /// A fixed magnifying glass for placing on a control /// </summary> public partial class MagnifyingGlass : UserControl { private System.Windows.Forms.Timer _UpdateTimer = new System.Windows.Forms.Timer(); private int _PixelSize = 5; private int _PixelRange = 10; private bool _ShowPixel = true; private bool _ShowPosition = true; private string _PosFormat = "#x ; #y"; private bool _FollowCursor = false; internal Bitmap _ScreenShot = null; internal MovingMagnifyingGlass _DisplayForm = null; private Point _LastPosition = Point.Empty; private MovingMagnifyingGlass _MovingGlass = null; private ContentAlignment _PosAlign = ContentAlignment.TopLeft; private bool _UseMovingGlass = false; /// <summary> /// Instance of the magnifying glass with moving glass, if the user clicks on this one /// </summary> public MagnifyingGlass() : this(true) { } /// <summary> /// Instance of the magnifying glass /// </summary> /// <param name="movingGlass">Create a moving glass if the user clicks on this one?</param> public MagnifyingGlass(bool movingGlass) { if (movingGlass) { // Moving glass is enabled _MovingGlass = new MovingMagnifyingGlass(); MovingGlass.MagnifyingGlass.ShowPosition = false; MovingGlass.MagnifyingGlass.DisplayUpdated += new DisplayUpdatedDelegate(MagnifyingGlass_DisplayUpdated); MovingGlass.MagnifyingGlass.Click += new EventHandler(_MovingGlass_Click); MouseWheel += new MouseEventHandler(MagnifyingGlass_MouseWheel); Cursor = Cursors.SizeAll; UseMovingGlass = true; } _UpdateTimer.Tick += new System.EventHandler(_UpdateTimer_Tick); Click += new System.EventHandler(MagnifyingGlass_Click); CalculateSize(); } #region Properties [Description("Magnifying ratio (calculate PixelRange*PixelSize*2+PixelSize for the final control size, min. 3)")] public int PixelSize { get { return _PixelSize; } set { int temp = value; if (temp < 3) { // Minimum size temp = 3; } if ((double)temp / 2 == (double)Math.Floor((double)temp / 2)) { // Use only integers that can't be divided by 2 temp++; } _PixelSize = temp; CalculateSize(); } } [Description("Get/set if the moving glass feature should be used")] public bool UseMovingGlass { get { return _UseMovingGlass; } set { if (MovingGlass != null) { _UseMovingGlass = value; } } } [Description("Get/set the align of the position (choose everything, but not the middle")] public ContentAlignment PosAlign { get { return _PosAlign; } set { _PosAlign = (!value.ToString().ToLower().StartsWith("middle")) ? value : ContentAlignment.TopLeft; } } [Description("Get/set the position display string format (you have to use #x and #y for the corrdinates values)")] public string PosFormat { get { return _PosFormat; } set { // Settings without the #x and #y variables will be ignored _PosFormat = (value != null && value != "" && value.Contains("#x") && value.Contains("#y")) ? value : "#x ; #y"; Invalidate(); } } [Description("The moving glass, if the user clicks on this")] public MovingMagnifyingGlass MovingGlass { get { return _MovingGlass; } } /// <summary> /// Returns true, if enabled, visible and not in designer mode /// </summary> [Browsable(false)] public bool IsEnabled { get { return Visible && Enabled && !DesignMode; } } [Browsable(false)] internal bool FollowCursor { get { return _FollowCursor; } set { if (!(_FollowCursor = value)) { // Exit the following mode if (_ScreenShot != null) { _ScreenShot.Dispose(); _ScreenShot = null; } } } } [Description("Get/set the pixel range (calculate PixelRange*PixelSize*2+PixelSize for the final control size, min. 1)")] public int PixelRange { get { return _PixelRange; } set { int temp = value; if (temp < 1) { // Minimum range is one pixel temp = 1; } _PixelRange = temp; CalculateSize(); } } [Description("Get/set if the active pixel should be shown")] public bool ShowPixel { get { return _ShowPixel; } set { _ShowPixel = value; Invalidate(); } } [Description("Get/set if the current cursor position should be shown")] public bool ShowPosition { get { return _ShowPosition; } set { _ShowPosition = value; Invalidate(); } } [Description("Get the control size (settings will be ignored)")] new public Size Size { get { return base.Size; } set { // Settings will be ignored 'cause size will be calculated internal } } [Description("Get the timer that updates the display in an interval")] public Timer UpdateTimer { get { return _UpdateTimer; } } [Description("Get the color of the current pixel")] public Color PixelColor { get { Bitmap bmp = null; try { // Make a screenshot of the pixel from the current cursor position bmp = new Bitmap(1, 1); using (Graphics g = Graphics.FromImage(bmp)) { bool makeScreenshot = !FollowCursor;// Make a real screenshot? if (makeScreenshot) { if (MovingGlass != null) { //Only make a real screenshot if the moving glass is inactive makeScreenshot &= !MovingGlass.Visible; } } if (!FollowCursor) { // Make a real screenshot g.CopyFromScreen(Cursor.Position, new Point(0, 0), bmp.Size); } else { // Use the screen image for the screenshot bool createScreenshot = false;// Did we create a screenshot for this? if (FollowCursor) { // Create the screenshot only if it wasn't done yet createScreenshot = _ScreenShot == null; } else { // Create the screenshot only of the moving glass has not done it yet createScreenshot = MovingGlass.MagnifyingGlass._ScreenShot == null; } if (createScreenshot) { // Create a new screen image MakeScreenshot(); } if (FollowCursor) { // We're the moving glass g.DrawImage(_ScreenShot, new Rectangle(new Point(0, 0), new Size(1, 1)), new Rectangle(Cursor.Position, new Size(1, 1)), GraphicsUnit.Pixel); } else { // Use the moving glasses screenshot g.DrawImage(MovingGlass.MagnifyingGlass._ScreenShot, new Rectangle(new Point(0, 0), new Size(1, 1)), new Rectangle(Cursor.Position, new Size(1, 1)), GraphicsUnit.Pixel); } if (createScreenshot) { // Destroy the screenshot if we only needed to create one for this _ScreenShot.Dispose(); } } } // Return the pixel color return bmp.GetPixel(0, 0); } finally { bmp.Dispose(); } } } #endregion #region Painting protected override void OnPaintBackground(PaintEventArgs e) { // Only paint the background, if we're disabled or in DesignMode if (!IsEnabled) { base.OnPaintBackground(e); } } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); if (!IsEnabled) { // Draw only if visible, enabled and not in DesignMode return; } // Set the InterpolationMode to NearestNeighbor to see the pixels clearly e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor; // Prepare some shortcut variables for a better overview Point pos = Cursor.Position; Rectangle scr = Screen.PrimaryScreen.Bounds;// The screen size Point zeroPoint = new Point(0, 0); #region Set the new display window location if we follow the cursor if (FollowCursor) { Point loc = new Point(Cursor.Position.X - PixelRange * PixelSize, Cursor.Position.Y - PixelRange * PixelSize); if (loc.X < 0) { loc = new Point(0, loc.Y); } if (loc.X + Width > Screen.PrimaryScreen.Bounds.Width) { loc = new Point(Screen.PrimaryScreen.Bounds.Width - Width, loc.Y); } if (loc.Y < 0) { loc = new Point(loc.X, 0); } if (loc.Y + Height > Screen.PrimaryScreen.Bounds.Height) { loc = new Point(loc.X, Screen.PrimaryScreen.Bounds.Height - Height); } _DisplayForm.Location = loc; } #endregion #region Make the screenshot Rectangle shot = new Rectangle(zeroPoint, new Size(Size.Width / PixelSize, Size.Height / PixelSize));// The final screenshot size and position Point defaultLocation = new Point(pos.X - PixelRange, pos.Y - PixelRange);// The screenshot default location shot.Location = defaultLocation; if (shot.Location.X < 0) { // The area is going over the left screen border shot.Size = new Size(shot.Size.Width + shot.Location.X, shot.Size.Height); shot.Location = new Point(0, shot.Location.Y); } else if (shot.Location.X > scr.Width) { // The area is going over the right screen border shot.Size = new Size(shot.Location.X - scr.Width, shot.Size.Height); } if (shot.Location.Y < 0) { // The area is going over the upper screen border shot.Size = new Size(shot.Size.Width, shot.Size.Height + shot.Location.Y); shot.Location = new Point(shot.Location.X, 0); } else if (shot.Location.Y > scr.Height) { // The area is going over the bottom screen border shot.Size = new Size(shot.Size.Width, shot.Location.Y - scr.Height); } Bitmap screenShot=new Bitmap(shot.Width, shot.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);// The screenshot imag; using (Graphics g = Graphics.FromImage(screenShot)) { bool makeScreenshot = !FollowCursor;// Make areal screenshot? if (makeScreenshot) { if (MovingGlass != null) { // Only make a real screenshot if the moving glass is inactive makeScreenshot &= !MovingGlass.Visible; } } if (makeScreenshot) { // Make screenshot g.CopyFromScreen(shot.Location, zeroPoint, shot.Size); } else { // Copy from work screenshot if (FollowCursor) { // We're the moving glass g.DrawImage(_ScreenShot, new Rectangle(zeroPoint, screenShot.Size), shot, GraphicsUnit.Pixel); } else { // We're not the moving glass, but we should use the work screenshot // of the moving glass, 'cause if it's fully visible we'd copy the // moving glass display area... g.DrawImage(MovingGlass.MagnifyingGlass._ScreenShot, new Rectangle(zeroPoint, screenShot.Size), shot, GraphicsUnit.Pixel); } } } #endregion #region Paint the screenshot scaled to the display Rectangle display = new Rectangle(zeroPoint, Size);// The rectangle within the display to show the screenshot Size displaySize = new Size(shot.Width * PixelSize, shot.Height * PixelSize);// The default magnified screenshot size if (defaultLocation.X < 0 || defaultLocation.X > scr.Width) { if (defaultLocation.X < 0) { // Display the screenshot with right align display.Location = new Point(display.Width - displaySize.Width, display.Location.Y); } // Change the display area width to the width of the magnified screenshot display.Size = new Size(displaySize.Width, display.Size.Height); } if (defaultLocation.Y < 0 || defaultLocation.Y > scr.Height) { if (defaultLocation.Y < 0) { // Display the screenshot with bottom align display.Location = new Point(display.Location.X, display.Height - displaySize.Height); } // Change the display area height to the height of the magnified screenshot display.Size = new Size(display.Size.Width, displaySize.Height); } if (displaySize != Size) { // Paint the background 'cause the magnified screenshot size is different from the display size and we have a out-of-screen area e.Graphics.FillRectangle(new SolidBrush(BackColor), new Rectangle(zeroPoint, Size)); } // Scale and paint the screenshot e.Graphics.DrawImage(screenShot, display); screenShot.Dispose(); #endregion #region Paint everything else to the display // Show the current pixel in a black/white bordered rectangle in the middle of the display if (ShowPixel) { int xy = PixelSize * PixelRange; e.Graphics.DrawRectangle(new Pen(new SolidBrush(Color.Black)), new Rectangle(new Point(xy, xy), new Size(PixelSize, PixelSize))); e.Graphics.DrawRectangle(new Pen(new SolidBrush(Color.White)), new Rectangle(new Point(xy + 1, xy + 1), new Size(PixelSize - 2, PixelSize - 2))); } // Show the cursor position coordinates on a fixed colored background rectangle in the display if (ShowPosition) { // Parse the format string string posText = PosFormat; posText = posText.Replace("#x", pos.X.ToString()); posText = posText.Replace("#y", pos.Y.ToString()); // Calculate where to paint Size textSize = e.Graphics.MeasureString(posText, Font).ToSize(); if (textSize.Width + 6 <= Width && textSize.Height + 6 <= Height)// Continue only if the display is bigger or equal to the needed size { string posString = PosAlign.ToString().ToLower();// The align as text (for less code) Point posZero = Point.Empty;// The zero coordinates for the position display if (posString.StartsWith("top")) { posZero = new Point(0, 0); } else { posZero = new Point(0, Height - textSize.Height); } if (posString.Contains("center")) { posZero = new Point((int)Math.Ceiling((double)(Width - textSize.Width) / 2), posZero.Y); } else if (posString.Contains("right")) { posZero = new Point(Width - textSize.Width - 6, posZero.Y); } // Paint the text background rectangle and the text on it e.Graphics.FillRectangle(new SolidBrush(BackColor), new Rectangle(posZero, new Size(textSize.Width + 6, textSize.Height + 6))); e.Graphics.DrawString(posText, Font, new SolidBrush(ForeColor), new PointF(posZero.X + 3, posZero.Y + 3)); } } #endregion } #endregion /// <summary> /// Set a new size /// </summary> /// <param name="pixelSize">Pixel size value</param> /// <param name="pixelRange">Pixel range value</param> public void SetNewSize(int pixelSize, int pixelRange) { SuspendLayout(); PixelSize = pixelSize; PixelRange = pixelRange; ResumeLayout(true); } private void CalculateSize() { // Calculate the new control size depending on the magnifying ratio and the pixel range to display int wh = PixelSize * (PixelRange * 2 + 1); base.Size = new Size(wh, wh); } private void _UpdateTimer_Tick(object sender, EventArgs e) { try { // Redraw and continue the timer if we're visible, enabled and not in DesignMode // The timer is also disabled here because the Timer component seems to have an error (it will crashafter a while!?). Restarting the timer is a workaround. UpdateTimer.Stop(); if (IsEnabled) { if (_LastPosition == Cursor.Position) { // Refresh only if the position has changed return; } // Remember the current cursor position _LastPosition = Cursor.Position; // Repaint everything Invalidate(); // Release the event after the display has been updated OnDisplayUpdated(); } } finally { // Restart the timer UpdateTimer.Start(); } } /// <summary> /// Delegate for the DisplayUpdated event /// </summary> /// <param name="sender">The sending MagnifyingGlass control</param> public delegate void DisplayUpdatedDelegate(MagnifyingGlass sender); /// <summary> /// Fired after the display has been refreshed by the UpdateTimer or the moving glass /// </summary> public event DisplayUpdatedDelegate DisplayUpdated; private void OnDisplayUpdated() { if (DisplayUpdated != null) { DisplayUpdated(this); } } #region Moving glass related methods private void MagnifyingGlass_Click(object sender, EventArgs e) { // Show the moving glass if (MovingGlass != null && IsEnabled && UseMovingGlass) { MovingGlass.Show(); } } private void MagnifyingGlass_MouseWheel(object sender, MouseEventArgs e) { // Resize on mouse wheel actions if (_DisplayForm != null && e.Delta != 0) { if (e.Delta > 0) { if ((PixelRange + 1) * PixelRange * 2 <= Screen.PrimaryScreen.Bounds.Width && (PixelRange + 1) * PixelRange * 2 <= Screen.PrimaryScreen.Bounds.Height) { PixelRange++; PixelSize += 2; } } else { if (PixelRange - 1 >= 5) { PixelRange--; } if (PixelSize > 3) { PixelSize -= 2; } } } } private void _MovingGlass_Click(object sender, EventArgs e) { // Hide the moving glass on mouse click MovingGlass.Hide(); } private void MagnifyingGlass_DisplayUpdated(MagnifyingGlass sender) { // Refresh if the moving one has refreshed Invalidate(); OnDisplayUpdated(); } internal void MakeScreenshot() { // Copy the current screen without this control for the following glass OnBeforeMakingScreenshot(); _ScreenShot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height); using (Graphics g = Graphics.FromImage(_ScreenShot)) { bool visible = _DisplayForm.Visible; if (visible) { _DisplayForm.Visible = false; } g.CopyFromScreen(new Point(0, 0), new Point(0, 0), _ScreenShot.Size); g.Flush(); if (visible) { _DisplayForm.Visible = true; } } OnAfterMakingScreenshot(); } /// <summary> /// Delegate for the BeforeMakingScreenshot and the AfterMakingScreenshot events /// </summary> /// <param name="sender">The sending MagnifyingGlass object</param> public delegate void MakingScreenshotDelegate(object sender); /// <summary> /// Fired before making a screenshot /// </summary> public event MakingScreenshotDelegate BeforeMakingScreenshot; /// <summary> /// Fired after making a screenshot /// </summary> public event MakingScreenshotDelegate AfterMakingScreenshot; private void OnBeforeMakingScreenshot() { if (BeforeMakingScreenshot != null) { BeforeMakingScreenshot(this); } } private void OnAfterMakingScreenshot() { if (AfterMakingScreenshot != null) { AfterMakingScreenshot(this); } } #endregion } /// <summary> /// A free magnifying glass that follows the cursor /// </summary> public class MovingMagnifyingGlass : Form { private MagnifyingGlass _MagnifyingGlass = new MagnifyingGlass(false); public MovingMagnifyingGlass() { Opacity = .75;// Added because it makes things easier ShowInTaskbar = false; ShowIcon = false; FormBorderStyle = FormBorderStyle.None; MagnifyingGlass.PixelSize = 10; MagnifyingGlass.PixelRange = 5; MagnifyingGlass.BackColor = Color.Black; MagnifyingGlass.ForeColor = Color.White; MagnifyingGlass.UpdateTimer.Interval = 50; MagnifyingGlass._DisplayForm = this; MagnifyingGlass.FollowCursor = true; MagnifyingGlass.BorderStyle = BorderStyle.FixedSingle; MagnifyingGlass.Resize += new EventHandler(MagnifyingGlass_Resize); MagnifyingGlass.Location = new Point(0, 0); Controls.Add(MagnifyingGlass); Size = MagnifyingGlass.Size; Text = "Moving magnifying glass"; } /// <summary> /// Show the window and enable the timer /// </summary> new public void Show() { MagnifyingGlass.MakeScreenshot(); Cursor.Position = new Point(0, 0); base.Show(); MagnifyingGlass.UpdateTimer.Start(); Cursor.Hide(); } /// <summary> /// Hide the window and disable the timer /// </summary> new public void Hide() { base.Hide(); MagnifyingGlass.UpdateTimer.Stop(); Cursor.Show(); MagnifyingGlass._ScreenShot.Dispose(); MagnifyingGlass._ScreenShot = null; } private void MagnifyingGlass_Resize(object sender, EventArgs e) { // Always stay as big as the glass Size = MagnifyingGlass.Size; } /// <summary> /// The magnifying glass object /// </summary> [Description("The magnifying glass object")] public MagnifyingGlass MagnifyingGlass { get { return _MagnifyingGlass; } } } }
// Application.cs // Script#/FX/Sharpen/Core // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Html; using System.Runtime.CompilerServices; namespace Sharpen { /// <summary> /// A page-level singleton representing the current application. It provides core /// services like settings, IoC, and pub/sub events-based messaging for decoupled /// components. /// </summary> public sealed partial class Application : IApplication, IContainer, IEventManager { internal const string ServicesAttribute = "data-services"; internal const string BehaviorNameKey = "behaviorName"; internal const string BehaviorsKey = "behaviors"; internal const string BehaviorsAttribute = "data-behavior"; internal const string BehaviorsSelector = "*[data-behavior]"; internal const string ModelTypeAttribute = "data-model-type"; internal const string BindingsAttribute = "data-bindings"; internal const string BindingsSelector = "*[data-bindings]"; internal static readonly RegExp BindingsRegex = new RegExp(@"([a-z\.\-]+)\s*:\s*([a-z]+)\s+([^;]*)\s*\;", "gi"); internal static readonly RegExp PropertyPathRegex = new RegExp(@"[a-z0-9\.]+", "gi"); internal const string TemplateTypeAttribute = "data-template"; internal const string TemplateOptionsAttribute = "template-options"; /// <summary> /// The current Application instance. /// </summary> public static readonly Application Current = new Application(); private readonly Dictionary<string, ServiceRegistration> _registeredServices; private readonly Dictionary<string, BehaviorRegistration> _registeredBehaviors; private readonly Dictionary<string, ExpressionFactory> _registeredExpressions; private readonly Dictionary<string, BinderFactory> _registeredBinders; private readonly Dictionary<string, TemplateEngine> _registeredTemplateEngines; private readonly Dictionary<string, Template> _registeredTemplates; private Dictionary<string, object> _catalog; private Dictionary<string, Dictionary<string, Callback>> _subscriptions; private int _subscriptionCount; private object _model; static Application() { Script.SetTimeout(delegate() { Application.Current.ActivateFragment(Document.Body, /* contentOnly */ false); }, 0); } private Application() { _catalog = new Dictionary<string, object>(); _subscriptions = new Dictionary<string, Dictionary<string, Callback>>(); _registeredServices = new Dictionary<string, ServiceRegistration>(); _registeredBehaviors = new Dictionary<string, BehaviorRegistration>(); _registeredExpressions = new Dictionary<string, ExpressionFactory>(); _registeredBinders = new Dictionary<string, BinderFactory>(); _registeredTemplateEngines = new Dictionary<string, TemplateEngine>(); _registeredTemplates = new Dictionary<string, Template>(); RegisterObject(typeof(IApplication), this); RegisterObject(typeof(IContainer), this); RegisterObject(typeof(IEventManager), this); RegisterBehavior(BinderManager.BehaviorName, typeof(BinderManager)); RegisterExpression("bind", ProcessModelExpression); RegisterExpression("init", ProcessModelExpression); RegisterExpression("link", ProcessModelExpression); RegisterExpression("exec", ProcessModelExpression); RegisterBinder("text", BindContent); RegisterBinder("html", BindContent); RegisterBinder("value", BindValue); RegisterBinder("visibility", BindVisibility); } /// <summary> /// The model object associated with the application. /// </summary> public object Model { get { return _model; } } /// <summary> /// Activates a specified element and its children by instantiating any /// declaratively specified behaviors or bindings within the markup. /// </summary> /// <param name="element">The element to activate.</param> /// <param name="contentOnly">Whether the element should be activated, or only its contained content.</param> public extern void ActivateFragment(Element element, bool contentOnly); /// <summary> /// Activates a specified element and its children by instantiating any /// declaratively specified behaviors or bindings within the markup. /// </summary> /// <param name="element">The element to activate.</param> /// <param name="contentOnly">Whether the element should be activated, or only its contained content.</param> /// <param name="model">The model to bind to.</param> public void ActivateFragment(Element element, bool contentOnly, object model) { Debug.Assert(element != null); if (element == Document.Body) { // Perform app-level activation (tied to body initialization) // Setup top-level services specified declaratively. SetupServices(); // Create the model declaratively associated with the application. if (model == null) { string modelTypeName = (string)Document.Body.GetAttribute(ModelTypeAttribute); if (String.IsNullOrEmpty(modelTypeName) == false) { Type modelType = Type.GetType(modelTypeName); Debug.Assert(modelType != null, "Could not resolve model '" + modelTypeName + "'"); model = GetObject(modelType); IInitializable initializableModel = model as IInitializable; if (initializableModel != null) { Dictionary<string, object> modelData = OptionsParser.GetOptions(element, "model"); initializableModel.BeginInitialization(modelData); initializableModel.EndInitialization(); } } } _model = model; } // Create expressions and bindings associated with the specified elements and // the contained elements. Do this first, as this allows behaviors to look at // values set as a result of bindings when they are attached. if ((contentOnly == false) && element.HasAttribute(Application.BindingsAttribute)) { SetupBindings(element, model); } ElementCollection boundElements = element.QuerySelectorAll(Application.BindingsSelector); for (int i = 0, boundElementCount = boundElements.Length; i < boundElementCount; i++) { SetupBindings(boundElements[i], model); } // Attach behaviors associated declaratively with the specified element and the // contained elements. if ((contentOnly == false) && element.HasAttribute(Application.BehaviorsAttribute)) { AttachBehaviors(element); } ElementCollection extendedElements = element.QuerySelectorAll(Application.BehaviorsSelector); for (int i = 0, extendedElementCount = extendedElements.Length; i < extendedElementCount; i++) { AttachBehaviors(extendedElements[i]); } } /// <summary> /// Deactivates the specified element and its children by disposing any /// behaviors or binding instances attached to the elements. /// </summary> /// <param name="element">The element to deactivate.</param> /// <param name="contentOnly">Whether the element should be deactivated, or only its contained content.</param> public void DeactivateFragment(Element element, bool contentOnly) { Debug.Assert(element != null); // Detach behaviors associated with the element and the contained elements. if ((contentOnly == false) && element.HasAttribute(Application.BehaviorsAttribute)) { DetachBehaviors(element); } ElementCollection elements = element.QuerySelectorAll(Application.BehaviorsSelector); int matchingElements = elements.Length; if (matchingElements != 0) { for (int i = 0; i < matchingElements; i++) { DetachBehaviors(elements[i]); } } } private string GetTypeKey(Type type) { string key = Script.GetField<string>(type, "$key"); if (key == null) { key = Date.Now.GetTime().ToString(); Script.SetField(type, "$key", key); } return key; } #region Implementation of IApplication /// <summary> /// Gets the value of the specified setting. /// </summary> /// <param name="name">The name of the setting.</param> /// <returns>The value of the specified setting.</returns> public string GetSetting(string name) { // TODO: Implement access to query string settings as well as maybe // a few other things like JSON data written out as page-level // metadata, or maybe a JSON block in an embedded script element. return null; } #endregion #region Implementation of IContainer /// <summary> /// Gets an instance of the specified object type. An instance is created /// if one has not been registered with the container. A factory method is /// called if a factory has been registered or implemented on the object type. /// </summary> /// <param name="objectType">The type of object to retrieve.</param> /// <returns>The object instance.</returns> public object GetObject(Type objectType) { Debug.Assert(objectType != null, "Expected an object type when creating objects."); string catalogKey = GetTypeKey(objectType); object catalogItem = _catalog[catalogKey]; if (catalogItem == null) { Function objectFactory = Script.GetField(objectType, "factory") as Function; if (objectFactory != null) { catalogItem = objectFactory; } else { return Script.CreateInstance(objectType); } } if (catalogItem is Function) { return ((Function)catalogItem).Call(null, (IContainer)this, objectType); } return catalogItem; } /// <summary> /// Registers an object factory with the container. The factory is called /// when the particular object type is requested. The factory can decide whether to /// cache object instances it returns or not, based on its policy. /// </summary> /// <param name="objectType"></param> /// <param name="objectFactory"></param> public void RegisterFactory(Type objectType, Func<IContainer, Type, object> objectFactory) { Debug.Assert(objectType != null, "Expected an object type when registering object factories."); Debug.Assert(objectFactory != null, "Expected an object factory when registering object factories."); _catalog[GetTypeKey(objectType)] = objectFactory; } /// <summary> /// Registers an object instance for the specified object type. /// </summary> /// <param name="objectType">The type that can be used to lookup the specified object instance.</param> /// <param name="objectInstance">The object instance to use.</param> public void RegisterObject(Type objectType, object objectInstance) { Debug.Assert(objectType != null, "Expected an object type when registering objects."); Debug.Assert(objectInstance != null, "Expected an object instance when registering objects."); _catalog[GetTypeKey(objectType)] = objectInstance; } #endregion #region Implementation of IEventManager /// <summary> /// Raises the specified event. The type of the event arguments is used to determine /// which subscribers the event is routed to. /// </summary> /// <param name="eventArgs">The event arguments containing event-specific data.</param> public void PublishEvent(EventArgs eventArgs) { Debug.Assert(eventArgs != null, "Must specify an eventArgs when raising an event."); string eventTypeKey = GetTypeKey(eventArgs.GetType()); Dictionary<string, Callback> eventHandlerMap = _subscriptions[eventTypeKey]; if (eventHandlerMap != null) { // TODO: Handle the case where a subscriber unsubscribes while we're iterating // Should we do it here by copying/cloning the list, or should we handle it // by completing unsubscribe asynchronously? foreach (KeyValuePair<string, Callback> eventHandlerEntry in eventHandlerMap) { eventHandlerEntry.Value(eventArgs); } } } /// <summary> /// Subscribes to the specified type of events. The resulting cookie can be used for /// unsubscribing. /// </summary> /// <param name="eventType">The type of the event.</param> /// <param name="eventHandler">The event handler to invoke when the specified event type is raised.</param> /// <returns></returns> public object SubscribeEvent(Type eventType, Callback eventHandler) { Debug.Assert(eventType != null, "Must specify an event type when subscribing to events."); Debug.Assert(eventHandler != null, "Must specify an event handler when subscribing to events."); string eventTypeKey = GetTypeKey(eventType); Dictionary<string, Callback> eventHandlerMap = _subscriptions[eventTypeKey]; if (eventHandlerMap == null) { eventHandlerMap = new Dictionary<string, Callback>(); _subscriptions[eventTypeKey] = eventHandlerMap; } string eventHandlerKey = (++_subscriptionCount).ToString(); eventHandlerMap[eventHandlerKey] = eventHandler; // The subscription cookie we use is an object with the two strings // identifying the event handler uniquely - the event type key used to index // into the top-level event handlers key/value pair list, and the handler key // (as generated above) to index into the event-type-specific key/value pair list. // Keep these in sync with Unsubscribe... return new Dictionary<string, string>("type", eventTypeKey, "handler", eventHandlerKey); } /// <summary> /// Unsubcribes from a previously subscribed-to event type. /// </summary> /// <param name="subscriptionCookie">The subscription cookie.</param> public void UnsubscribeEvent(object subscriptionCookie) { Debug.Assert(subscriptionCookie != null, "Must specify the subscription cookie when unsubscribing to events."); Debug.Assert(Script.HasField(subscriptionCookie, "type") && Script.HasField(subscriptionCookie, "handler"), "A valid subscription cookie is an object with 'type' and 'handler' fields."); Dictionary<string, string> keys = (Dictionary<string, string>)subscriptionCookie; Dictionary<string, Callback> eventHandlerMap = _subscriptions[keys["type"]]; Debug.Assert(eventHandlerMap != null, "Invalid subscription cookie."); Debug.Assert(eventHandlerMap.ContainsKey(keys["handler"]), "Invalid subscription cookie."); eventHandlerMap.Remove(keys["handler"]); if (eventHandlerMap.Count == 0) { _subscriptions.Remove(keys["type"]); } } #endregion } }
using System; using System.Configuration; using System.IO; using System.Net; using System.Text; namespace Telligent.Evolution.Extensibility.Rest.Version1 { public class ClientCredentialsRestHost : RestHost { private string _communityUrl = null; private string DefaultUsername { get; set; } private string ImpersonatingUsername { get; set; } private string ClientId { get; set; } private string ClientSecret { get; set; } public ClientCredentialsRestHost(string defaultUsername, string communityUrl,string clientId,string clientSecret) : base() { _communityUrl = communityUrl.EndsWith("/") ? communityUrl : communityUrl + "/"; ; ClientId = clientId; ClientSecret = clientSecret; DefaultUsername = defaultUsername; } public override int PostTimeout { get { return 300000; } } public override string Name { get { return "Client Credentials Rest Host"; } } public ClientCredentialsRestHost():base() { var config = ConfigurationManager.AppSettings; if(string.IsNullOrEmpty(config["defaultUsername"])) throw new ConfigurationErrorsException("defaultUsername is expected in the appSettings section of the application configuration"); if (string.IsNullOrEmpty(config["communityUrl"])) throw new ConfigurationErrorsException("communityUrl is expected in the appSettings section of the application configuration"); if (string.IsNullOrEmpty(config["clientId"])) throw new ConfigurationErrorsException("clientId is expected in the appSettings section of the application configuration"); if (string.IsNullOrEmpty(config["clientSecret"])) throw new ConfigurationErrorsException("clientSecret is expected in the appSettings section of the application configuration"); this.DefaultUsername = config["DefaultUsername"]; this.ClientId = config["clientId"]; this.ClientSecret = config["clientSecret"]; var url = config["communityUrl"]; _communityUrl = url.EndsWith("/") ? url : url + "/"; } public override void ApplyAuthenticationToHostRequest(System.Net.HttpWebRequest request, bool forAccessingUser) { OauthUser user = null; if (forAccessingUser && !string.IsNullOrEmpty(ImpersonatingUsername)) user = GetUser(this.ImpersonatingUsername); if (user == null) user = GetUser(DefaultUsername); request.Headers["Authorization"] = "OAuth " + user.Token; } public override string EvolutionRootUrl { get { return _communityUrl; } } public void Impersonate(string username, Action<ClientCredentialsRestHost> impersonatedActions) { this.ImpersonatingUsername = username; impersonatedActions(this); this.ImpersonatingUsername = null; } public async void ImpersonateAsync(string username, Action<ClientCredentialsRestHost> impersonatedActions) { this.ImpersonatingUsername = username; impersonatedActions(this); this.ImpersonatingUsername = null; } private OauthUser GetUser(string username) { string userCacheKey = GetUserCacheKey(username); var user = this.Cache.Get(userCacheKey) as OauthUser; if (user == null) { user = GetToken(username); this.Cache.Put(userCacheKey, user, 600); } else { if (user.TokenExpiresUtc.Subtract(DateTime.UtcNow).TotalMinutes <= 3) { user = RefreshToken(user); this.Cache.Remove(userCacheKey); this.Cache.Put(userCacheKey, user, 600); } } return user; } private static readonly string _userFmtString = "SDK::User::{0}"; private string GetUserCacheKey(string username) { return string.Format(_userFmtString, username); } private OauthUser RefreshToken(OauthUser user) { var request = (HttpWebRequest) WebRequest.Create(this.EvolutionRootUrl + "api.ashx/v2/oauth/token"); request.Timeout = this.PostTimeout; request.Method = "POST"; string data = string.Concat( "client_id=", Uri.EscapeDataString(ClientId), "&client_secret=", Uri.EscapeDataString(ClientSecret), "&grant_type=refresh_token&refresh_token=", Uri.EscapeDataString(user.RefreshToken) ); byte[] bytes = Encoding.UTF8.GetBytes(data); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = bytes.Length; using (var requestStream = request.GetRequestStream()) { requestStream.Write(bytes, 0, bytes.Length); requestStream.Close(); } string rawResponse = null; try { using (HttpWebResponse webResponse = (HttpWebResponse) request.GetResponse()) { using (var reader = new StreamReader(webResponse.GetResponseStream())) { rawResponse = reader.ReadToEnd(); } } } catch { throw new Exception( "An error occured while attempting to acquire a refresh token for an authorization code"); } var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); var response = serializer.Deserialize<OauthResponse>(rawResponse); if (!string.IsNullOrEmpty(response.error)) throw new Exception(response.error); return new OauthUser(user.Username, response); return user; } private OauthUser GetToken(string username) { var request = (HttpWebRequest) WebRequest.Create(this.EvolutionRootUrl + "api.ashx/v2/oauth/token"); request.Timeout = this.PostTimeout; request.Method = "POST"; string data = string.Concat( "client_id=", Uri.EscapeDataString(ClientId), "&client_secret=", Uri.EscapeDataString(ClientSecret), "&grant_type=client_credentials&username=", Uri.EscapeDataString(username) ); byte[] bytes = Encoding.UTF8.GetBytes(data); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = bytes.Length; using (var requestStream = request.GetRequestStream()) { requestStream.Write(bytes, 0, bytes.Length); requestStream.Close(); } string rawResponse = null; try { using (HttpWebResponse webResponse = (HttpWebResponse) request.GetResponse()) { using (var reader = new StreamReader(webResponse.GetResponseStream())) { rawResponse = reader.ReadToEnd(); } } } catch (Exception e) { throw new Exception("An error occured while attempting to acquire a token for an authorization code", e); } var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); var response = serializer.Deserialize<OauthResponse>(rawResponse); if (!string.IsNullOrEmpty(response.error)) throw new Exception(response.error); return new OauthUser(username, response); } internal class OauthResponse { public string error { get; set; } public string access_token { get; set; } public int expires_in { get; set; } public string refresh_token { get; set; } } internal class OauthUser { public OauthUser() { } public OauthUser(string username, OauthResponse response) { Username = username; Token = response.access_token; TokenExpiresUtc = DateTime.UtcNow.AddSeconds(response.expires_in); RefreshToken = response.refresh_token; } public string Username { get; set; } public string Token { get; set; } public string RefreshToken { get; set; } public DateTime TokenExpiresUtc { get; set; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using Newtonsoft.Json; using RestSharp; using RestSharp.Extensions; namespace DocumentDBRestApi { /// <summary> /// API client is mainly responible for making the HTTP call to the API backend. /// </summary> public class ApiClient { /// <summary> /// Initializes a new instance of the <see cref="ApiClient" /> class. /// </summary> /// <param name="basePath">The base path.</param> // ReSharper disable once InconsistentNaming public ApiClient(string basePath = "https://healthcare.documents.azure.com:443/dbs") { if (basePath == null) throw new ArgumentNullException(nameof(basePath)); BasePath = basePath; RestClient = new RestClient(BasePath); } // Creates and sets up a RestRequest prior to a call. private RestRequest PrepareRequest( string Path, Method Method, Dictionary<string, string> QueryParams, string PostBody, Dictionary<string, string> HeaderParams, Dictionary<string, string> FormParams, Dictionary<string, FileParameter> FileParams, Dictionary<string, string> PathParams, string[] AuthSettings) { var request = new RestRequest(Path, Method); UpdateParamsForAuth(QueryParams, HeaderParams, AuthSettings); // add default header, if any foreach (var defaultHeader in DefaultHeader) request.AddHeader(defaultHeader.Key, defaultHeader.Value); // add path parameter, if any foreach (var param in PathParams) request.AddParameter(param.Key, param.Value, ParameterType.UrlSegment); // add header parameter, if any foreach (var param in HeaderParams) request.AddHeader(param.Key, param.Value); // add query parameter, if any foreach (var param in QueryParams) request.AddQueryParameter(param.Key, param.Value); // add form parameter, if any foreach (var param in FormParams) request.AddParameter(param.Key, param.Value); // add file parameter, if any foreach (var param in FileParams) request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType); if (PostBody != null) // http body (model) parameter request.AddParameter("application/json", PostBody, ParameterType.RequestBody); return request; } /// <summary> /// Add default header. /// </summary> /// <param name="Key">Header field name.</param> /// <param name="Value">Header field value.</param> /// <returns></returns> public void AddDefaultHeader(string Key, string Value) { DefaultHeader.Add(Key, Value); } /// <summary> /// Encode string in base64 format. /// </summary> /// <param name="Text">String to be encoded.</param> /// <returns>Encoded string.</returns> public static string Base64Encode(string Text) { var textByte = Encoding.UTF8.GetBytes(Text); return Convert.ToBase64String(textByte); } /// <summary> /// Makes the HTTP request (Sync). /// </summary> /// <param name="Path">URL path.</param> /// <param name="Method">HTTP method.</param> /// <param name="QueryParams">Query parameters.</param> /// <param name="PostBody">HTTP body (POST request).</param> /// <param name="HeaderParams">Header parameters.</param> /// <param name="FormParams">Form parameters.</param> /// <param name="FileParams">File parameters.</param> /// <param name="PathParams">Path parameters.</param> /// <param name="AuthSettings">Authentication settings.</param> /// <returns>Object</returns> public Object CallApi( string Path, Method Method, Dictionary<string, string> QueryParams, string PostBody, Dictionary<string, string> HeaderParams, Dictionary<string, string> FormParams, Dictionary<string, FileParameter> FileParams, Dictionary<string, string> PathParams, string[] AuthSettings) { var request = PrepareRequest( Path, Method, QueryParams, PostBody, HeaderParams, FormParams, FileParams, PathParams, AuthSettings); var response = RestClient.Execute(request); StatusCode = (int)response.StatusCode; ResponseHeaders = response.Headers.ToDictionary(X => X.Name, X => X.Value.ToString()); return response; } /// <summary> /// Makes the asynchronous HTTP request. /// </summary> /// <param name="Path">URL path.</param> /// <param name="Method">HTTP method.</param> /// <param name="QueryParams">Query parameters.</param> /// <param name="PostBody">HTTP body (POST request).</param> /// <param name="HeaderParams">Header parameters.</param> /// <param name="FormParams">Form parameters.</param> /// <param name="FileParams">File parameters.</param> /// <param name="PathParams">Path parameters.</param> /// <param name="AuthSettings">Authentication settings.</param> /// <returns>The Task instance.</returns> public async Task<Object> CallApiAsync( string Path, Method Method, Dictionary<string, string> QueryParams, string PostBody, Dictionary<string, string> HeaderParams, Dictionary<string, string> FormParams, Dictionary<string, FileParameter> FileParams, Dictionary<string, string> PathParams, string[] AuthSettings) { var request = PrepareRequest( Path, Method, QueryParams, PostBody, HeaderParams, FormParams, FileParams, PathParams, AuthSettings); var response = await RestClient.ExecuteTaskAsync(request); StatusCode = (int)response.StatusCode; ResponseHeaders = response.Headers.ToDictionary(X => X.Name, X => X.Value.ToString()); return response; } /// <summary> /// Dynamically cast the object into target type. /// Ref: http://stackoverflow.com/questions/4925718/c-dynamic-runtime-cast /// </summary> /// <param name="Source">Object to be casted</param> /// <param name="Dest">Target type</param> /// <returns>Casted object</returns> public static dynamic ConvertType(dynamic Source, Type Dest) { return Convert.ChangeType(Source, Dest); } /// <summary> /// Deserialize the JSON string into a proper object. /// </summary> /// <param name="Response">The HTTP response.</param> /// <param name="Type">Object type.</param> /// <returns>Object representation of the JSON string.</returns> public object Deserialize(IRestResponse Response, Type Type) { var data = Response.RawBytes; var content = Response.Content; var headers = Response.Headers; if (Type == typeof (Object)) // return an object return content; if (Type == typeof(Stream)) { if (headers != null) { var filePath = string.IsNullOrEmpty(Configuration.TempFolderPath) ? Path.GetTempPath() : Configuration.TempFolderPath; var regex = new Regex(@"Content-Disposition:.*filename=['""]?([^'""\s]+)['""]?$"); var match = regex.Match(headers.ToString()); if (match.Success) { var fileName = filePath + match.Value.Replace("\"", "").Replace("'", ""); File.WriteAllBytes(fileName, data); return new FileStream(fileName, FileMode.Open); } } var stream = new MemoryStream(data); return stream; } if (Type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object return DateTime.Parse(content, null, DateTimeStyles.RoundtripKind); if (Type == typeof(string) || Type.Name.StartsWith("System.Nullable")) // return primitive type return ConvertType(content, Type); // at this point, it must be a model (json) try { return JsonConvert.DeserializeObject(content, Type); } catch (Exception e) { throw new ApiException(500, e.Message); } } /// <summary> /// Escape string (url-encoded). /// </summary> /// <param name="Str">String to be escaped.</param> /// <returns>Escaped string.</returns> public string EscapeString(string Str) { return Str.UrlEncode(); } /// <summary> /// Get the API key with prefix. /// </summary> /// <param name="ApiKeyIdentifier">API key identifier (authentication scheme).</param> /// <returns>API key with prefix.</returns> public string GetApiKeyWithPrefix(string ApiKeyIdentifier) { string apiKeyValue; Configuration.ApiKey.TryGetValue(ApiKeyIdentifier, out apiKeyValue); string apiKeyPrefix; if (Configuration.ApiKeyPrefix.TryGetValue(ApiKeyIdentifier, out apiKeyPrefix)) return apiKeyPrefix + " " + apiKeyValue; return apiKeyValue; } /// <summary> /// Create FileParameter based on Stream. /// </summary> /// <param name="Name">Parameter name.</param> /// <param name="Stream">Input stream.</param> /// <returns>FileParameter.</returns> public FileParameter ParameterToFile(string Name, Stream Stream) { var stream = Stream as FileStream; return stream != null ? FileParameter.Create(Name, stream.ReadAsBytes(), Path.GetFileName(stream.Name)) : FileParameter.Create(Name, Stream.ReadAsBytes(), "no_file_name_provided"); } /// <summary> /// If parameter is DateTime, output in ISO8601 format. /// If parameter is a list, join the list with ",". /// Otherwise just return the string. /// </summary> /// <param name="Obj">The parameter (header, path, query, form).</param> /// <returns>Formatted string.</returns> public string ParameterToString(object Obj) { if (Obj is DateTime) return ((DateTime)Obj).ToString("u"); if (!(Obj is IList)) return Convert.ToString(Obj); const string separator = ","; var flattenString = ((IList)Obj).Cast<object>().Aggregate("", (Current, Param) => Current + (Param + separator)); return flattenString.Remove(flattenString.Length - 1); } /// <summary> /// Select the Accept header's value from the given accepts array: /// if JSON exists in the given array, use it; /// otherwise use all of them (joining into a string) /// </summary> /// <param name="Accepts">The accepts array to select from.</param> /// <returns>The Accept header to use.</returns> public string SelectHeaderAccept(string[] Accepts) { if (Accepts.Length == 0) return null; if (Accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) return "application/json"; return string.Join(",", Accepts); } /// <summary> /// Serialize an object into JSON string. /// </summary> /// <param name="Obj">Object.</param> /// <returns>JSON string.</returns> public string Serialize(object Obj) { try { return Obj != null ? JsonConvert.SerializeObject(Obj) : null; } catch (Exception e) { throw new ApiException(500, e.Message); } } /// <summary> /// Update parameters based on authentication. /// NOT CURRENTLY USED /// </summary> /// <param name="QueryParams">Query parameters.</param> /// <param name="HeaderParams">Header parameters.</param> /// <param name="AuthSettings">Authentication settings.</param> public void UpdateParamsForAuth(Dictionary<string, string> QueryParams, Dictionary<string, string> HeaderParams, string[] AuthSettings) { if (AuthSettings == null || AuthSettings.Length == 0) return; foreach (var auth in AuthSettings) { // determine which one to use switch (auth) { default: //TODO show warning about security definition not found throw new ArgumentNullException(); } } } /// <summary> /// Gets or sets the base path. /// </summary> /// <value>The base path</value> public string BasePath { get; set; } /// <summary> /// Gets the default header. /// </summary> public Dictionary<string, string> DefaultHeader { get; } = new Dictionary<string, string>(); /// <summary> /// Gets the response headers of the previous request /// </summary> public Dictionary<string, string> ResponseHeaders { get; private set; } /// <summary> /// Gets or sets the RestClient. /// </summary> /// <value>An instance of the RestClient</value> public RestClient RestClient { get; set; } /// <summary> /// Gets the status code of the previous request /// </summary> public int StatusCode { get; private set; } } }
/* * Reactor 3D MIT License * * Copyright (c) 2010 Reiser Games * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace Reactor.Content { #region Keyframe public class Keyframe { #region Fields int boneValue; TimeSpan timeValue; Matrix transformValue; #endregion /// <summary> /// Constructs a new keyframe object. /// </summary> public Keyframe(int bone, TimeSpan time, Matrix transform) { boneValue = bone; timeValue = time; transformValue = transform; } /// <summary> /// Gets the index of the target bone that is animated by this keyframe. /// </summary> public int Bone { get { return boneValue; } } /// <summary> /// Gets the time offset from the start of the animation to this keyframe. /// </summary> public TimeSpan Time { get { return timeValue; } } /// <summary> /// Gets the bone transform for this keyframe. /// </summary> public Matrix Transform { get { return transformValue; } } } #endregion #region AnimationClip /// <summary> /// An animation clip is the runtime equivalent of the /// Microsoft.Xna.Framework.Content.Pipeline.Graphics.AnimationContent type. /// It holds all the keyframes needed to describe a single animation. /// </summary> public class AnimationClip { /// <summary> /// Constructs a new animation clip object. /// </summary> public AnimationClip(TimeSpan duration, IList<Keyframe> keyframes) { durationValue = duration; keyframesValue = keyframes; } /// <summary> /// Gets the total length of the animation. /// </summary> public TimeSpan Duration { get { return durationValue; } } TimeSpan durationValue; /// <summary> /// Gets a combined list containing all the keyframes for all bones, /// sorted by time. /// </summary> public IList<Keyframe> Keyframes { get { return keyframesValue; } } IList<Keyframe> keyframesValue; } #endregion #region SkinningData public class SkinningData { #region Fields IDictionary<string, AnimationClip> animationClipsValue; IList<Matrix> bindPoseValue; IList<Matrix> inverseBindPoseValue; IList<int> skeletonHierarchyValue; #endregion /// <summary> /// Constructs a new skinning data object. /// </summary> public SkinningData(IDictionary<string, AnimationClip> animationClips, IList<Matrix> bindPose, IList<Matrix> inverseBindPose, IList<int> skeletonHierarchy) { animationClipsValue = animationClips; bindPoseValue = bindPose; inverseBindPoseValue = inverseBindPose; skeletonHierarchyValue = skeletonHierarchy; } /// <summary> /// Gets a collection of animation clips. These are stored by name in a /// dictionary, so there could for instance be clips for "Walk", "Run", /// "JumpReallyHigh", etc. /// </summary> public IDictionary<string, AnimationClip> AnimationClips { get { return animationClipsValue; } } public IList<AnimationClip> AnimationIndexes { get { List<AnimationClip> clips = new List<AnimationClip>(animationClipsValue.Values); return clips; } } /// <summary> /// Bindpose matrices for each bone in the skeleton, /// relative to the parent bone. /// </summary> public IList<Matrix> BindPose { get { return bindPoseValue; } } /// <summary> /// Vertex to bonespace transforms for each bone in the skeleton. /// </summary> public IList<Matrix> InverseBindPose { get { return inverseBindPoseValue; } } /// <summary> /// For each bone in the skeleton, stores the index of the parent bone. /// </summary> public IList<int> SkeletonHierarchy { get { return skeletonHierarchyValue; } } } /// <summary> /// Loads SkinningData objects from compiled XNB format. /// </summary> #endregion #region TypeReader /// <summary> /// Loads SkinningData objects from compiled XNB format. /// </summary> public class SkinningDataReader : ContentTypeReader<SkinningData> { protected override SkinningData Read(ContentReader input, SkinningData existingInstance) { IDictionary<string, AnimationClip> animationClips; IList<Matrix> bindPose, inverseBindPose; IList<int> skeletonHierarchy; animationClips = input.ReadObject<IDictionary<string, AnimationClip>>(); bindPose = input.ReadObject<IList<Matrix>>(); inverseBindPose = input.ReadObject<IList<Matrix>>(); skeletonHierarchy = input.ReadObject<IList<int>>(); return new SkinningData(animationClips, bindPose, inverseBindPose, skeletonHierarchy); } } /// <summary> /// Loads AnimationClip objects from compiled XNB format. /// </summary> public class AnimationClipReader : ContentTypeReader<AnimationClip> { protected override AnimationClip Read(ContentReader input, AnimationClip existingInstance) { TimeSpan duration = input.ReadObject<TimeSpan>(); IList<Keyframe> keyframes = input.ReadObject<IList<Keyframe>>(); return new AnimationClip(duration, keyframes); } } /// <summary> /// Loads Keyframe objects from compiled XNB format. /// </summary> public class KeyframeReader : ContentTypeReader<Keyframe> { protected override Keyframe Read(ContentReader input, Keyframe existingInstance) { int bone = input.ReadObject<int>(); TimeSpan time = input.ReadObject<TimeSpan>(); Matrix transform = input.ReadObject<Matrix>(); return new Keyframe(bone, time, transform); } } #endregion #region AnimationPlayer /// <summary> /// The animation player is in charge of decoding bone position /// matrices from an animation clip. /// </summary> public class AnimationPlayer { #region Fields // Information about the currently playing animation clip. AnimationClip currentClipValue; TimeSpan currentTimeValue; int currentKeyframe; // Current animation transform matrices. Matrix[] boneTransforms; Matrix[] worldTransforms; Matrix[] skinTransforms; // Backlink to the bind pose and skeleton hierarchy data. SkinningData skinningDataValue; #endregion /// <summary> /// Constructs a new animation player. /// </summary> public AnimationPlayer(SkinningData skinningData) { if (skinningData == null) throw new ArgumentNullException("skinningData"); skinningDataValue = skinningData; boneTransforms = new Matrix[skinningData.BindPose.Count]; worldTransforms = new Matrix[skinningData.BindPose.Count]; skinTransforms = new Matrix[skinningData.BindPose.Count]; } internal float blendFactor = 0.0f; /// <summary> /// Starts decoding the specified animation clip. /// </summary> public void StartClip(AnimationClip clip, float blendfactor) { if (clip == null) throw new ArgumentNullException("clip"); blendFactor = blendfactor; currentClipValue = clip; currentTimeValue = TimeSpan.Zero; currentKeyframe = 0; // Initialize bone transforms to the bind pose. skinningDataValue.BindPose.CopyTo(boneTransforms, 0); } /// <summary> /// Advances the current animation position. /// </summary> public void Update(TimeSpan time, bool relativeToCurrentTime, Matrix rootTransform) { UpdateBoneTransforms(time, relativeToCurrentTime); UpdateWorldTransforms(rootTransform); UpdateSkinTransforms(); } /// <summary> /// Helper used by the Update method to refresh the BoneTransforms data. /// </summary> public void UpdateBoneTransforms(TimeSpan time, bool relativeToCurrentTime) { if (currentClipValue == null) throw new InvalidOperationException( "internal RActor.Update was called before StartClip"); // Update the animation position. if (relativeToCurrentTime) { time += currentTimeValue; // If we reached the end, loop back to the start. while (time >= currentClipValue.Duration) time -= currentClipValue.Duration; } if ((time < TimeSpan.Zero) || (time >= currentClipValue.Duration)) throw new ArgumentOutOfRangeException("time"); // If the position moved backwards, reset the keyframe index. if (time < currentTimeValue) { currentKeyframe = 0; skinningDataValue.BindPose.CopyTo(boneTransforms, 0); } currentTimeValue = time; // Read keyframe matrices. IList<Keyframe> keyframes = currentClipValue.Keyframes; while (currentKeyframe < keyframes.Count) { Keyframe keyframe = keyframes[currentKeyframe]; // Stop when we've read up to the current time position. if (keyframe.Time > currentTimeValue) break; // Use this keyframe. boneTransforms[keyframe.Bone] = keyframe.Transform; currentKeyframe++; } } /// <summary> /// Helper used by the Update method to refresh the WorldTransforms data. /// </summary> public void UpdateWorldTransforms(Matrix rootTransform) { // Root bone. worldTransforms[0] = boneTransforms[0] * rootTransform; // Child bones. for (int bone = 1; bone < worldTransforms.Length; bone++) { int parentBone = skinningDataValue.SkeletonHierarchy[bone]; worldTransforms[bone] = boneTransforms[bone] * worldTransforms[parentBone]; } } /// <summary> /// Helper used by the Update method to refresh the SkinTransforms data. /// </summary> public void UpdateSkinTransforms() { for (int bone = 0; bone < skinTransforms.Length; bone++) { skinTransforms[bone] = skinningDataValue.InverseBindPose[bone] * worldTransforms[bone]; } } /// <summary> /// Gets the current bone transform matrices, relative to their parent bones. /// </summary> public Matrix[] GetBoneTransforms() { return boneTransforms; } /// <summary> /// Gets the current bone transform matrices, in absolute format. /// </summary> public Matrix[] GetWorldTransforms() { return worldTransforms; } /// <summary> /// Gets the current bone transform matrices, /// relative to the skinning bind pose. /// </summary> public Matrix[] GetSkinTransforms() { return skinTransforms; } /// <summary> /// Gets the clip currently being decoded. /// </summary> public AnimationClip CurrentClip { get { return currentClipValue; } } /// <summary> /// Gets the current play position. /// </summary> public TimeSpan CurrentTime { get { return currentTimeValue; } } } #endregion }
#region file header // //////////////////////////////////////////////////////////////////// // /// // /// // /// 22.05.2015 // /// // //////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Threading.Tasks; using Elite.Insight.Core.DomainModel; using Elite.Insight.Core.Helpers; using Elite.Insight.Core.Messaging; namespace Elite.Insight.DataProviders.Eddb { public class EddbDataProvider { private readonly Dictionary<int, string> _systemIdToNameMap; private readonly Dictionary<int, string> _commodityNameMap; public const string EDDB_COMMODITIES_DATAFILE = @"./Data/commodities.json"; public const string EDDB_STATIONS_LITE_DATAFILE = @"./Data/stations_lite.json"; public const string EDDB_STATIONS_FULL_DATAFILE = @"./Data/stations.json"; public const string EDDB_SYSTEMS_DATAFILE = @"./Data/systems.json"; public const string EDDB_COMMODITIES_URL = @"http://eddb.io/archive/v3/commodities.json"; public const string EDDB_SYSTEMS_URL = @"http://eddb.io/archive/v3/systems.json"; public const string EDDB_STATIONS_LITE_URL = @"http://eddb.io/archive/v3/stations_lite.json"; public const string SOURCENAME = "EDDB"; private const string EDDB_STATIONS_FULL_URL = @"http://eddb.io/archive/v3/stations.json"; public ImportMode ImportMode { get; protected set; } public EddbDataProvider() { _systemIdToNameMap = new Dictionary<int, string>(); _commodityNameMap = new Dictionary<int, string>(); } public void ImportData(DataModel model, bool importMarketData, ImportMode importMode) { if (model == null) { throw new ArgumentNullException("model"); } ImportMode = importMode; DownloadDataFiles(); ImportSystems(model.StarMap); ImportCommodities(model.Commodities); if (importMarketData) { ImportStations(model.StarMap, model.GalacticMarket); } else { ImportStations(model.StarMap); } } internal void ImportCommodities(Commodities commodities) { List<EddbCommodity> eddbCommodities = SerializationHelpers.ReadJsonFromFile<List<EddbCommodity>>(new FileInfo(EDDB_COMMODITIES_DATAFILE)); int count = 0; int correlationId = EventBus.Start("importing commodities...", eddbCommodities.Count); foreach (EddbCommodity commodity in eddbCommodities) { _commodityNameMap.Add(commodity.Id, commodity.Name); commodities.Update(ToCommodity(commodity)); ++count; } EventBus.Completed("commodities imported", correlationId); } private Commodity ToCommodity(EddbCommodity eddbCommodity) { var commodity = new Commodity(eddbCommodity.Name) { AveragePrice = eddbCommodity.AveragePrice , Category = eddbCommodity.Category != null ? eddbCommodity.Category.Name : null , Source = SOURCENAME }; return commodity; } internal void ImportStations(StarMap starMap, GalacticMarket market = null) { int count = 0; if (File.Exists(EDDB_STATIONS_FULL_DATAFILE) && market != null) { EventBus.Progress("parsing stations data file...", 0, 1); List<EddbStation> eddbStations = SerializationHelpers.ReadJsonFromFile<List<EddbStation>>(new FileInfo(EDDB_STATIONS_FULL_DATAFILE)); int correlationId = EventBus.Start("importing stations and market datas...", eddbStations.Count); foreach (EddbStation eddbStation in eddbStations) { starMap.Update(ToStation(eddbStation)); ImportMarketData(eddbStation, market); ++count; EventBus.Progress("importing stations and market datas...", count, eddbStations.Count, correlationId); } EventBus.Completed("stations imported", correlationId); } else if (File.Exists(EDDB_STATIONS_LITE_DATAFILE)) { List<EddbStation> eddbStations = SerializationHelpers.ReadJsonFromFile<List<EddbStation>>(new FileInfo(EDDB_STATIONS_FULL_DATAFILE)); int correlationId = EventBus.Start("importing stations...", eddbStations.Count); foreach (EddbStation eddbStation in eddbStations) { starMap.Update(ToStation(eddbStation)); ++count; EventBus.Progress("importing stations...", count, eddbStations.Count, correlationId); } EventBus.Completed("stations imported", correlationId); } } private void ImportMarketData(EddbStation station, GalacticMarket market) { if (station.MarketDatas == null) return; int count = 0; foreach (EddbStation.MarketData marketData in station.MarketDatas) { if (ImportMode == ImportMode.Update) { market.Update(ToMarketData(marketData, station.Name, RetrieveSystemName(station.SystemId))); } else { market.Import(ToMarketData(marketData, station.Name, RetrieveSystemName(station.SystemId))); } ++count; } } private MarketDataRow ToMarketData(EddbStation.MarketData marketData, string stationName, string systemName) { return new MarketDataRow() { CommodityName = RetrieveCommodityName(marketData.CommodityId) , BuyPrice = marketData.BuyPrice , Demand = marketData.Demand , SellPrice = marketData.SellPrice , StationName = stationName , Source = SOURCENAME , Supply = marketData.Supply , SystemName = systemName , SampleDate = UnixTimeStamp.ToDateTime(marketData.CollectedAt) }; } private string RetrieveCommodityName(int commodityId) { return _commodityNameMap[commodityId]; } private Station ToStation(EddbStation eddbStation) { Station station = new Station(eddbStation.Name.ToCleanTitleCase()) { Allegiance = eddbStation.Allegiance , DistanceToStar = eddbStation.DistanceToStar , Economies = eddbStation.Economies , ExportCommodities = eddbStation.ExportCommodities , Faction = eddbStation.Faction , Government = eddbStation.Government , HasBlackmarket = ToNBool(eddbStation.HasBlackmarket) , HasCommodities = ToNBool(eddbStation.HasCommodities) , HasOutfitting = ToNBool(eddbStation.HasOutfitting) , HasRearm = ToNBool(eddbStation.HasRearm) , HasRepair = ToNBool(eddbStation.HasRepair) , HasRefuel = ToNBool(eddbStation.HasRefuel) , HasShipyard = ToNBool(eddbStation.HasShipyard) , ImportCommodities = eddbStation.ImportCommodities , MaxLandingPadSize = ParseLandingPadSize(eddbStation.MaxLandingPadSize) , ProhibitedCommodities = eddbStation.ProhibitedCommodities , Source = SOURCENAME , State = eddbStation.State , SystemName = RetrieveSystemName(eddbStation.SystemId) , Type = eddbStation.Type , UpdatedAt = eddbStation.UpdatedAt }; return station; } private string RetrieveSystemName(int systemId) { return _systemIdToNameMap[systemId]; } internal void ImportSystems(StarMap starMap) { List<EddbSystem> eddbSystems = SerializationHelpers.ReadJsonFromFile<List<EddbSystem>>(new FileInfo(EDDB_SYSTEMS_DATAFILE)); int correlationId = EventBus.Start("importing systems...", eddbSystems.Count); int count = 0; foreach (EddbSystem system in (IEnumerable<EddbSystem>)eddbSystems) { _systemIdToNameMap.Add(system.Id, system.Name.ToUpperInvariant()); starMap.Update(ToStarSystem(system)); ++count; EventBus.Progress("importing systems...", count, eddbSystems.Count, correlationId); } EventBus.Completed("importing systems", correlationId); } private static StarSystem ToStarSystem(EddbSystem eddbSystem) { var starSystem = new StarSystem(eddbSystem.Name.ToUpperInvariant()) { Allegiance = eddbSystem.Allegiance , Faction = eddbSystem.Faction , Government = eddbSystem.Government , NeedsPermit = ToNBool(eddbSystem.NeedsPermit) , Population = eddbSystem.Population , PrimaryEconomy = eddbSystem.PrimaryEconomy , Security = eddbSystem.Security , Source = SOURCENAME , State = eddbSystem.State , UpdatedAt = eddbSystem.UpdatedAt , X = eddbSystem.X , Y = eddbSystem.Y , Z = eddbSystem.Z }; return starSystem; } private static bool? ToNBool(int? needsPermit) { if (needsPermit.HasValue) { if (needsPermit == 0) { return false; } else if (needsPermit == 1) { return true; } else { throw new NotSupportedException(needsPermit + ": unable to convert from int to bool"); } } else { return null; } } private static LandingPadSize? ParseLandingPadSize(string maxLandingPadSize) { LandingPadSize size; if (Enum.TryParse(maxLandingPadSize, true, out size)) { return size; } else { return null; } } internal void DownloadDataFiles() { var tasks = new List<Task>(); int correlationId = EventBus.Start("trying to download data files..."); if (!File.Exists(EDDB_COMMODITIES_DATAFILE)) { tasks.Add(Task.Run(() => DownloadDataFile(new Uri(EDDB_COMMODITIES_URL), EDDB_COMMODITIES_DATAFILE, "eddb commodities data", correlationId))); } if (!File.Exists(EDDB_SYSTEMS_DATAFILE)) { tasks.Add(Task.Run(() => DownloadDataFile(new Uri(EDDB_SYSTEMS_URL), EDDB_SYSTEMS_DATAFILE, "eddb stations lite data", correlationId))); } if (!File.Exists(EDDB_STATIONS_FULL_DATAFILE) && !File.Exists(EDDB_STATIONS_LITE_DATAFILE)) { tasks.Add(Task.Run(() => DownloadDataFile(new Uri(EDDB_STATIONS_LITE_URL), EDDB_STATIONS_LITE_DATAFILE, "eddb stations lite data", correlationId))); } if (!File.Exists(EDDB_STATIONS_FULL_DATAFILE)) { Task.Run(() => DownloadDataFile(new Uri(EDDB_STATIONS_FULL_URL), EDDB_STATIONS_FULL_DATAFILE, "eddb stations full data", correlationId)); } if (tasks.Any()) { while (!Task.WaitAll(tasks.ToArray(), TimeSpan.FromMinutes(5)) && EventBus.Request("eddb server not responding, still waiting?")) { } EventBus.Completed("data files downloaded", correlationId); } } private static void DownloadDataFile(Uri address, string filepath, string contentDescription, int correlationId) { EventBus.Progress("starting download of " + contentDescription, 1, 2, correlationId); try { using (var webClient = new WebClient()) { webClient.DownloadFile(address, filepath); } } catch (Exception ex) { Trace.TraceError("unable to download file: " + ex); } EventBus.Progress("completed download of " + contentDescription, 2, 2, correlationId); } } public enum ImportMode { Import, Update } }
//----------------------------------------------------------------------------- // Copyright (c) 2013 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- if ($platform $= "windows") $platformFontType = "lucida console"; else if ($platform $= "Android") $platformFontType = "Droid"; else $platformFontType = "monaco"; if ($platform $= "ios") $platformFontSize = 18; else if ($platform $= "Android") $platformFontSize = 14; else $platformFontSize = 12; //----------------------------------------------------------------------------- new GuiCursor(DefaultCursor) { hotSpot = "4 4"; renderOffset = "0 0"; bitmapName = "game/gui/images/defaultCursor"; }; //--------------------------------------------------------------------------------------------- // GuiDefaultProfile is a special profile that all other profiles inherit defaults from. It // must exist. //--------------------------------------------------------------------------------------------- if(!isObject(GuiDefaultProfile)) new GuiControlProfile (GuiDefaultProfile) { tab = false; canKeyFocus = false; hasBitmapArray = false; mouseOverSelected = false; // fill color opaque = false; fillColor = "211 211 211"; fillColorHL = "244 244 244"; fillColorNA = "244 244 244"; // border color border = 0; borderColor = "100 100 100 255"; borderColorHL = "128 128 128"; borderColorNA = "64 64 64"; // font fontType = $platformFontType; fontSize = $platformFontSize; fontColor = "0 0 0"; fontColorHL = "32 100 100"; fontColorNA = "0 0 0"; fontColorSEL= "10 10 10"; // bitmap information bitmap = "game/gui/images/window.png"; bitmapBase = ""; textOffset = "0 0"; // used by guiTextControl modal = true; justify = "left"; autoSizeWidth = false; autoSizeHeight = false; returnTab = false; numbersOnly = false; cursorColor = "0 0 0 255"; // sounds soundButtonDown = $ButtonSound.fileName; soundButtonOver = ""; }; // ---------------------------------------------------------------------------- if (!isObject(GuiTransparentProfile)) new GuiControlProfile (GuiTransparentProfile : GuiDefaultProfile) { opaque = false; border = false; }; // ---------------------------------------------------------------------------- if(!isObject(GuiSolidProfile)) new GuiControlProfile (GuiSolidProfile) { opaque = true; border = true; }; // ---------------------------------------------------------------------------- if (!isObject(GuiToolTipProfile)) new GuiControlProfile (GuiToolTipProfile : GuiDefaultProfile) { fillColor = "246 220 165 255"; fontType = $platformFontType; fontSize = $platformFontSize; }; // ---------------------------------------------------------------------------- if (!isObject(GuiPopupMenuItemBorder)) new GuiControlProfile (GuiPopupMenuItemBorder : GuiDefaultProfile) { bitmap = "game/gui/images/scroll"; hasBitmapArray = true; }; // ---------------------------------------------------------------------------- if (!isObject(GuiPopUpMenuDefault)) new GuiControlProfile (GuiPopUpMenuDefault) { tab = false; canKeyFocus = false; hasBitmapArray = false; mouseOverSelected = false; // fill color opaque = false; fillColor = "255 255 255 192"; fillColorHL = "255 0 0 192"; fillColorNA = "0 0 255 255"; // border color border = 1; borderColor = "100 100 100 255"; borderColorHL = "0 128 0 255"; borderColorNA = "0 226 226 52"; // font fontType = $platformFontType; fontSize = $platformFontSize; fontColor = "27 59 95 255"; fontColorHL = "232 240 248 255"; fontColorNA = "0 0 0 255"; fontColorSEL= "255 255 255 255"; // bitmap information bitmap = "game/gui/images/scroll"; hasBitmapArray = true; bitmapBase = ""; textOffset = "0 0"; // used by guiTextControl modal = true; justify = "left"; autoSizeWidth = false; autoSizeHeight = false; returnTab = false; numbersOnly = false; cursorColor = "0 0 0 255"; profileForChildren = GuiPopupMenuItemBorder; // sounds soundButtonDown = ""; soundButtonOver = ""; }; // ---------------------------------------------------------------------------- if (!isObject(GuiPopUpMenuProfile)) new GuiControlProfile (GuiPopUpMenuProfile : GuiPopUpMenuDefault) { textOffset = "6 3"; justify = "center"; bitmap = "game/gui/images/dropDown"; hasBitmapArray = true; border = -3; profileForChildren = GuiPopUpMenuDefault; opaque = true; }; //----------------------------------------------------------------------------- if (!isObject(GuiTextProfile)) new GuiControlProfile (GuiTextProfile) { border=false; // font fontType = $platformFontType; fontSize = $platformFontSize; fontColor = "white"; modal = true; justify = "left"; autoSizeWidth = false; autoSizeHeight = false; returnTab = false; numbersOnly = false; cursorColor = "0 0 0 255"; }; //----------------------------------------------------------------------------- if (!isObject(GuiCheckBoxProfile)) new GuiControlProfile (GuiCheckBoxProfile) { opaque = false; fontColor = "white"; fillColor = "232 232 232 255"; fontColorHL = "white"; border = false; borderColor = "0 0 0 255"; fontType = $platformFontType; fontSize = $platformFontSize; fixedExtent = true; justify = "left"; bitmap = "game/gui/images/checkBox"; hasBitmapArray = true; }; //----------------------------------------------------------------------------- if(!isObject(GuiConsoleProfile)) new GuiControlProfile (GuiConsoleProfile) { fontType = $platformFontType; fontSize = $platformFontSize * 1.1; fontColor = White; fontColorHL = LightSlateGray; fontColorNA = Red; fontColors[6] = "100 100 100"; fontColors[7] = "100 100 0"; fontColors[8] = "0 0 100"; fontColors[9] = "0 100 0"; }; //----------------------------------------------------------------------------- if (!isObject(GuiTextEditProfile)) new GuiControlProfile (GuiTextEditProfile) { fontSize = $platformFontSize; opaque = false; fillColor = "232 240 248 255"; fillColorHL = "251 170 0 255"; fillColorNA = "127 127 127 52"; border = -2; bitmap = "game/gui/images/textEdit.png"; borderColor = "40 40 40 10"; fontColor = "27 59 95 255"; fontColorHL = "232 240 248 255"; fontColorNA = "0 0 0 52"; fontColorSEL = "0 0 0 255"; textOffset = "5 2"; autoSizeWidth = false; autoSizeHeight = false; tab = false; canKeyFocus = true; returnTab = true; }; //----------------------------------------------------------------------------- if(!isObject(GuiNumberEditProfile)) new GuiControlProfile (GuiNumberEditProfile: GuiTextEditProfile) { numbersOnly = true; }; //----------------------------------------------------------------------------- if(!isObject(GuiConsoleTextEditProfile)) new GuiControlProfile (GuiConsoleTextEditProfile : GuiTextEditProfile) { fontType = $platformFontType; fontSize = $platformFontSize * 1.1; }; //----------------------------------------------------------------------------- if(!isObject(GuiScrollProfile)) new GuiControlProfile (GuiScrollProfile) { opaque = true; fillColor = "255 255 255"; border = 1; borderThickness = 2; bitmap = "game/gui/images/scrollBar.png"; hasBitmapArray = true; }; //----------------------------------------------------------------------------- if(!isObject(GuiTransparentScrollProfile)) new GuiControlProfile (GuiTransparentScrollProfile) { opaque = false; fillColor = "255 255 255"; border = false; borderThickness = 2; borderColor = "0 0 0"; bitmap = "game/gui/images/scrollBar.png"; hasBitmapArray = true; }; //----------------------------------------------------------------------------- if(!isObject(ConsoleScrollProfile)) new GuiControlProfile( ConsoleScrollProfile : GuiScrollProfile ) { opaque = true; fillColor = "0 0 0 120"; border = 3; borderThickness = 0; borderColor = "0 0 0"; }; //----------------------------------------------------------------------------- if(!isObject(GuiToolboxProfile)) new GuiControlProfile( GuiToolboxProfile : GuiScrollProfile ) { opaque = true; fillColor = "255 255 255 220"; border = 3; borderThickness = 0; borderColor = "0 0 0"; }; //----------------------------------------------------------------------------- if(!isObject(SandboxWindowProfile)) new GuiControlProfile (SandboxWindowProfile : GuiDefaultProfile) { // fill color opaque = false; fillColor = "0 0 0 92"; // font fontType = $platformFontType; fontSize = $platformFontSize; fontColor = "255 255 255 255"; }; //----------------------------------------------------------------------------- if (!isObject(GuiButtonProfile)) new GuiControlProfile (GuiButtonProfile) { opaque = true; border = -1; fontColor = "white"; fontColorHL = "229 229 229 255"; fixedExtent = true; justify = "center"; canKeyFocus = false; fontType = $platformFontType; bitmap = "game/gui/images/smallButtonContainer"; }; //----------------------------------------------------------------------------- if (!isObject(BlueButtonProfile)) new GuiControlProfile (BlueButtonProfile : GuiButtonProfile) { fontSize = $platformFontSize; fontColor = "255 255 255 255"; fontColorHL = "255 255 255 255"; bitmap = "game/gui/images/blueButton.png"; }; //----------------------------------------------------------------------------- if (!isObject(RedButtonProfile)) new GuiControlProfile (RedButtonProfile : GuiButtonProfile) { fontSize = $platformFontSize; fontColor = "255 255 255 255"; fontColorHL = "255 255 255 255"; bitmap = "game/gui/images/redButton.png"; }; //----------------------------------------------------------------------------- if (!isObject(GreenButtonProfile)) new GuiControlProfile (GreenButtonProfile : GuiButtonProfile) { fontSize = $platformFontSize; fontColor = "255 255 255 255"; fontColorHL = "255 255 255 255"; bitmap = "game/gui/images/greenButton.png"; }; //----------------------------------------------------------------------------- if (!isObject(GuiRadioProfile)) new GuiControlProfile (GuiRadioProfile : GuiDefaultProfile) { fillColor = "232 232 232 255"; fixedExtent = true; bitmap = "game/gui/images/radioButton.png"; hasBitmapArray = true; }; //----------------------------------------------------------------------------- if (!isObject(GuiSliderProfile)) new GuiControlProfile (GuiSliderProfile) { bitmap = "game/gui/images/slider.png"; fontType = $platformFontType; fontSize = $platformFontSize; fontColor = "white"; }; //----------------------------------------------------------------------------- if (!isObject(GuiSliderNoTextProfile)) new GuiControlProfile (GuiSliderNoTextProfile) { bitmap = "game/gui/images/slider.png"; fontColor = "white"; fontSize = 1; }; //----------------------------------------------------------------------------- if (!isObject(GuiSpinnerProfile)) new GuiControlProfile (GuiSpinnerProfile) { fontType = $platformFontType; fontSize = $platformFontSize; opaque = false; justify = "center"; fillColor = "232 240 248 255"; fillColorHL = "251 170 0 255"; fillColorNA = "127 127 127 52"; numbersOnly = true; border = -2; bitmap = "game/gui/images/textEdit_noSides"; borderColor = "40 40 40 10"; fontColor = "27 59 95 255"; fontColorHL = "232 240 248 255"; fontColorNA = "0 0 0 52"; fontColorSEL = "0 0 0 255"; textOffset = "4 2"; autoSizeWidth = false; autoSizeHeight = false; tab = false; canKeyFocus = true; returnTab = true; }; //----------------------------------------------------------------------------- if (!isObject(GuiLightScrollProfile)) new GuiControlProfile (GuiLightScrollProfile : GuiScrollProfile) { opaque = false; fillColor = "212 216 220"; border = 0; bitmap = "game/gui/images/scrollBar"; hasBitmapArray = true; }; //----------------------------------------------------------------------------- if (!isObject(GuiSunkenContainerProfile)) new GuiControlProfile (GuiSunkenContainerProfile) { opaque = false; fillColor = "232 240 248 255"; fillColorHL = "251 170 0 255"; fillColorNA = "127 127 127 52"; border = -2; bitmap = "game/gui/images/sunkenContainer"; borderColor = "40 40 40 10"; };
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Management.ServiceManagement.Test.FunctionalTests { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Management.Automation; using System.Net; using System.Net.Cache; using System.Reflection; using System.Text; using System.Threading; using System.Xml; using System.Xml.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.WindowsAzure.Management.Service.Gateway; using Microsoft.WindowsAzure.Management.ServiceManagement.Extensions; using Microsoft.WindowsAzure.Management.ServiceManagement.Model; using Microsoft.WindowsAzure.Management.ServiceManagement.Test.FunctionalTests.ConfigDataInfo; using Microsoft.WindowsAzure.Management.ServiceManagement.Test.Properties; using Microsoft.WindowsAzure.Management.Utilities.Common; using Microsoft.WindowsAzure.ServiceManagement; [TestClass] public class ScenarioTest : ServiceManagementTest { private string serviceName; string perfFile; [TestInitialize] public void Initialize() { SetTestSettings(); serviceName = Utilities.GetUniqueShortName(serviceNamePrefix); pass = false; testStartTime = DateTime.Now; } /// <summary> /// </summary> [TestMethod(), TestCategory("BVT"), TestCategory("Scenario"), TestProperty("Feature", "IaaS"), Priority(1), Owner("priya"), Description("Test the cmdlets (New-AzureQuickVM,Get-AzureVMImage,Get-AzureVM,Get-AzureLocation,Import-AzurePublishSettingsFile,Get-AzureSubscription,Set-AzureSubscription)")] public void NewWindowsAzureQuickVM() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); string newAzureQuickVMName = Utilities.GetUniqueShortName(vmNamePrefix); if(string.IsNullOrEmpty(imageName)) imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows", "testvmimage" }, false); vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName, serviceName, imageName, username, password, locationName); // Verify PersistentVMRoleContext vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName); Assert.AreEqual(newAzureQuickVMName, vmRoleCtxt.Name, true); // Cleanup vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName, serviceName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName)); pass = true; } /// <summary> /// Basic Provisioning a Virtual Machine /// </summary> [TestMethod(), TestCategory("BVT"), TestCategory("Scenario"), TestProperty("Feature", "IaaS"), Priority(1), Owner("priya"), Description("Test the cmdlets (Get-AzureLocation,Test-AzureName ,Get-AzureVMImage,New-AzureQuickVM,Get-AzureVM ,Restart-AzureVM,Stop-AzureVM , Start-AzureVM)")] public void ProvisionLinuxVM() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); string newAzureQuickVMName = Utilities.GetUniqueShortName("PSLinuxVM"); string linuxImageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Linux", "Ubuntu", "testvmimage" }, false); vmPowershellCmdlets.NewAzureQuickLinuxVM(OS.Linux, newAzureQuickVMName, serviceName, linuxImageName, "user", password, locationName); // Verify PersistentVMRoleContext vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName); Assert.AreEqual(newAzureQuickVMName, vmRoleCtxt.Name, true); // TODO: Disabling Stop / start / restart tests for now due to timing isues /* // Stop & start the VM vmPowershellCmdlets.StopAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); Assert.AreEqual(vmRoleCtxt.PowerState, VMPowerState.Stopped); vmPowershellCmdlets.StartAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); Assert.AreEqual(vmRoleCtxt.PowerState, VMPowerState.Started.ToString()); // Restart the VM vmPowershellCmdlets.StopAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); Assert.AreEqual(vmRoleCtxt.PowerState, VMPowerState.Stopped); vmPowershellCmdlets.RestartAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); Assert.AreEqual(vmRoleCtxt.PowerState, VMPowerState.Started.ToString()); * */ // Cleanup vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName, serviceName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName)); //TODO: Need to do proper cleanup of the service // vmPowershellCmdlets.RemoveAzureService(newAzureQuickVMSvcName); // Assert.AreEqual(null, vmPowershellCmdlets.GetAzureService(newAzureQuickVMSvcName)); pass = true; } /// <summary> /// Verify Advanced Provisioning /// </summary> [TestMethod(), TestCategory("BVT"), TestCategory("Scenario"), TestProperty("Feature", "IaaS"), Priority(1), Owner("priya"), Description("Test the cmdlets (New-AzureService,New-AzureVMConfig,Add-AzureProvisioningConfig ,Add-AzureDataDisk ,Add-AzureEndpoint,New-AzureVM)")] public void AdvancedProvisioning() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); string newAzureVM1Name = Utilities.GetUniqueShortName(vmNamePrefix); string newAzureVM2Name = Utilities.GetUniqueShortName(vmNamePrefix); if (string.IsNullOrEmpty(imageName)) imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows", "testvmimage" }, false); vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName); AzureVMConfigInfo azureVMConfigInfo1 = new AzureVMConfigInfo(newAzureVM1Name, InstanceSize.ExtraSmall, imageName); AzureVMConfigInfo azureVMConfigInfo2 = new AzureVMConfigInfo(newAzureVM2Name, InstanceSize.ExtraSmall, imageName); AzureProvisioningConfigInfo azureProvisioningConfig = new AzureProvisioningConfigInfo(OS.Windows, username, password); AddAzureDataDiskConfig azureDataDiskConfigInfo = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, 50, "datadisk1", 0); AzureEndPointConfigInfo azureEndPointConfigInfo = new AzureEndPointConfigInfo(AzureEndPointConfigInfo.ParameterSet.CustonProbe, ProtocolInfo.tcp, 80, 80, "web", "lbweb", 80, ProtocolInfo.http, @"/", null, null); PersistentVMConfigInfo persistentVMConfigInfo1 = new PersistentVMConfigInfo(azureVMConfigInfo1, azureProvisioningConfig, azureDataDiskConfigInfo, azureEndPointConfigInfo); PersistentVMConfigInfo persistentVMConfigInfo2 = new PersistentVMConfigInfo(azureVMConfigInfo2, azureProvisioningConfig, azureDataDiskConfigInfo, azureEndPointConfigInfo); PersistentVM persistentVM1 = vmPowershellCmdlets.GetPersistentVM(persistentVMConfigInfo1); PersistentVM persistentVM2 = vmPowershellCmdlets.GetPersistentVM(persistentVMConfigInfo2); PersistentVM[] VMs = { persistentVM1, persistentVM2 }; vmPowershellCmdlets.NewAzureVM(serviceName, VMs); // Cleanup vmPowershellCmdlets.RemoveAzureVM(newAzureVM1Name, serviceName); vmPowershellCmdlets.RemoveAzureVM(newAzureVM2Name, serviceName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureVM1Name, serviceName)); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureVM2Name, serviceName)); pass = true; } /// <summary> /// Modifying Existing Virtual Machines /// </summary> [TestMethod(), TestCategory("Scenario"), TestProperty("Feature", "IaaS"), Priority(1), Owner("priya"), Description("Test the cmdlets (New-AzureVMConfig,Add-AzureProvisioningConfig ,Add-AzureDataDisk ,Add-AzureEndpoint,New-AzureVM)")] public void ModifyingVM() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); string newAzureQuickVMName = Utilities.GetUniqueShortName(vmNamePrefix); if (string.IsNullOrEmpty(imageName)) imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows", "testvmimage" }, false); vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName, serviceName, imageName, username, password, locationName); AddAzureDataDiskConfig azureDataDiskConfigInfo1 = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, 50, "datadisk1", 0); AddAzureDataDiskConfig azureDataDiskConfigInfo2 = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, 50, "datadisk2", 1); AzureEndPointConfigInfo azureEndPointConfigInfo = new AzureEndPointConfigInfo(AzureEndPointConfigInfo.ParameterSet.NoLB, ProtocolInfo.tcp, 1433, 2000, "sql"); AddAzureDataDiskConfig[] dataDiskConfig = { azureDataDiskConfigInfo1, azureDataDiskConfigInfo2 }; vmPowershellCmdlets.AddVMDataDisksAndEndPoint(newAzureQuickVMName, serviceName, dataDiskConfig, azureEndPointConfigInfo); SetAzureDataDiskConfig setAzureDataDiskConfig1 = new SetAzureDataDiskConfig(HostCaching.ReadWrite, 0); SetAzureDataDiskConfig setAzureDataDiskConfig2 = new SetAzureDataDiskConfig(HostCaching.ReadWrite, 0); SetAzureDataDiskConfig[] diskConfig = { setAzureDataDiskConfig1, setAzureDataDiskConfig2 }; vmPowershellCmdlets.SetVMDataDisks(newAzureQuickVMName, serviceName, diskConfig); vmPowershellCmdlets.GetAzureDataDisk(newAzureQuickVMName, serviceName); // Cleanup vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName, serviceName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName)); pass = true; } /// <summary> /// Changes that Require a Reboot /// </summary> [TestMethod(), TestCategory("Scenario"), TestProperty("Feature", "IaaS"), Priority(1), Owner("priya"), Description("Test the cmdlets (Get-AzureVM,Set-AzureDataDisk ,Update-AzureVM,Set-AzureVMSize)")] public void UpdateAndReboot() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); string newAzureQuickVMName = Utilities.GetUniqueShortName("PSTestVM"); if (string.IsNullOrEmpty(imageName)) imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows", "testvmimage" }, false); vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName, serviceName, imageName, username, password, locationName); AddAzureDataDiskConfig azureDataDiskConfigInfo1 = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, 50, "datadisk1", 0); AddAzureDataDiskConfig azureDataDiskConfigInfo2 = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, 50, "datadisk2", 1); AddAzureDataDiskConfig[] dataDiskConfig = { azureDataDiskConfigInfo1, azureDataDiskConfigInfo2 }; vmPowershellCmdlets.AddVMDataDisks(newAzureQuickVMName, serviceName, dataDiskConfig); SetAzureDataDiskConfig setAzureDataDiskConfig1 = new SetAzureDataDiskConfig(HostCaching.ReadOnly, 0); SetAzureDataDiskConfig setAzureDataDiskConfig2 = new SetAzureDataDiskConfig(HostCaching.ReadOnly, 0); SetAzureDataDiskConfig[] diskConfig = { setAzureDataDiskConfig1, setAzureDataDiskConfig2 }; vmPowershellCmdlets.SetVMDataDisks(newAzureQuickVMName, serviceName, diskConfig); SetAzureVMSizeConfig vmSizeConfig = new SetAzureVMSizeConfig(InstanceSize.Medium); vmPowershellCmdlets.SetVMSize(newAzureQuickVMName, serviceName, vmSizeConfig); // Cleanup vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName, serviceName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName)); pass = true; } /// <summary> /// </summary> [TestMethod(), TestCategory("Scenario"), TestProperty("Feature", "IaaS"), Priority(1), Owner("hylee"), Description("Test the cmdlets (Get-AzureDisk,Remove-AzureVM,Remove-AzureDisk,Get-AzureVMImage)")] public void ManagingDiskImages() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); // Create a unique VM name and Service Name string newAzureQuickVMName = Utilities.GetUniqueShortName(vmNamePrefix); if (string.IsNullOrEmpty(imageName)) imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows", "testvmimage" }, false); vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName, serviceName, imageName, username, password, locationName); // New-AzureQuickVM Console.WriteLine("VM is created successfully: -Name {0} -ServiceName {1}", newAzureQuickVMName, serviceName); // starting the test. Collection<DiskContext> vmDisks = vmPowershellCmdlets.GetAzureDiskAttachedToRoleName(new[] { newAzureQuickVMName }); // Get-AzureDisk | Where {$_.AttachedTo.RoleName -eq $vmname } foreach (var disk in vmDisks) Console.WriteLine("The disk, {0}, is created", disk.DiskName); vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName, serviceName); // Remove-AzureVM Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName)); Console.WriteLine("The VM, {0}, is successfully removed.", newAzureQuickVMName); foreach (var disk in vmDisks) { for (int i = 0; i < 3; i++) { try { vmPowershellCmdlets.RemoveAzureDisk(disk.DiskName, true); // Remove-AzureDisk break; } catch (Exception e) { if (e.ToString().ToLowerInvariant().Contains("currently in use") && i != 2) { Console.WriteLine("The vhd, {0}, is still in the state of being used by the deleted VM", disk.DiskName); Thread.Sleep(120000); continue; } else { Assert.Fail("error during Remove-AzureDisk: {0}", e.ToString()); } } } try { vmPowershellCmdlets.GetAzureDisk(disk.DiskName); // Get-AzureDisk -DiskName (try to get the removed disk.) Console.WriteLine("Disk is not removed: {0}", disk.DiskName); pass = false; } catch (Exception e) { if (e.ToString().ToLowerInvariant().Contains("does not exist")) { Console.WriteLine("The disk, {0}, is successfully removed.", disk.DiskName); continue; } else { Assert.Fail("Exception: {0}", e.ToString()); } } } pass = true; } /// <summary> /// </summary> [TestMethod(), TestCategory("Scenario"), TestProperty("Feature", "IaaS"), Priority(1), Owner("hylee"), Description("Test the cmdlets (New-AzureVMConfig,Add-AzureProvisioningConfig,New-AzureVM,Save-AzureVMImage)")] public void CaptureImagingExportingImportingVMConfig() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); // Create a unique VM name string newAzureVMName = Utilities.GetUniqueShortName("PSTestVM"); Console.WriteLine("VM Name: {0}", newAzureVMName); // Create a unique Service Name vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName); Console.WriteLine("Service Name: {0}", serviceName); if (string.IsNullOrEmpty(imageName)) imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows", "testvmimage" }, false); // starting the test. AzureVMConfigInfo azureVMConfigInfo = new AzureVMConfigInfo(newAzureVMName, InstanceSize.Small, imageName); // parameters for New-AzureVMConfig (-Name -InstanceSize -ImageName) AzureProvisioningConfigInfo azureProvisioningConfig = new AzureProvisioningConfigInfo(OS.Windows, username, password); // parameters for Add-AzureProvisioningConfig (-Windows -Password) PersistentVMConfigInfo persistentVMConfigInfo = new PersistentVMConfigInfo(azureVMConfigInfo, azureProvisioningConfig, null, null); PersistentVM persistentVM = vmPowershellCmdlets.GetPersistentVM(persistentVMConfigInfo); // New-AzureVMConfig & Add-AzureProvisioningConfig PersistentVM[] VMs = { persistentVM }; vmPowershellCmdlets.NewAzureVM(serviceName, VMs); // New-AzureVM Console.WriteLine("The VM is successfully created: {0}", persistentVM.RoleName); PersistentVMRoleContext vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(persistentVM.RoleName, serviceName); Assert.AreEqual(vmRoleCtxt.Name, persistentVM.RoleName, true); vmPowershellCmdlets.StopAzureVM(newAzureVMName, serviceName, true); // Stop-AzureVM for (int i = 0; i < 3; i++) { vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(persistentVM.RoleName, serviceName); if (vmRoleCtxt.InstanceStatus == "StoppedVM") break; else { Console.WriteLine("The status of the VM {0} : {1}", persistentVM.RoleName, vmRoleCtxt.InstanceStatus); Thread.Sleep(120000); } } Assert.AreEqual(vmRoleCtxt.InstanceStatus, "StoppedVM", true); //TODO // RDP //TODO: // Run sysprep and shutdown // Check the status of VM //PersistentVMRoleContext vmRoleCtxt2 = vmPowershellCmdlets.GetAzureVM(newAzureVMName, newAzureSvcName); // Get-AzureVM -Name //Assert.AreEqual(newAzureVMName, vmRoleCtxt2.Name, true); // // Save-AzureVMImage //string newImageName = "newImage"; //string newImageLabel = "newImageLabel"; //string postAction = "Delete"; // Save-AzureVMImage -ServiceName -Name -NewImageName -NewImageLabel -PostCaptureAction //vmPowershellCmdlets.SaveAzureVMImage(newAzureSvcName, newAzureVMName, newImageName, newImageLabel, postAction); // Cleanup vmPowershellCmdlets.RemoveAzureVM(persistentVM.RoleName, serviceName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(persistentVM.RoleName, serviceName)); } /// <summary> /// </summary> [TestMethod(), TestCategory("Scenario"), TestProperty("Feature", "IaaS"), Priority(1), Owner("hylee"), Description("Test the cmdlets (Export-AzureVM,Remove-AzureVM,Import-AzureVM,New-AzureVM)")] public void ExportingImportingVMConfigAsTemplateforRepeatableUsage() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); // Create a new Azure quick VM string newAzureQuickVMName = Utilities.GetUniqueShortName("PSTestVM"); if (string.IsNullOrEmpty(imageName)) imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows", "testvmimage" }, false); vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName, serviceName, imageName, username, password, locationName); // New-AzureQuickVM Console.WriteLine("VM is created successfully: -Name {0} -ServiceName {1}", newAzureQuickVMName, serviceName); // starting the test. string path = ".\\mytestvmconfig1.xml"; PersistentVMRoleContext vmRole = vmPowershellCmdlets.ExportAzureVM(newAzureQuickVMName, serviceName, path); // Export-AzureVM Console.WriteLine("Exporting VM is successfully done: path - {0} Name - {1}", path, vmRole.Name); vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName, serviceName); // Remove-AzureVM Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName)); Console.WriteLine("The VM is successfully removed: {0}", newAzureQuickVMName); List<PersistentVM> VMs = new List<PersistentVM>(); foreach (var pervm in vmPowershellCmdlets.ImportAzureVM(path)) // Import-AzureVM { VMs.Add(pervm); Console.WriteLine("The VM, {0}, is imported.", pervm.RoleName); } for (int i = 0; i < 3; i++) { try { vmPowershellCmdlets.NewAzureVM(serviceName, VMs.ToArray()); // New-AzureVM Console.WriteLine("All VMs are successfully created."); foreach (var vm in VMs) { Console.WriteLine("created VM: {0}", vm.RoleName); } break; } catch (Exception e) { if (e.ToString().ToLowerInvariant().Contains("currently in use") && i != 2) { Console.WriteLine("The removed VM is still using the vhd"); Thread.Sleep(120000); continue; } else { Assert.Fail("error during New-AzureVM: {0}", e.ToString()); } } } // Verify PersistentVMRoleContext vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName); Assert.AreEqual(newAzureQuickVMName, vmRoleCtxt.Name, true); // Cleanup vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName, serviceName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName)); pass = true; } /// <summary> /// </summary> [TestMethod(), TestCategory("Scenario"), TestProperty("Feature", "IaaS"), Priority(1), Owner("hylee"), Description("Test the cmdlets (Get-AzureVM,Get-AzureEndpoint,Get-AzureRemoteDesktopFile)")] public void ManagingRDPSSHConnectivity() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); // Create a new Azure quick VM string newAzureQuickVMName = Utilities.GetUniqueShortName("PSTestVM"); if (string.IsNullOrEmpty(imageName)) imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows", "testvmimage" }, false); vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName, serviceName, imageName, username, password, locationName); // New-AzureQuickVM Console.WriteLine("VM is created successfully: -Name {0} -ServiceName {1}", newAzureQuickVMName, serviceName); // starting the test. PersistentVMRoleContext vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName); // Get-AzureVM InputEndpointContext inputEndpointCtxt = vmPowershellCmdlets.GetAzureEndPoint(vmRoleCtxt)[0]; // Get-AzureEndpoint Console.WriteLine("InputEndpointContext Name: {0}", inputEndpointCtxt.Name); Console.WriteLine("InputEndpointContext port: {0}", inputEndpointCtxt.Port); Console.WriteLine("InputEndpointContext protocol: {0}", inputEndpointCtxt.Protocol); Assert.AreEqual(inputEndpointCtxt.Name, "RemoteDesktop", true); string path = ".\\myvmconnection.rdp"; vmPowershellCmdlets.GetAzureRemoteDesktopFile(newAzureQuickVMName, serviceName, path, false); // Get-AzureRemoteDesktopFile Console.WriteLine("RDP file is successfully created at: {0}", path); // ToDo: Automate RDP. //vmPowershellCmdlets.GetAzureRemoteDesktopFile(newAzureQuickVMName, newAzureQuickVMSvcName, path, true); // Get-AzureRemoteDesktopFile -Launch Console.WriteLine("Test passed"); // Cleanup vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName, serviceName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName)); pass = true; } /// <summary> /// Basic Provisioning a Virtual Machine /// </summary> [TestMethod(), TestCategory("Scenario"), TestProperty("Feature", "PAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((New,Get,Set,Remove,Move)-AzureDeployment)")] [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\Resources\\packageScenario.csv", "packageScenario#csv", DataAccessMethod.Sequential)] public void DeploymentUpgrade() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); perfFile = @"..\deploymentUpgradeResult.csv"; // Choose the package and config files from local machine string path = Convert.ToString(TestContext.DataRow["path"]); string packageName = Convert.ToString(TestContext.DataRow["packageName"]); string configName = Convert.ToString(TestContext.DataRow["configName"]); string upgradePackageName = Convert.ToString(TestContext.DataRow["upgradePackage"]); string upgradeConfigName = Convert.ToString(TestContext.DataRow["upgradeConfig"]); string upgradeConfigName2 = Convert.ToString(TestContext.DataRow["upgradeConfig2"]); var packagePath1 = new FileInfo(@path + packageName); // package with two roles var packagePath2 = new FileInfo(@path + upgradePackageName); // package with one role var configPath1 = new FileInfo(@path + configName); // config with 2 roles, 4 instances each var configPath2 = new FileInfo(@path + upgradeConfigName); // config with 1 role, 2 instances var configPath3 = new FileInfo(@path + upgradeConfigName2); // config with 1 role, 4 instances Assert.IsTrue(File.Exists(packagePath1.FullName), "VHD file not exist={0}", packagePath1); Assert.IsTrue(File.Exists(configPath1.FullName), "VHD file not exist={0}", configPath1); string deploymentName = "deployment1"; string deploymentLabel = "label1"; DeploymentInfoContext result; try { vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName); Console.WriteLine("service, {0}, is created.", serviceName); // New deployment to Production DateTime start = DateTime.Now; vmPowershellCmdlets.NewAzureDeployment(serviceName, packagePath1.FullName, configPath1.FullName, DeploymentSlotType.Production, deploymentLabel, deploymentName, false, false); TimeSpan duration = DateTime.Now - start; Uri site = Utilities.GetDeploymentAndWaitForReady(serviceName, DeploymentSlotType.Production, 10, 1000); System.IO.File.AppendAllLines(perfFile, new string[] { String.Format("Deployment, {0}, {1}", duration, DateTime.Now - start) }); Console.WriteLine("site: {0}", site.ToString()); Console.WriteLine("Time for all instances to become in ready state: {0}", DateTime.Now - start); // Auto-Upgrade the deployment start = DateTime.Now; vmPowershellCmdlets.SetAzureDeploymentUpgrade(serviceName, DeploymentSlotType.Production, UpgradeType.Auto, packagePath1.FullName, configPath1.FullName); duration = DateTime.Now - start; Console.WriteLine("Auto upgrade took {0}.", duration); result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production); Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, serviceName, DeploymentSlotType.Production, null, 8); Console.WriteLine("successfully updated the deployment"); site = Utilities.GetDeploymentAndWaitForReady(serviceName, DeploymentSlotType.Production, 10, 600); System.IO.File.AppendAllLines(perfFile, new string[] { String.Format("Auto Upgrade, {0}, {1}", duration, DateTime.Now - start) }); // Manual-Upgrade the deployment start = DateTime.Now; vmPowershellCmdlets.SetAzureDeploymentUpgrade(serviceName, DeploymentSlotType.Production, UpgradeType.Manual, packagePath1.FullName, configPath1.FullName); vmPowershellCmdlets.SetAzureWalkUpgradeDomain(serviceName, DeploymentSlotType.Production, 0); vmPowershellCmdlets.SetAzureWalkUpgradeDomain(serviceName, DeploymentSlotType.Production, 1); vmPowershellCmdlets.SetAzureWalkUpgradeDomain(serviceName, DeploymentSlotType.Production, 2); vmPowershellCmdlets.SetAzureWalkUpgradeDomain(serviceName, DeploymentSlotType.Production, 3); vmPowershellCmdlets.SetAzureWalkUpgradeDomain(serviceName, DeploymentSlotType.Production, 4); duration = DateTime.Now - start; Console.WriteLine("Manual upgrade took {0}.", duration); result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production); Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, serviceName, DeploymentSlotType.Production, null, 8); Console.WriteLine("successfully updated the deployment"); site = Utilities.GetDeploymentAndWaitForReady(serviceName, DeploymentSlotType.Production, 10, 600); System.IO.File.AppendAllLines(perfFile, new string[] { String.Format("Manual Upgrade, {0}, {1}", duration, DateTime.Now - start) }); // Simulatenous-Upgrade the deployment start = DateTime.Now; vmPowershellCmdlets.SetAzureDeploymentUpgrade(serviceName, DeploymentSlotType.Production, UpgradeType.Simultaneous, packagePath1.FullName, configPath1.FullName); duration = DateTime.Now - start; Console.WriteLine("Simulatenous upgrade took {0}.", duration); result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production); Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, serviceName, DeploymentSlotType.Production, null, 8); Console.WriteLine("successfully updated the deployment"); site = Utilities.GetDeploymentAndWaitForReady(serviceName, DeploymentSlotType.Production, 10, 600); System.IO.File.AppendAllLines(perfFile, new string[] { String.Format("Simulatenous Upgrade, {0}, {1}", duration, DateTime.Now - start) }); vmPowershellCmdlets.RemoveAzureDeployment(serviceName, DeploymentSlotType.Production, true); pass = Utilities.CheckRemove(vmPowershellCmdlets.GetAzureDeployment, serviceName); } catch (Exception e) { pass = false; Assert.Fail("Exception occurred: {0}", e.ToString()); } } /// <summary> /// AzureVNetGatewayTest() /// </summary> /// Note: Create a VNet, a LocalNet from the portal without creating a gateway. [TestMethod(), TestCategory("LongRunningTest"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Set,Remove)-AzureVNetConfig, Get-AzureVNetSite, (New,Get,Set,Remove)-AzureVNetGateway, Get-AzureVNetConnection)")] public void VNetTest() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); string newAzureQuickVMName = Utilities.GetUniqueShortName(vmNamePrefix); if (string.IsNullOrEmpty(imageName)) imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows", "testvmimage" }, false); // Read the vnetconfig file and get the names of local networks, virtual networks and affinity groups. XDocument vnetconfigxml = XDocument.Load(vnetConfigFilePath); List<string> localNets = new List<string>(); List<string> virtualNets = new List<string>(); HashSet<string> affinityGroups = new HashSet<string>(); foreach (XElement el in vnetconfigxml.Descendants()) { switch (el.Name.LocalName) { case "LocalNetworkSite": localNets.Add(el.FirstAttribute.Value); break; case "VirtualNetworkSite": virtualNets.Add(el.Attribute("name").Value); affinityGroups.Add(el.Attribute("AffinityGroup").Value); break; default: break; } } foreach (string aff in affinityGroups) { if (Utilities.CheckRemove(vmPowershellCmdlets.GetAzureAffinityGroup, aff)) { vmPowershellCmdlets.NewAzureAffinityGroup(aff, Resource.Location, null, null); } } string vnet1 = virtualNets[0]; string lnet1 = localNets[0]; try { vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName, serviceName, imageName, username, password, locationName); // New-AzureQuickVM Console.WriteLine("VM is created successfully: -Name {0} -ServiceName {1}", newAzureQuickVMName, serviceName); vmPowershellCmdlets.SetAzureVNetConfig(vnetConfigFilePath); foreach (VirtualNetworkSiteContext site in vmPowershellCmdlets.GetAzureVNetSite(null)) { Console.WriteLine("Name: {0}, AffinityGroup: {1}", site.Name, site.AffinityGroup); } foreach (string vnet in virtualNets) { Assert.AreEqual(vnet, vmPowershellCmdlets.GetAzureVNetSite(vnet)[0].Name); Assert.AreEqual(ProvisioningState.NotProvisioned, vmPowershellCmdlets.GetAzureVNetGateway(vnet)[0].State); } vmPowershellCmdlets.NewAzureVNetGateway(vnet1); Assert.IsTrue(GetVNetState(vnet1, ProvisioningState.Provisioned, 12, 60)); // Set-AzureVNetGateway -Connect Test vmPowershellCmdlets.SetAzureVNetGateway("connect", vnet1, lnet1); foreach (GatewayConnectionContext connection in vmPowershellCmdlets.GetAzureVNetConnection(vnet1)) { Console.WriteLine("Connectivity: {0}, LocalNetwork: {1}", connection.ConnectivityState, connection.LocalNetworkSiteName); Assert.IsFalse(connection.ConnectivityState.ToLowerInvariant().Contains("notconnected")); } // Get-AzureVNetGatewayKey SharedKeyContext result = vmPowershellCmdlets.GetAzureVNetGatewayKey(vnet1, vmPowershellCmdlets.GetAzureVNetConnection(vnet1)[0].LocalNetworkSiteName); Console.WriteLine("Gateway Key: {0}", result.Value); // Set-AzureVNetGateway -Disconnect vmPowershellCmdlets.SetAzureVNetGateway("disconnect", vnet1, lnet1); foreach (GatewayConnectionContext connection in vmPowershellCmdlets.GetAzureVNetConnection(vnet1)) { Console.WriteLine("Connectivity: {0}, LocalNetwork: {1}", connection.ConnectivityState, connection.LocalNetworkSiteName); } // Remove-AzureVnetGateway vmPowershellCmdlets.RemoveAzureVNetGateway(vnet1); foreach (string vnet in virtualNets) { VirtualNetworkGatewayContext gateway = vmPowershellCmdlets.GetAzureVNetGateway(vnet)[0]; Console.WriteLine("State: {0}, VIP: {1}", gateway.State.ToString(), gateway.VIPAddress); if (vnet.Equals(vnet1)) { Assert.AreEqual(ProvisioningState.Deprovisioning, gateway.State); } else { Assert.AreEqual(ProvisioningState.NotProvisioned, gateway.State); } } Utilities.RetryUntilSuccess<ManagementOperationContext>(vmPowershellCmdlets.RemoveAzureVNetConfig, "in use", 10, 30); pass = true; } catch (Exception e) { pass = false; if (cleanupIfFailed) { try { vmPowershellCmdlets.RemoveAzureVNetGateway(vnet1); } catch { } Utilities.RetryUntilSuccess<ManagementOperationContext>(vmPowershellCmdlets.RemoveAzureVNetConfig, "in use", 10, 30); } Assert.Fail("Exception occurred: {0}", e.ToString()); } finally { foreach (string aff in affinityGroups) { try { vmPowershellCmdlets.RemoveAzureAffinityGroup(aff); } catch { // Some service uses the affinity group, so it cannot be deleted. Just leave it. } } } } [TestMethod(), TestCategory("Scenario"), TestProperty("Feature", "PAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet (New-AzureServiceRemoteDesktopConfig)")] [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\Resources\\nodiagpackage.csv", "nodiagpackage#csv", DataAccessMethod.Sequential)] public void AzureServiceDiagnosticsExtensionConfigScenarioTest() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); // Choose the package and config files from local machine string packageName = Convert.ToString(TestContext.DataRow["packageName"]); string configName = Convert.ToString(TestContext.DataRow["configName"]); var packagePath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + packageName); var configPath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + configName); Assert.IsTrue(File.Exists(packagePath1.FullName), "VHD file not exist={0}", packagePath1); Assert.IsTrue(File.Exists(configPath1.FullName), "VHD file not exist={0}", configPath1); string deploymentName = "deployment1"; string deploymentLabel = "label1"; DeploymentInfoContext result; string storage = defaultAzureSubscription.CurrentStorageAccount; XmlDocument daConfig = new XmlDocument(); daConfig.Load(@".\da.xml"); try { serviceName = Utilities.GetUniqueShortName(serviceNamePrefix); vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName); Console.WriteLine("service, {0}, is created.", serviceName); ExtensionConfigurationInput config = vmPowershellCmdlets.NewAzureServiceDiagnosticsExtensionConfig(storage, daConfig); vmPowershellCmdlets.NewAzureDeployment(serviceName, packagePath1.FullName, configPath1.FullName, DeploymentSlotType.Production, deploymentLabel, deploymentName, false, false, config); result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production); pass = Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, deploymentLabel, DeploymentSlotType.Production, null, 2); Console.WriteLine("successfully deployed the package"); DiagnosticExtensionContext resultContext = vmPowershellCmdlets.GetAzureServiceDiagnosticsExtension(serviceName)[0]; VerifyDiagExtContext(resultContext, "AllRoles", "Default-Diagnostics-Production-Ext-0", storage, daConfig); vmPowershellCmdlets.RemoveAzureServiceDiagnosticsExtension(serviceName); Assert.AreEqual(vmPowershellCmdlets.GetAzureServiceDiagnosticsExtension(serviceName).Count, 0); vmPowershellCmdlets.RemoveAzureDeployment(serviceName, DeploymentSlotType.Production, true); pass &= Utilities.CheckRemove(vmPowershellCmdlets.GetAzureDeployment, serviceName, DeploymentSlotType.Production); } catch (Exception e) { pass = false; Assert.Fail("Exception occurred: {0}", e.ToString()); } } [TestMethod(), TestCategory("Scenario"), TestProperty("Feature", "PAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Get,Set,Remove)-AzureServiceRemoteDesktopExtension)")] [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\Resources\\nodiagpackage.csv", "nodiagpackage#csv", DataAccessMethod.Sequential)] public void AzureServiceDiagnosticsExtensionTest() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); // Choose the package and config files from local machine string packageName = Convert.ToString(TestContext.DataRow["packageName"]); string configName = Convert.ToString(TestContext.DataRow["configName"]); var packagePath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + packageName); var configPath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + configName); Assert.IsTrue(File.Exists(packagePath1.FullName), "VHD file not exist={0}", packagePath1); Assert.IsTrue(File.Exists(configPath1.FullName), "VHD file not exist={0}", configPath1); string deploymentName = "deployment1"; string deploymentLabel = "label1"; DeploymentInfoContext result; string storage = defaultAzureSubscription.CurrentStorageAccount; XmlDocument daConfig = new XmlDocument(); daConfig.Load(@".\da.xml"); try { serviceName = Utilities.GetUniqueShortName(serviceNamePrefix); vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName); Console.WriteLine("service, {0}, is created.", serviceName); vmPowershellCmdlets.NewAzureDeployment(serviceName, packagePath1.FullName, configPath1.FullName, DeploymentSlotType.Production, deploymentLabel, deploymentName, false, false); result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production); pass = Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, deploymentLabel, DeploymentSlotType.Production, null, 2); Console.WriteLine("successfully deployed the package"); vmPowershellCmdlets.SetAzureServiceDiagnosticsExtension(serviceName, storage, daConfig); DiagnosticExtensionContext resultContext = vmPowershellCmdlets.GetAzureServiceDiagnosticsExtension(serviceName)[0]; Assert.IsTrue(VerifyDiagExtContext(resultContext, "AllRoles", "Default-Diagnostics-Production-Ext-0", storage, daConfig)); vmPowershellCmdlets.RemoveAzureServiceDiagnosticsExtension(serviceName, true); Assert.AreEqual(vmPowershellCmdlets.GetAzureServiceDiagnosticsExtension(serviceName).Count, 0); vmPowershellCmdlets.RemoveAzureDeployment(serviceName, DeploymentSlotType.Production, true); pass &= Utilities.CheckRemove(vmPowershellCmdlets.GetAzureDeployment, serviceName, DeploymentSlotType.Production); } catch (Exception e) { pass = false; Assert.Fail("Exception occurred: {0}", e.ToString()); } } // Disabled. Tracking Issue # 1479 [TestMethod(), TestCategory("Scenario"), TestProperty("Feature", "PAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet (New-AzureServiceRemoteDesktopConfig)")] [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\Resources\\package.csv", "package#csv", DataAccessMethod.Sequential)] public void AzureServiceRemoteDesktopExtensionConfigScenarioTest() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); // Choose the package and config files from local machine string packageName = Convert.ToString(TestContext.DataRow["upgradePackage"]); string configName = Convert.ToString(TestContext.DataRow["upgradeConfig"]); var packagePath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + packageName); var configPath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + configName); Assert.IsTrue(File.Exists(packagePath1.FullName), "VHD file not exist={0}", packagePath1); Assert.IsTrue(File.Exists(configPath1.FullName), "VHD file not exist={0}", configPath1); string deploymentName = "deployment1"; string deploymentLabel = "label1"; DeploymentInfoContext result; PSCredential cred = new PSCredential(username, Utilities.convertToSecureString(password)); string rdpPath = @".\WebRole1.rdp"; string dns; try { serviceName = Utilities.GetUniqueShortName(serviceNamePrefix); vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName); Console.WriteLine("service, {0}, is created.", serviceName); ExtensionConfigurationInput config = vmPowershellCmdlets.NewAzureServiceRemoteDesktopExtensionConfig(cred); vmPowershellCmdlets.NewAzureDeployment(serviceName, packagePath1.FullName, configPath1.FullName, DeploymentSlotType.Production, deploymentLabel, deploymentName, false, false, config); result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production); pass = Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, deploymentLabel, DeploymentSlotType.Production, null, 2); Console.WriteLine("successfully deployed the package"); RemoteDesktopExtensionContext resultContext = vmPowershellCmdlets.GetAzureServiceRemoteDesktopExtension(serviceName)[0]; VerifyRDPExtContext(resultContext, "AllRoles", "Default-RDP-Production-Ext-0", username, DateTime.Now.AddMonths(6)); Utilities.GetDeploymentAndWaitForReady(serviceName, DeploymentSlotType.Production, 10, 600); vmPowershellCmdlets.GetAzureRemoteDesktopFile("WebRole1_IN_0", serviceName, rdpPath, false); using (StreamReader stream = new StreamReader(rdpPath)) { string firstLine = stream.ReadLine(); dns = Utilities.FindSubstring(firstLine, ':', 2); } Assert.IsTrue((Utilities.RDPtestPaaS(dns, "WebRole1", 0, username, password, true)), "Cannot RDP to the instance!!"); vmPowershellCmdlets.RemoveAzureServiceRemoteDesktopExtension(serviceName); try { vmPowershellCmdlets.GetAzureRemoteDesktopFile("WebRole1_IN_0", serviceName, rdpPath, false); Assert.Fail("Succeeded, but extected to fail!"); } catch (Exception e) { if (e is AssertFailedException) { throw; } else { Console.WriteLine("Failed to get RDP file as expected"); } } vmPowershellCmdlets.RemoveAzureDeployment(serviceName, DeploymentSlotType.Production, true); pass &= Utilities.CheckRemove(vmPowershellCmdlets.GetAzureDeployment, serviceName, DeploymentSlotType.Production); } catch (Exception e) { pass = false; Assert.Fail("Exception occurred: {0}", e.ToString()); } } // Disabled. Tracking Issue # 1479 [TestMethod(), TestCategory("Scenario"), TestProperty("Feature", "PAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Get,Set,Remove)-AzureServiceRemoteDesktopExtension)")] [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\Resources\\package.csv", "package#csv", DataAccessMethod.Sequential)] public void AzureServiceRemoteDesktopExtensionTest() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); // Choose the package and config files from local machine string packageName = Convert.ToString(TestContext.DataRow["upgradePackage"]); string configName = Convert.ToString(TestContext.DataRow["upgradeConfig"]); var packagePath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + packageName); var configPath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + configName); Assert.IsTrue(File.Exists(packagePath1.FullName), "VHD file not exist={0}", packagePath1); Assert.IsTrue(File.Exists(configPath1.FullName), "VHD file not exist={0}", configPath1); string deploymentName = "deployment1"; string deploymentLabel = "label1"; DeploymentInfoContext result; PSCredential cred = new PSCredential(username, Utilities.convertToSecureString(password)); string rdpPath = @".\WebRole1.rdp"; string dns; try { serviceName = Utilities.GetUniqueShortName(serviceNamePrefix); vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName); Console.WriteLine("service, {0}, is created.", serviceName); vmPowershellCmdlets.NewAzureDeployment(serviceName, packagePath1.FullName, configPath1.FullName, DeploymentSlotType.Production, deploymentLabel, deploymentName, false, false); result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production); pass = Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, deploymentLabel, DeploymentSlotType.Production, null, 2); Console.WriteLine("successfully deployed the package"); vmPowershellCmdlets.SetAzureServiceRemoteDesktopExtension(serviceName, cred); RemoteDesktopExtensionContext resultContext = vmPowershellCmdlets.GetAzureServiceRemoteDesktopExtension(serviceName)[0]; VerifyRDPExtContext(resultContext, "AllRoles", "Default-RDP-Production-Ext-0", username, DateTime.Now.AddMonths(6)); vmPowershellCmdlets.GetAzureRemoteDesktopFile("WebRole1_IN_0", serviceName, rdpPath, false); using (StreamReader stream = new StreamReader(rdpPath)) { string firstLine = stream.ReadLine(); dns = Utilities.FindSubstring(firstLine, ':', 2); } Assert.IsTrue((Utilities.RDPtestPaaS(dns, "WebRole1", 0, username, password, true)), "Cannot RDP to the instance!!"); vmPowershellCmdlets.RemoveAzureServiceRemoteDesktopExtension(serviceName, true); try { vmPowershellCmdlets.GetAzureRemoteDesktopFile("WebRole1_IN_0", serviceName, rdpPath, false); Assert.Fail("Succeeded, but extected to fail!"); } catch (Exception e) { if (e is AssertFailedException) { throw; } else { Console.WriteLine("Failed to get RDP file as expected"); } } vmPowershellCmdlets.RemoveAzureDeployment(serviceName, DeploymentSlotType.Production, true); pass &= Utilities.CheckRemove(vmPowershellCmdlets.GetAzureDeployment, serviceName, DeploymentSlotType.Production); } catch (Exception e) { pass = false; Assert.Fail("Exception occurred: {0}", e.ToString()); } } [TestCleanup] public virtual void CleanUp() { Console.WriteLine("Test {0}", pass ? "passed" : "failed"); // Remove the service if ((cleanupIfPassed && pass) || (cleanupIfFailed && !pass)) { vmPowershellCmdlets.RemoveAzureService(serviceName); try { vmPowershellCmdlets.GetAzureService(serviceName); Console.WriteLine("The service, {0}, is not removed", serviceName); } catch (Exception e) { if (e.ToString().ToLowerInvariant().Contains("does not exist")) { Console.WriteLine("The service, {0}, is successfully removed", serviceName); } else { Console.WriteLine("Error occurred: {0}", e.ToString()); } } } } private string GetSiteContent(Uri uri, int maxRetryTimes, bool holdConnection) { Console.WriteLine("GetSiteContent. uri={0} maxRetryTimes={1}", uri.AbsoluteUri, maxRetryTimes); HttpWebRequest request; HttpWebResponse response = null; var noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore); HttpWebRequest.DefaultCachePolicy = noCachePolicy; int i; for (i = 1; i <= maxRetryTimes; i++) { try { request = (HttpWebRequest)WebRequest.Create(uri); request.Timeout = 10 * 60 * 1000; //set to 10 minutes, default 100 sec. default IE7/8 is 60 minutes response = (HttpWebResponse)request.GetResponse(); break; } catch (WebException e) { Console.WriteLine("Exception Message: " + e.Message); if (e.Status == WebExceptionStatus.ProtocolError) { Console.WriteLine("Status Code: {0}", ((HttpWebResponse)e.Response).StatusCode); Console.WriteLine("Status Description: {0}", ((HttpWebResponse)e.Response).StatusDescription); } } Thread.Sleep(30 * 1000); } if (i > maxRetryTimes) { throw new Exception("Web Site has error and reached maxRetryTimes"); } Stream responseStream = response.GetResponseStream(); StringBuilder sb = new StringBuilder(); byte[] buf = new byte[100]; int length; while ((length = responseStream.Read(buf, 0, 100)) != 0) { if (holdConnection) { Thread.Sleep(TimeSpan.FromSeconds(10)); } sb.Append(Encoding.UTF8.GetString(buf, 0, length)); } string responseString = sb.ToString(); Console.WriteLine("Site content: (IsFromCache={0})", response.IsFromCache); Console.WriteLine(responseString); return responseString; } private bool GetVNetState(string vnet, ProvisioningState expectedState, int maxTime, int intervalTime) { ProvisioningState vnetState; int i = 0; do { vnetState = vmPowershellCmdlets.GetAzureVNetGateway(vnet)[0].State; Thread.Sleep(intervalTime * 1000); i++; } while (!vnetState.Equals(expectedState) || i < maxTime); return vnetState.Equals(expectedState); } private bool VerifyDiagExtContext(DiagnosticExtensionContext resultContext, string role, string extID, string storage, XmlDocument config) { try { Assert.AreEqual(role, resultContext.Role.RoleType.ToString()); Assert.AreEqual("Diagnostics", resultContext.Extension); Assert.AreEqual(extID, resultContext.Id); Assert.AreEqual(storage, resultContext.StorageAccountName); string inner = Utilities.GetInnerXml(resultContext.WadCfg, "WadCfg"); Assert.IsTrue(Utilities.CompareWadCfg(inner, config)); return true; } catch { return false; } } private bool VerifyRDPExtContext(RemoteDesktopExtensionContext resultContext, string role, string extID, string userName, DateTime exp) { try { Assert.AreEqual(role, resultContext.Role.RoleType.ToString()); Assert.AreEqual("RDP", resultContext.Extension); Assert.AreEqual(extID, resultContext.Id); Assert.AreEqual(userName, resultContext.UserName); Assert.IsTrue(Utilities.CompareDateTime(exp, resultContext.Expiration)); return true; } catch { return false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO; using System.Runtime; using Internal.Runtime.Augments; using Microsoft.Win32.SafeHandles; namespace System.Threading { public abstract partial class WaitHandle { internal static unsafe int WaitForSingleObject(IntPtr handle, int millisecondsTimeout) { SynchronizationContext context = RuntimeThread.CurrentThread.SynchronizationContext; bool useSyncContextWait = (context != null) && context.IsWaitNotificationRequired(); if (useSyncContextWait) { var handles = new IntPtr[1] { handle }; return context.Wait(handles, false, millisecondsTimeout); } return WaitForMultipleObjectsIgnoringSyncContext(&handle, 1, false, millisecondsTimeout); } internal static unsafe int WaitForMultipleObjectsIgnoringSyncContext(IntPtr[] handles, int numHandles, bool waitAll, int millisecondsTimeout) { fixed (IntPtr* pHandles = handles) { return WaitForMultipleObjectsIgnoringSyncContext(pHandles, numHandles, waitAll, millisecondsTimeout); } } private static unsafe int WaitForMultipleObjectsIgnoringSyncContext(IntPtr* pHandles, int numHandles, bool waitAll, int millisecondsTimeout) { Debug.Assert(millisecondsTimeout >= -1); // // In the CLR, we use CoWaitForMultipleHandles to pump messages while waiting in an STA. In that case, we cannot use WAIT_ALL. // That's because the wait would only be satisfied if a message arrives while the handles are signalled. // if (waitAll) { if (numHandles == 1) waitAll = false; else if (RuntimeThread.GetCurrentApartmentType() == RuntimeThread.ApartmentType.STA) throw new NotSupportedException(SR.NotSupported_WaitAllSTAThread); } RuntimeThread currentThread = RuntimeThread.CurrentThread; currentThread.SetWaitSleepJoinState(); int result; if (RuntimeThread.ReentrantWaitsEnabled) { Debug.Assert(!waitAll); result = RuntimeImports.RhCompatibleReentrantWaitAny(false, millisecondsTimeout, numHandles, pHandles); } else { result = (int)Interop.mincore.WaitForMultipleObjectsEx((uint)numHandles, (IntPtr)pHandles, waitAll, (uint)millisecondsTimeout, false); } currentThread.ClearWaitSleepJoinState(); if (result == WaitHandle.WaitFailed) { int errorCode = Interop.mincore.GetLastError(); if (waitAll && errorCode == Interop.Errors.ERROR_INVALID_PARAMETER) { // Check for duplicate handles. This is a brute force O(n^2) search, which is intended since the typical // array length is short enough that this would actually be faster than using a hash set. Also, the worst // case is not so bad considering that the array length is limited by // <see cref="WaitHandle.MaxWaitHandles"/>. for (int i = 1; i < numHandles; ++i) { IntPtr handle = pHandles[i]; for (int j = 0; j < i; ++j) { if (pHandles[j] == handle) { throw new DuplicateWaitObjectException("waitHandles[" + i + ']'); } } } } ThrowWaitFailedException(errorCode); } return result; } private static bool WaitOneCore(IntPtr handle, int millisecondsTimeout) { Debug.Assert(millisecondsTimeout >= -1); int ret = WaitForSingleObject(handle, millisecondsTimeout); if (ret == WaitAbandoned) { ThrowAbandonedMutexException(); } return ret != WaitTimeout; } /*======================================================================== ** Waits for signal from all the objects. ** timeout indicates how long to wait before the method returns. ** This method will return either when all the object have been pulsed ** or timeout milliseonds have elapsed. ========================================================================*/ private static int WaitMultiple( RuntimeThread currentThread, SafeWaitHandle[] safeWaitHandles, int count, int millisecondsTimeout, bool waitAll) { Debug.Assert(currentThread == RuntimeThread.CurrentThread); Debug.Assert(safeWaitHandles != null); Debug.Assert(safeWaitHandles.Length >= count); // If we need to call SynchronizationContext.Wait method, always allocate a new IntPtr[] SynchronizationContext context = currentThread.SynchronizationContext; bool useSyncContextWait = (context != null) && context.IsWaitNotificationRequired(); IntPtr[] rentedHandles = useSyncContextWait ? null : currentThread.RentWaitedHandleArray(count); IntPtr[] handles = rentedHandles ?? new IntPtr[count]; try { for (int i = 0; i < count; i++) { handles[i] = safeWaitHandles[i].DangerousGetHandle(); } if (useSyncContextWait) { return context.Wait(handles, waitAll, millisecondsTimeout); } return WaitForMultipleObjectsIgnoringSyncContext(handles, count, waitAll, millisecondsTimeout); } finally { if (rentedHandles != null) { currentThread.ReturnWaitedHandleArray(rentedHandles); } } } private static int WaitAnyCore( RuntimeThread currentThread, SafeWaitHandle[] safeWaitHandles, WaitHandle[] waitHandles, int millisecondsTimeout) { Debug.Assert(currentThread == RuntimeThread.CurrentThread); Debug.Assert(safeWaitHandles != null); Debug.Assert(safeWaitHandles.Length >= waitHandles.Length); Debug.Assert(waitHandles != null); Debug.Assert(waitHandles.Length > 0); Debug.Assert(waitHandles.Length <= MaxWaitHandles); Debug.Assert(millisecondsTimeout >= -1); int ret = WaitMultiple(currentThread, safeWaitHandles, waitHandles.Length, millisecondsTimeout, false /* waitany*/ ); if ((WaitAbandoned <= ret) && (WaitAbandoned + waitHandles.Length > ret)) { int mutexIndex = ret - WaitAbandoned; if (0 <= mutexIndex && mutexIndex < waitHandles.Length) { ThrowAbandonedMutexException(mutexIndex, waitHandles[mutexIndex]); } else { ThrowAbandonedMutexException(); } } return ret; } private static bool WaitAllCore( RuntimeThread currentThread, SafeWaitHandle[] safeWaitHandles, WaitHandle[] waitHandles, int millisecondsTimeout) { Debug.Assert(currentThread == RuntimeThread.CurrentThread); Debug.Assert(safeWaitHandles != null); Debug.Assert(safeWaitHandles.Length >= waitHandles.Length); Debug.Assert(millisecondsTimeout >= -1); int ret = WaitMultiple(currentThread, safeWaitHandles, waitHandles.Length, millisecondsTimeout, true /* waitall*/ ); if ((WaitAbandoned <= ret) && (WaitAbandoned + waitHandles.Length > ret)) { //In the case of WaitAll the OS will only provide the // information that mutex was abandoned. // It won't tell us which one. So we can't set the Index or provide access to the Mutex ThrowAbandonedMutexException(); } return ret != WaitTimeout; } private static bool SignalAndWaitCore(IntPtr handleToSignal, IntPtr handleToWaitOn, int millisecondsTimeout) { Debug.Assert(millisecondsTimeout >= -1); int ret = (int)Interop.mincore.SignalObjectAndWait(handleToSignal, handleToWaitOn, (uint)millisecondsTimeout, false); if (ret == WaitAbandoned) { ThrowAbandonedMutexException(); } if (ret == WaitFailed) { ThrowWaitFailedException(Interop.mincore.GetLastError()); } return ret != WaitTimeout; } private static void ThrowAbandonedMutexException() { throw new AbandonedMutexException(); } private static void ThrowAbandonedMutexException(int location, WaitHandle handle) { throw new AbandonedMutexException(location, handle); } internal static void ThrowSignalOrUnsignalException() { int errorCode = Interop.mincore.GetLastError(); switch (errorCode) { case Interop.Errors.ERROR_INVALID_HANDLE: ThrowInvalidHandleException(); break; case Interop.Errors.ERROR_TOO_MANY_POSTS: throw new SemaphoreFullException(); case Interop.Errors.ERROR_NOT_OWNER: throw new ApplicationException(SR.Arg_SynchronizationLockException); default: var ex = new Exception(); ex.SetErrorCode(errorCode); throw ex; } } private static void ThrowWaitFailedException(int errorCode) { switch (errorCode) { case Interop.Errors.ERROR_INVALID_HANDLE: ThrowInvalidHandleException(); break; case Interop.Errors.ERROR_INVALID_PARAMETER: throw new ArgumentException(); case Interop.Errors.ERROR_ACCESS_DENIED: throw new UnauthorizedAccessException(); case Interop.Errors.ERROR_NOT_ENOUGH_MEMORY: throw new OutOfMemoryException(); case Interop.Errors.ERROR_TOO_MANY_POSTS: // Only applicable to <see cref="WaitHandle.SignalAndWait(WaitHandle, WaitHandle)"/>. Note however, that // if the semahpore already has the maximum signal count, the Windows SignalObjectAndWait function does not // return an error, but this code is kept for historical reasons and to convey the intent, since ideally, // that should be an error. throw new InvalidOperationException(SR.Threading_SemaphoreFullException); case Interop.Errors.ERROR_NOT_OWNER: // Only applicable to <see cref="WaitHandle.SignalAndWait(WaitHandle, WaitHandle)"/> when signaling a mutex // that is locked by a different thread. Note that if the mutex is already unlocked, the Windows // SignalObjectAndWait function does not return an error. throw new ApplicationException(SR.Arg_SynchronizationLockException); case Interop.Errors.ERROR_MUTANT_LIMIT_EXCEEDED: throw new OverflowException(SR.Overflow_MutexReacquireCount); default: Exception ex = new Exception(); ex.SetErrorCode(errorCode); throw ex; } } internal static Exception ExceptionFromCreationError(int errorCode, string path) { switch (errorCode) { case Interop.Errors.ERROR_PATH_NOT_FOUND: return new IOException(SR.Format(SR.IO_PathNotFound_Path, path)); case Interop.Errors.ERROR_ACCESS_DENIED: return new UnauthorizedAccessException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, path)); case Interop.Errors.ERROR_ALREADY_EXISTS: return new IOException(SR.Format(SR.IO_AlreadyExists_Name, path)); case Interop.Errors.ERROR_FILENAME_EXCED_RANGE: return new PathTooLongException(); default: return new IOException(SR.Arg_IOException, errorCode); } } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ShellShopResolver.cs" company="Sitecore Corporation"> // Copyright (c) Sitecore Corporation 1999-2015 // </copyright> // <summary> // Defines the shell shop resolver class. // </summary> // -------------------------------------------------------------------------------------------------------------------- // Copyright 2015 Sitecore Corporation A/S // 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 Sitecore.Ecommerce.Shell.Pipelines.HttpRequest { using System; using System.Linq; using System.Web; using Microsoft.Practices.Unity; using Sitecore.Data; using Sitecore.Pipelines; using Sitecore.Sites; /// <summary> /// Defines the shell shop resolver class. /// </summary> public class ShellShopResolver { /// <summary> /// The HttpContextBase instance. /// </summary> private HttpContextBase httpContext; /// <summary> /// The shop context factory. /// </summary> private ShopContextFactory shopContextFactory; /// <summary> /// The shop configuration. /// </summary> private ShopConfiguration shopConfiguration; /// <summary> /// The shop context switcher. /// </summary> private ShopContextSwitcher shopContextSwitcher; /// <summary> /// Gets or sets the HTTP context. /// </summary> /// <value>The HTTP context.</value> [NotNull] public HttpContextBase HttpContext { get { if (this.httpContext == null) { HttpContext context = System.Web.HttpContext.Current; this.httpContext = new HttpContextWrapper(context); } return this.httpContext; } set { this.httpContext = value; } } /// <summary> /// Gets or sets the shop context factory. /// </summary> /// <value> /// The shop context factory. /// </value> [NotNull] public ShopContextFactory ShopContextFactory { get { return this.shopContextFactory ?? (this.shopContextFactory = Context.Entity.Resolve<ShopContextFactory>()); } set { this.shopContextFactory = value; } } /// <summary> /// Gets or sets the shop configuration. /// </summary> /// <value> /// The shop configuration. /// </value> [NotNull] public ShopConfiguration ShopConfiguration { get { return this.shopConfiguration ?? (this.shopConfiguration = Context.Entity.Resolve<ShopConfiguration>()); } set { this.shopConfiguration = value; } } /// <summary> /// Gets or sets the name of the shell site. /// </summary> /// <value> /// The name of the shell site. /// </value> [NotNull] public string ShellSiteName { get; set; } /// <summary> /// Runs the processor. /// </summary> /// <param name="args">The arguments.</param> public void Process(PipelineArgs args) { this.ResetHttpContext(); SiteContext site = Sitecore.Context.Site; if (site == null || string.Compare(this.ShellSiteName, site.Name, StringComparison.OrdinalIgnoreCase) != 0) { return; } var queryString = this.HttpContext.Request.QueryString; string itemId = queryString["id"] ?? queryString["sc_itemid"]; if (string.IsNullOrEmpty(itemId) || !ID.IsID(itemId)) { return; } string databaseOverrideName = queryString["database"] ?? queryString["db"] ?? queryString["sc_database"]; Database databaseOverride = null; if (!string.IsNullOrEmpty(databaseOverrideName)) { databaseOverride = Database.GetDatabase(databaseOverrideName); } var shop = this.ShopContextFactory.GetWebShops().FirstOrDefault(sh => this.CheckIfCurrentShopContext(sh, databaseOverride, ID.Parse(itemId))); if (shop == null) { return; } shop.GeneralSettings = this.ShopConfiguration.GetGeneralSettings(shop.InnerSite, shop.Database); shop.BusinessCatalogSettings = this.ShopConfiguration.GetBusinesCatalogSettings(shop.InnerSite, shop.Database); // INFO: looks like using factories here is an overdesign. Simple instantiation is used instead. this.shopContextSwitcher = new ShopContextSwitcher(shop); } /// <summary> /// Checks if current shop context. /// </summary> /// <param name="shopContext">The shop context.</param> /// <param name="database">The database.</param> /// <param name="itemId">The item identifier.</param> /// <returns>True if current shop context, otherwise false.</returns> private bool CheckIfCurrentShopContext(ShopContext shopContext, Database database, ID itemId) { if (database != null) { shopContext.Database = database; } return this.CheckIfCurrentSiteContextByHomePath(shopContext, itemId) || this.CheckIfCurrentSiteContextByContentPath(shopContext, itemId); } /// <summary> /// Checks if current site context by home path. /// </summary> /// <param name="shopContext">The shop context.</param> /// <param name="itemId">The item identifier.</param> /// <returns>True if current shop context, otherwise false.</returns> private bool CheckIfCurrentSiteContextByHomePath(ShopContext shopContext, ID itemId) { return this.CheckIfItemIsDescendantOfSiteContextRoot(shopContext, itemId, shopContext.InnerSite.RootPath + shopContext.InnerSite.StartItem); } /// <summary> /// Checks if current site context by content path. /// </summary> /// <param name="shopContext">The shop context.</param> /// <param name="itemId">The item identifier.</param> /// <returns>True if current shop context, otherwise false.</returns> private bool CheckIfCurrentSiteContextByContentPath(ShopContext shopContext, ID itemId) { return this.CheckIfItemIsDescendantOfSiteContextRoot(shopContext, itemId, shopContext.InnerSite.RootPath); } /// <summary> /// Checks if item is descendant of site context root. /// </summary> /// <param name="shopContext">The shop context.</param> /// <param name="itemId">The item identifier.</param> /// <param name="rootPath">The root path.</param> /// <returns>True if current shop context, otherwise false.</returns> private bool CheckIfItemIsDescendantOfSiteContextRoot(ShopContext shopContext, ID itemId, string rootPath) { if (shopContext.Database == null) { return false; } var item = shopContext.Database.GetItem(itemId); var rootItem = shopContext.Database.GetItem(rootPath); return item != null && rootItem != null && (rootItem.Axes.IsAncestorOf(item) || rootItem.ID == itemId); } /// <summary> /// Resets the HTTP context. /// </summary> private void ResetHttpContext() { if (System.Web.HttpContext.Current != null) { if (this.HttpContext.Request.RawUrl != System.Web.HttpContext.Current.Request.RawUrl) { this.httpContext = null; } } } } }
// Copyright (c) 2012, Event Store LLP // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the Event Store LLP 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 // 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.Linq; using System.Security.Principal; using EventStore.Core.Bus; using EventStore.Core.Data; using EventStore.Core.Helpers; using EventStore.Core.Messages; using EventStore.Core.Messaging; using EventStore.Core.Services.TimerService; using EventStore.Projections.Core.Messages; using EventStore.Projections.Core.Messaging; namespace EventStore.Projections.Core.Services.Processing { public class MultiStreamEventReader : EventReader, IHandle<ClientMessage.ReadStreamEventsForwardCompleted> { private readonly HashSet<string> _streams; private CheckpointTag _fromPositions; private readonly bool _resolveLinkTos; private readonly ITimeProvider _timeProvider; private readonly HashSet<string> _eventsRequested = new HashSet<string>(); private readonly Dictionary<string, long?> _preparePositions = new Dictionary<string, long?>(); // event, link, progress // null element in a queue means tream deleted private readonly Dictionary<string, Queue<Tuple<EventStore.Core.Data.ResolvedEvent, float>>> _buffers = new Dictionary<string, Queue<Tuple<EventStore.Core.Data.ResolvedEvent, float>>>(); private const int _maxReadCount = 111; private long? _safePositionToJoin; private readonly Dictionary<string, bool> _eofs; private int _deliveredEvents; private long _lastPosition; public MultiStreamEventReader( IODispatcher ioDispatcher, IPublisher publisher, Guid eventReaderCorrelationId, IPrincipal readAs, int phase, string[] streams, Dictionary<string, int> fromPositions, bool resolveLinkTos, ITimeProvider timeProvider, bool stopOnEof = false, int? stopAfterNEvents = null) : base(ioDispatcher, publisher, eventReaderCorrelationId, readAs, stopOnEof, stopAfterNEvents) { if (streams == null) throw new ArgumentNullException("streams"); if (timeProvider == null) throw new ArgumentNullException("timeProvider"); if (streams.Length == 0) throw new ArgumentException("streams"); _streams = new HashSet<string>(streams); _eofs = _streams.ToDictionary(v => v, v => false); var positions = CheckpointTag.FromStreamPositions(phase, fromPositions); ValidateTag(positions); _fromPositions = positions; _resolveLinkTos = resolveLinkTos; _timeProvider = timeProvider; foreach (var stream in streams) { _preparePositions.Add(stream, null); } } private void ValidateTag(CheckpointTag fromPositions) { if (_streams.Count != fromPositions.Streams.Count) throw new ArgumentException("Number of streams does not match", "fromPositions"); foreach (var stream in _streams) { if (!fromPositions.Streams.ContainsKey(stream)) throw new ArgumentException( string.Format("The '{0}' stream position has not been set", stream), "fromPositions"); } } protected override void RequestEvents() { if (PauseRequested || Paused) return; if (_eofs.Any(v => v.Value)) _publisher.Publish( TimerMessage.Schedule.Create( TimeSpan.FromMilliseconds(250), new PublishEnvelope(_publisher, crossThread: true), new UnwrapEnvelopeMessage(ProcessBuffers2))); foreach (var stream in _streams) RequestEvents(stream, delay: _eofs[stream]); } private void ProcessBuffers2() { ProcessBuffers(); CheckIdle(); } protected override bool AreEventsRequested() { return _eventsRequested.Count != 0; } public void Handle(ClientMessage.ReadStreamEventsForwardCompleted message) { if (_disposed) return; if (!_streams.Contains(message.EventStreamId)) throw new InvalidOperationException(string.Format("Invalid stream name: {0}", message.EventStreamId)); if (!_eventsRequested.Contains(message.EventStreamId)) throw new InvalidOperationException("Read events has not been requested"); if (Paused) throw new InvalidOperationException("Paused"); _lastPosition = message.TfLastCommitPosition; switch (message.Result) { case ReadStreamResult.StreamDeleted: case ReadStreamResult.NoStream: _eofs[message.EventStreamId] = true; UpdateSafePositionToJoin(message.EventStreamId, MessageToLastCommitPosition(message)); if (message.Result == ReadStreamResult.NoStream && message.LastEventNumber >= 0) EnqueueItem(null, message.EventStreamId); ProcessBuffers(); _eventsRequested.Remove(message.EventStreamId); PauseOrContinueProcessing(); CheckIdle(); CheckEof(); break; case ReadStreamResult.Success: if (message.Events.Length == 0) { // the end _eofs[message.EventStreamId] = true; UpdateSafePositionToJoin(message.EventStreamId, MessageToLastCommitPosition(message)); CheckIdle(); CheckEof(); } else { _eofs[message.EventStreamId] = false; for (int index = 0; index < message.Events.Length; index++) { var @event = message.Events[index].Event; var @link = message.Events[index].Link; EventRecord positionEvent = (link ?? @event); UpdateSafePositionToJoin( positionEvent.EventStreamId, EventPairToPosition(message.Events[index])); Tuple<EventStore.Core.Data.ResolvedEvent, float> itemToEnqueue = Tuple.Create(message.Events[index], 100.0f*(link ?? @event).EventNumber/message.LastEventNumber); EnqueueItem(itemToEnqueue, positionEvent.EventStreamId); } } ProcessBuffers(); _eventsRequested.Remove(message.EventStreamId); PauseOrContinueProcessing(); break; case ReadStreamResult.AccessDenied: SendNotAuthorized(); return; default: throw new NotSupportedException( string.Format("ReadEvents result code was not recognized. Code: {0}", message.Result)); } } private void EnqueueItem(Tuple<EventStore.Core.Data.ResolvedEvent, float> itemToEnqueue, string streamId) { Queue<Tuple<EventStore.Core.Data.ResolvedEvent, float>> queue; if (!_buffers.TryGetValue(streamId, out queue)) { queue = new Queue<Tuple<EventStore.Core.Data.ResolvedEvent, float>>(); _buffers.Add(streamId, queue); } //TODO: progress calculation below is incorrect. sum(current)/sum(last_event) where sum by all streams queue.Enqueue(itemToEnqueue); } private void CheckEof() { if (_eofs.All(v => v.Value)) SendEof(); } private void CheckIdle() { if (_eofs.All(v => v.Value)) _publisher.Publish( new ReaderSubscriptionMessage.EventReaderIdle(EventReaderCorrelationId, _timeProvider.Now)); } private void ProcessBuffers() { if (_disposed) return; if (_safePositionToJoin == null) return; while (true) { var anyNonEmpty = false; var minStreamId = ""; var any = false; var minPosition = GetMaxPosition(); foreach (var buffer in _buffers) { if (buffer.Value.Count == 0) continue; anyNonEmpty = true; var head = buffer.Value.Peek(); var currentStreamId = buffer.Key; var itemPosition = GetItemPosition(head); if (_safePositionToJoin != null && itemPosition.CompareTo(_safePositionToJoin.GetValueOrDefault()) <= 0 && itemPosition.CompareTo(minPosition) < 0) { minPosition = itemPosition; minStreamId = currentStreamId; any = true; } } if (!any) { if (!anyNonEmpty) DeliverSafePositionToJoin(); break; } var minHead = _buffers[minStreamId].Dequeue(); DeliverEvent(minHead.Item1, minHead.Item2); if (CheckEnough()) return; if (_buffers[minStreamId].Count == 0) PauseOrContinueProcessing(); } } private bool CheckEnough() { if (_stopAfterNEvents != null && _deliveredEvents >= _stopAfterNEvents) { _publisher.Publish(new ReaderSubscriptionMessage.EventReaderEof(EventReaderCorrelationId, maxEventsReached: true)); Dispose(); return true; } return false; } private void RequestEvents(string stream, bool delay) { if (_disposed) throw new InvalidOperationException("Disposed"); if (PauseRequested || Paused) throw new InvalidOperationException("Paused or pause requested"); if (_eventsRequested.Contains(stream)) return; Queue<Tuple<EventStore.Core.Data.ResolvedEvent, float>> queue; if (_buffers.TryGetValue(stream, out queue) && queue.Count > 0) return; _eventsRequested.Add(stream); var readEventsForward = new ClientMessage.ReadStreamEventsForward( Guid.NewGuid(), EventReaderCorrelationId, new SendToThisEnvelope(this), stream, _fromPositions.Streams[stream], _maxReadCount, _resolveLinkTos, false, null, ReadAs); if (delay) _publisher.Publish( new AwakeReaderServiceMessage.SubscribeAwake( new PublishEnvelope(_publisher, crossThread: true), Guid.NewGuid(), null, new TFPos(_lastPosition, _lastPosition), readEventsForward)); else _publisher.Publish(readEventsForward); } private void DeliverSafePositionToJoin() { if (_stopOnEof || _stopAfterNEvents != null || _safePositionToJoin == null) return; // deliver if already available _publisher.Publish( new ReaderSubscriptionMessage.CommittedEventDistributed( EventReaderCorrelationId, null, PositionToSafeJoinPosition(_safePositionToJoin), 100.0f, source: this.GetType())); } private void UpdateSafePositionToJoin(string streamId, long? preparePosition) { _preparePositions[streamId] = preparePosition; if (_preparePositions.All(v => v.Value != null)) _safePositionToJoin = _preparePositions.Min(v => v.Value.GetValueOrDefault()); } private void DeliverEvent(EventStore.Core.Data.ResolvedEvent pair, float progress) { _deliveredEvents ++; var positionEvent = pair.OriginalEvent; string streamId = positionEvent.EventStreamId; int fromPosition = _fromPositions.Streams[streamId]; if (positionEvent.EventNumber != fromPosition) throw new InvalidOperationException( string.Format( "Event number {0} was expected in the stream {1}, but event number {2} was received", fromPosition, streamId, positionEvent.EventNumber)); _fromPositions = _fromPositions.UpdateStreamPosition(streamId, positionEvent.EventNumber + 1); _publisher.Publish( //TODO: publish both link and event data new ReaderSubscriptionMessage.CommittedEventDistributed( EventReaderCorrelationId, new ResolvedEvent(pair, null), _stopOnEof ? (long?) null : positionEvent.LogPosition, progress, source: this.GetType())); } private long? EventPairToPosition(EventStore.Core.Data.ResolvedEvent resolvedEvent) { return resolvedEvent.OriginalEvent.LogPosition; } private long? MessageToLastCommitPosition(ClientMessage.ReadStreamEventsForwardCompleted message) { return GetLastCommitPositionFrom(message); } private long GetItemPosition(Tuple<EventStore.Core.Data.ResolvedEvent, float> head) { return head.Item1.OriginalEvent.LogPosition; } private long GetMaxPosition() { return long.MaxValue; } private long? PositionToSafeJoinPosition(long? safePositionToJoin) { return safePositionToJoin; } } }
#if !MONO using System; using System.Collections.Generic; using System.Linq; using System.Drawing; using System.Windows.Forms; namespace SIL.Media.Naudio.UI { /// <summary> /// This control displays an icon and tooltip to indicate which recording device is currently in use. /// It also monitors the set of connected RecordingDevices and (a) switches to a new one if it appears, /// as for example when a new microphone is plugged in; (b) switches to the default one if the current /// one is unplugged. You can customize the icons using the __Image properties. /// </summary> /// <remarks> /// Enhance JohnT: Possibly the RecordingDeviceIndicator could become a RecordingDeviceButton and could respond to a click by cycling through /// the available devices, or pop up a chooser...though that is probably overdoing things, users /// are unlikely to have more than two. Currently there is no click behavior. /// </remarks> public partial class RecordingDeviceIndicator : UserControl { private IAudioRecorder _recorder; Timer _checkNewMicTimer = new Timer(); private HashSet<string> _knownRecordingDevices; /// <summary> /// Used to look at what names the OS has for a device and choose an icon. These are stored as functions so that we don't /// have to tell clients *when* they are allowed to override these. /// </summary> private readonly List<KeyValuePair<string, Func<Image>>> _nameSubstringToIconProperty = new List<KeyValuePair<string, Func<Image>>>(); // These allow clients to set their own images to match their color schemes public Image NoAudioDeviceImage { get; set; } = AudioDeviceIcons.NoAudioDevice; public Image WebcamImage { get; set; } = AudioDeviceIcons.Webcam; public Image ComputerInternalImage { get; set; } = AudioDeviceIcons.Computer; public Image KnownHeadsetImage { get; set; } = AudioDeviceIcons.Headset; public Image UsbAudioDeviceImage { get; set; } = AudioDeviceIcons.Headset; public Image MicrophoneImage { get; set; } = AudioDeviceIcons.Microphone; public Image LineImage { get; set; } = AudioDeviceIcons.Line; public Image RecorderImage { get; set; } = AudioDeviceIcons.Recorder; public RecordingDeviceIndicator() : this(1000, true) { } public RecordingDeviceIndicator(int checkNewMicTimerInterval, bool checkNewMicTimerInitiallyEnabled) { InitializeComponent(); // All the audio device icons shipped with libpalaso 16px high, but of varying width. // Because we allow clients to give different icons, honor whatever height/width they came in at, // no scaling. Done here so we can have this comment. _recordingDeviceImage.SizeMode = PictureBoxSizeMode.AutoSize; _checkNewMicTimer.Tick += OnCheckNewMicTimer_Tick; _checkNewMicTimer.Interval = checkNewMicTimerInterval; MicCheckingEnabled = checkNewMicTimerInitiallyEnabled; } /// <summary> /// This allows the client to suspend the periodic checking during operations (other than recording) where it is /// undesirable to change devices (or take the time to check for them). /// </summary> public bool MicCheckingEnabled { set { _checkNewMicTimer.Enabled = value; } } /// <summary> /// This control will find out about selected devices from the recorder, but also will tell the recorder to change devices as needed. /// </summary> public IAudioRecorder Recorder { get { return _recorder; } set { if(_recorder != null) _recorder.SelectedDeviceChanged -= RecorderOnSelectedDeviceChanged; _recorder = value; if(_recorder != null) { _recorder.SelectedDeviceChanged += RecorderOnSelectedDeviceChanged; _checkNewMicTimer.Start(); SetKnownRecordingDevices(RecordingDevice.Devices); } else { _checkNewMicTimer.Stop(); } if(IsHandleCreated) UpdateDisplay(); } } private void SetKnownRecordingDevices(IEnumerable<RecordingDevice> devices) { _knownRecordingDevices = new HashSet<string>(devices.Select(d => d.ProductName)); } /// <summary> /// This is invoked once per second. /// It looks for new recording devices, such as when a mic is plugged in. If it finds one, /// it switches the Recorder to use it. /// It also checks whether the current recording device is still available. If not, /// it switches to whatever is the current default recording device (unless a new one was found, /// which takes precedence). /// The list of RecordingDevice.Devices, at least on Win7 with USB mics, seems to update as things /// are connected and disconnected. /// I'm not sure this approach will detect the plugging and unplugging of non-USB mics. /// </summary> /// <remarks>We compare product names rather than actual devices, because it appears that /// RecordingDevices.Devices creates a new list of objects each time; the ones from one call /// are never equal to the ones from a previous call.</remarks> /// <param name="sender"></param> /// <param name="e"></param> void OnCheckNewMicTimer_Tick(object sender, EventArgs e) { if(_recorder == null) return; // Don't try to change horses in the middle of the stream if recording is in progress. if(_recorder.RecordingState != RecordingState.Monitoring && _recorder.RecordingState != RecordingState.Stopped) return; bool foundCurrentDevice = false; var devices = RecordingDevice.Devices.ToList(); foreach(var device in devices) { if(!_knownRecordingDevices.Contains(device.ProductName)) { _recorder.SelectedDevice = device; if(_recorder.RecordingState == RecordingState.Monitoring) { _knownRecordingDevices.Add(device.ProductName); UpdateDisplay(); return; } } if(_recorder.SelectedDevice != null && device.ProductName == _recorder.SelectedDevice.ProductName) foundCurrentDevice = true; } if(foundCurrentDevice) { if(_recorder.RecordingState != RecordingState.Monitoring) { _recorder.BeginMonitoring(); if(_recorder.RecordingState == RecordingState.Monitoring) UpdateDisplay(); } } else { // presumably unplugged...try to switch to another. var defaultDevice = devices.FirstOrDefault(); if(defaultDevice != _recorder.SelectedDevice) { _recorder.SelectedDevice = defaultDevice; UpdateDisplay(); } } // Update the list so one that was never active can be made active by unplugging and replugging SetKnownRecordingDevices(devices); } protected override void OnHandleDestroyed(EventArgs e) { if(_checkNewMicTimer != null) { _checkNewMicTimer.Stop(); _checkNewMicTimer.Dispose(); _checkNewMicTimer = null; } if(_recorder != null) _recorder.SelectedDeviceChanged -= RecorderOnSelectedDeviceChanged; base.OnHandleDestroyed(e); } private void RecorderOnSelectedDeviceChanged(object sender, EventArgs eventArgs) { UpdateDisplay(); } protected override void OnLoad(EventArgs e) { PrepareNameToIconLookup(); UpdateDisplay(); base.OnLoad(e); } public void UpdateDisplay() { if(_recorder?.SelectedDevice == null) { toolTip1.SetToolTip(_recordingDeviceImage, "no input device"); } if(_recorder == null) return; if(Recorder.SelectedDevice == null) _recordingDeviceImage.Image = NoAudioDeviceImage; else { toolTip1.SetToolTip(_recordingDeviceImage, _recorder.SelectedDevice.GenericName); _recordingDeviceImage.Image = GetIconForRecordingDevice(); } } private Image GetIconForRecordingDevice() { foreach(var pair in _nameSubstringToIconProperty) { var substring = pair.Key.ToLowerInvariant(); if(_recorder.SelectedDevice.GenericName.ToLowerInvariant().Contains(substring) || _recorder.SelectedDevice.ProductName.ToLowerInvariant().Contains(substring)) { return pair.Value(); } } return MicrophoneImage; } private void RecordingDeviceIndicator_Click(object sender, EventArgs e) { try { // launch the control panel that shows the user all their recording device options System.Diagnostics.Process.Start("control", "mmsys.cpl,,1"); } catch(Exception) { // ah well, we tried, nothing useful to tell the user. } } private void PrepareNameToIconLookup() { AddDeviceMatch("None", () => NoAudioDeviceImage); //NB order is important here, as these are used in a substring match, so put the more specific ones (e.g. Webcam) before more general ones (e.g. Microphone) AddDeviceMatch("Webcam", () => WebcamImage); AddDeviceMatch("Internal", () => ComputerInternalImage); AddDeviceMatch("Headset", () => KnownHeadsetImage); // Technically not necessarily a "known" headset... AddDeviceMatch("USB Audio Device", () => UsbAudioDeviceImage); AddDeviceMatch("Microphone", () => MicrophoneImage); AddDeviceMatch("Line", () => LineImage); AddDeviceMatch("ZOOM", () => RecorderImage); // not sure if this ever gets used; it would if we had a recording device but failed to figure out anything else about it AddDeviceMatch("Generic", () => MicrophoneImage); // Headset device names // It's not clear to me why these device names are needed, but the original code was written in a way that // suggests sometimes the SelectedDevice.GenericName is null, requiring us to match on specific device names. foreach(var name in new[] {"Plantronics", "Andrea", "Microphone (VXi X200"}) { AddDeviceMatch(name, () => KnownHeadsetImage); } } private void AddDeviceMatch(string substring, Func<Image> function) { _nameSubstringToIconProperty.Add(new KeyValuePair<string, Func<Image>>(substring, function)); } } } #endif
namespace UnityStandardAssets.CinematicEffects { using UnityEngine; using UnityEditor; using UnityEditorInternal; using System.Reflection; using System.Collections.Generic; using System.Linq; [CanEditMultipleObjects, CustomEditor(typeof(TonemappingColorGrading))] public class TonemappingColorGradingEditor : Editor { #region Property drawers [CustomPropertyDrawer(typeof(TonemappingColorGrading.ColorWheelGroup))] private class ColorWheelGroupDrawer : PropertyDrawer { int m_RenderSizePerWheel; int m_NumberOfWheels; public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { var wheelAttribute = (TonemappingColorGrading.ColorWheelGroup)attribute; property.isExpanded = true; m_NumberOfWheels = property.CountInProperty() - 1; if (m_NumberOfWheels == 0) return 0f; m_RenderSizePerWheel = Mathf.FloorToInt((EditorGUIUtility.currentViewWidth) / m_NumberOfWheels) - 30; m_RenderSizePerWheel = Mathf.Clamp(m_RenderSizePerWheel, wheelAttribute.minSizePerWheel, wheelAttribute.maxSizePerWheel); m_RenderSizePerWheel = Mathf.FloorToInt(pixelRatio * m_RenderSizePerWheel); return ColorWheel.GetColorWheelHeight(m_RenderSizePerWheel); } public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { if (m_NumberOfWheels == 0) return; var width = position.width; Rect newPosition = new Rect(position.x, position.y, width / m_NumberOfWheels, position.height); foreach (SerializedProperty prop in property) { if (prop.propertyType == SerializedPropertyType.Color) prop.colorValue = ColorWheel.DoGUI(newPosition, prop.displayName, prop.colorValue, m_RenderSizePerWheel); newPosition.x += width / m_NumberOfWheels; } } } [CustomPropertyDrawer(typeof(TonemappingColorGrading.IndentedGroup))] private class IndentedGroupDrawer : PropertyDrawer { public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { return 0f; } public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { EditorGUILayout.LabelField(label, EditorStyles.boldLabel); EditorGUI.indentLevel++; foreach (SerializedProperty prop in property) EditorGUILayout.PropertyField(prop); EditorGUI.indentLevel--; } } [CustomPropertyDrawer(typeof(TonemappingColorGrading.ChannelMixer))] private class ChannelMixerDrawer : PropertyDrawer { public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { return 0f; } public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { if (property.type != "ChannelMixerSettings") return; SerializedProperty currentChannel = property.FindPropertyRelative("currentChannel"); int intCurrentChannel = currentChannel.intValue; EditorGUILayout.LabelField(label, EditorStyles.boldLabel); EditorGUI.indentLevel++; EditorGUILayout.BeginHorizontal(); { EditorGUILayout.PrefixLabel("Channel"); if (GUILayout.Toggle(intCurrentChannel == 0, "Red", EditorStyles.miniButtonLeft)) intCurrentChannel = 0; if (GUILayout.Toggle(intCurrentChannel == 1, "Green", EditorStyles.miniButtonMid)) intCurrentChannel = 1; if (GUILayout.Toggle(intCurrentChannel == 2, "Blue", EditorStyles.miniButtonRight)) intCurrentChannel = 2; } EditorGUILayout.EndHorizontal(); SerializedProperty serializedChannel = property.FindPropertyRelative("channels").GetArrayElementAtIndex(intCurrentChannel); currentChannel.intValue = intCurrentChannel; Vector3 v = serializedChannel.vector3Value; v.x = EditorGUILayout.Slider("Red", v.x, -2f, 2f); v.y = EditorGUILayout.Slider("Green", v.y, -2f, 2f); v.z = EditorGUILayout.Slider("Blue", v.z, -2f, 2f); serializedChannel.vector3Value = v; EditorGUI.indentLevel--; } } [CustomPropertyDrawer(typeof(TonemappingColorGrading.Curve))] private class CurveDrawer : PropertyDrawer { public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { TonemappingColorGrading.Curve attribute = (TonemappingColorGrading.Curve)base.attribute; if (property.propertyType != SerializedPropertyType.AnimationCurve) { EditorGUI.LabelField(position, label.text, "Use ClampCurve with an AnimationCurve."); return; } property.animationCurveValue = EditorGUI.CurveField(position, label, property.animationCurveValue, attribute.color, new Rect(0f, 0f, 1f, 1f)); } } #endregion #region Styling private static Styles s_Styles; private class Styles { public GUIStyle thumb2D = "ColorPicker2DThumb"; public Vector2 thumb2DSize; internal Styles() { thumb2DSize = new Vector2( !Mathf.Approximately(thumb2D.fixedWidth, 0f) ? thumb2D.fixedWidth : thumb2D.padding.horizontal, !Mathf.Approximately(thumb2D.fixedHeight, 0f) ? thumb2D.fixedHeight : thumb2D.padding.vertical ); } } public static readonly Color masterCurveColor = new Color(1f, 1f, 1f, 2f); public static readonly Color redCurveColor = new Color(1f, 0f, 0f, 2f); public static readonly Color greenCurveColor = new Color(0f, 1f, 0f, 2f); public static readonly Color blueCurveColor = new Color(0f, 1f, 1f, 2f); #endregion private TonemappingColorGrading concreteTarget { get { return target as TonemappingColorGrading; } } private static float pixelRatio { get { #if !(UNITY_3 || UNITY_4 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5_3) return EditorGUIUtility.pixelsPerPoint; #else return 1f; #endif } } private bool isHistogramSupported { get { return concreteTarget.histogramComputeShader != null && ImageEffectHelper.supportsDX11 && concreteTarget.histogramShader != null && concreteTarget.histogramShader.isSupported; } } private enum HistogramMode { Red = 0, Green = 1, Blue = 2, Luminance = 3, RGB, } private HistogramMode m_HistogramMode = HistogramMode.RGB; private Rect m_HistogramRect; private Material m_HistogramMaterial; private ComputeBuffer m_HistogramBuffer; private RenderTexture m_HistogramTexture; // settings group <setting, property reference> private Dictionary<FieldInfo, List<SerializedProperty>> m_GroupFields = new Dictionary<FieldInfo, List<SerializedProperty>>(); private void PopulateMap(FieldInfo group) { var searchPath = group.Name + "."; foreach (var setting in group.FieldType.GetFields(BindingFlags.Instance | BindingFlags.Public)) { List<SerializedProperty> settingsGroup; if (!m_GroupFields.TryGetValue(group, out settingsGroup)) { settingsGroup = new List<SerializedProperty>(); m_GroupFields[group] = settingsGroup; } var property = serializedObject.FindProperty(searchPath + setting.Name); if (property != null) settingsGroup.Add(property); } } private void OnEnable() { var settingsGroups = typeof(TonemappingColorGrading).GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).Where(x => x.GetCustomAttributes(typeof(TonemappingColorGrading.SettingsGroup), false).Any()); foreach (var settingGroup in settingsGroups) PopulateMap(settingGroup); concreteTarget.onFrameEndEditorOnly = OnFrameEnd; } private void OnDisable() { concreteTarget.onFrameEndEditorOnly = null; if (m_HistogramMaterial != null) DestroyImmediate(m_HistogramMaterial); if (m_HistogramTexture != null) DestroyImmediate(m_HistogramTexture); if (m_HistogramBuffer != null) m_HistogramBuffer.Release(); } private void SetLUTImportSettings(TextureImporter importer) { #if UNITY_5_5_OR_NEWER importer.textureType = TextureImporterType.Default; importer.sRGBTexture = false; importer.textureCompression = TextureImporterCompression.Uncompressed; #else importer.textureType = TextureImporterType.Advanced; importer.linearTexture = true; importer.textureFormat = TextureImporterFormat.RGB24; #endif importer.anisoLevel = 0; importer.mipmapEnabled = false; importer.SaveAndReimport(); } private void DrawFields() { foreach (var group in m_GroupFields) { var enabledField = group.Value.FirstOrDefault(x => x.propertyPath == group.Key.Name + ".enabled"); var groupProperty = serializedObject.FindProperty(group.Key.Name); GUILayout.Space(5); bool display = EditorGUIHelper.Header(groupProperty, enabledField); if (!display) continue; GUILayout.BeginHorizontal(); { GUILayout.Space(10); GUILayout.BeginVertical(); { GUILayout.Space(3); foreach (var field in group.Value.Where(x => x.propertyPath != group.Key.Name + ".enabled")) { // Special case for the tonemapping curve field if (group.Key.FieldType == typeof(TonemappingColorGrading.TonemappingSettings) && field.propertyType == SerializedPropertyType.AnimationCurve && concreteTarget.tonemapping.tonemapper != TonemappingColorGrading.Tonemapper.Curve) continue; // Special case for the neutral tonemapper bool neutralParam = field.name.StartsWith("neutral"); if (group.Key.FieldType == typeof(TonemappingColorGrading.TonemappingSettings) && concreteTarget.tonemapping.tonemapper != TonemappingColorGrading.Tonemapper.Neutral && neutralParam) continue; if (neutralParam) EditorGUILayout.PropertyField(field, new GUIContent(ObjectNames.NicifyVariableName(field.name.Substring(7)))); else EditorGUILayout.PropertyField(field); } // Bake button if (group.Key.FieldType == typeof(TonemappingColorGrading.ColorGradingSettings)) { EditorGUI.BeginDisabledGroup(!enabledField.boolValue); if (GUILayout.Button("Export LUT as PNG", EditorStyles.miniButton)) { string path = EditorUtility.SaveFilePanelInProject("Export LUT as PNG", "LUT.png", "png", "Please enter a file name to save the LUT texture to"); if (!string.IsNullOrEmpty(path)) { Texture2D lut = concreteTarget.BakeLUT(); if (!concreteTarget.isGammaColorSpace) { var pixels = lut.GetPixels(); for (int i = 0; i < pixels.Length; i++) pixels[i] = pixels[i].linear; lut.SetPixels(pixels); lut.Apply(); } byte[] bytes = lut.EncodeToPNG(); System.IO.File.WriteAllBytes(path, bytes); DestroyImmediate(lut); AssetDatabase.Refresh(); TextureImporter importer = (TextureImporter)AssetImporter.GetAtPath(path); SetLUTImportSettings(importer); } } EditorGUI.EndDisabledGroup(); } } GUILayout.EndVertical(); } GUILayout.EndHorizontal(); } } public override void OnInspectorGUI() { if (s_Styles == null) s_Styles = new Styles(); serializedObject.Update(); GUILayout.Label("All following effects will use LDR color buffers.", EditorStyles.miniBoldLabel); if (concreteTarget.tonemapping.enabled) { Camera camera = concreteTarget.GetComponent<Camera>(); if (camera != null && !camera.allowHDR) EditorGUILayout.HelpBox("The camera is not HDR enabled. This will likely break the tonemapper.", MessageType.Warning); else if (!concreteTarget.validRenderTextureFormat) EditorGUILayout.HelpBox("The input to tonemapper is not in HDR. Make sure that all effects prior to this are executed in HDR.", MessageType.Warning); } if (concreteTarget.lut.enabled && concreteTarget.lut.texture != null) { if (!concreteTarget.validUserLutSize) { EditorGUILayout.HelpBox("Invalid LUT size. Should be \"height = sqrt(width)\" (e.g. 256x16).", MessageType.Error); } else { // Checks import settings on the lut, offers to fix them if invalid TextureImporter importer = (TextureImporter)AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(concreteTarget.lut.texture)); #if UNITY_5_5_OR_NEWER bool valid = importer.anisoLevel == 0 && importer.mipmapEnabled == false && importer.sRGBTexture == false && (importer.textureCompression == TextureImporterCompression.Uncompressed); #else bool valid = importer.anisoLevel == 0 && importer.mipmapEnabled == false && importer.linearTexture == true && (importer.textureFormat == TextureImporterFormat.RGB24 || importer.textureFormat == TextureImporterFormat.AutomaticTruecolor); #endif if (!valid) { EditorGUILayout.HelpBox("Invalid LUT import settings.", MessageType.Warning); GUILayout.Space(-32); EditorGUILayout.BeginHorizontal(); { GUILayout.FlexibleSpace(); if (GUILayout.Button("Fix", GUILayout.Width(60))) { SetLUTImportSettings(importer); AssetDatabase.Refresh(); } GUILayout.Space(8); } EditorGUILayout.EndHorizontal(); GUILayout.Space(11); } } } DrawFields(); serializedObject.ApplyModifiedProperties(); } private static readonly GUIContent k_HistogramTitle = new GUIContent("Histogram"); public override GUIContent GetPreviewTitle() { return k_HistogramTitle; } public override bool HasPreviewGUI() { return isHistogramSupported && targets.Length == 1 && concreteTarget != null && concreteTarget.enabled; } public override void OnPreviewGUI(Rect r, GUIStyle background) { serializedObject.Update(); if (Event.current.type == EventType.Repaint) { // If m_HistogramRect isn't set the preview was just opened so refresh the render to get the histogram data if (m_HistogramRect.width == 0 && m_HistogramRect.height == 0) InternalEditorUtility.RepaintAllViews(); // Sizing float width = Mathf.Min(512f, r.width); float height = Mathf.Min(128f, r.height); m_HistogramRect = new Rect( Mathf.Floor(r.x + r.width / 2f - width / 2f), Mathf.Floor(r.y + r.height / 2f - height / 2f), width, height ); if (m_HistogramTexture != null) GUI.DrawTexture(m_HistogramRect, m_HistogramTexture); } // Toolbar GUILayout.BeginHorizontal(); EditorGUI.BeginChangeCheck(); { concreteTarget.histogramRefreshOnPlay = GUILayout.Toggle(concreteTarget.histogramRefreshOnPlay, new GUIContent("Refresh on Play", "Keep refreshing the histogram in play mode; this may impact performances."), EditorStyles.miniButton); GUILayout.FlexibleSpace(); m_HistogramMode = (HistogramMode)EditorGUILayout.EnumPopup(m_HistogramMode); } GUILayout.EndHorizontal(); serializedObject.ApplyModifiedProperties(); if (EditorGUI.EndChangeCheck()) InternalEditorUtility.RepaintAllViews(); } private void OnFrameEnd(RenderTexture source) { if (Application.isPlaying && !concreteTarget.histogramRefreshOnPlay) return; if (Mathf.Approximately(m_HistogramRect.width, 0) || Mathf.Approximately(m_HistogramRect.height, 0) || !isHistogramSupported) return; // No need to process the full frame to get an histogram, resize the input to a max-size of 512 int rw = Mathf.Min(Mathf.Max(source.width, source.height), 512); RenderTexture rt = RenderTexture.GetTemporary(rw, rw, 0); Graphics.Blit(source, rt); UpdateHistogram(rt, m_HistogramRect, m_HistogramMode); Repaint(); RenderTexture.ReleaseTemporary(rt); RenderTexture.active = null; } private static readonly int[] k_EmptyBuffer = new int[256 << 2]; void UpdateHistogram(RenderTexture source, Rect rect, HistogramMode mode) { if (m_HistogramMaterial == null) m_HistogramMaterial = ImageEffectHelper.CheckShaderAndCreateMaterial(concreteTarget.histogramShader); if (m_HistogramBuffer == null) m_HistogramBuffer = new ComputeBuffer(256, sizeof(uint) << 2); m_HistogramBuffer.SetData(k_EmptyBuffer); ComputeShader cs = concreteTarget.histogramComputeShader; int kernel = cs.FindKernel("KHistogramGather"); cs.SetBuffer(kernel, "_Histogram", m_HistogramBuffer); cs.SetTexture(kernel, "_Source", source); int[] channels = null; switch (mode) { case HistogramMode.Luminance: channels = new[] { 0, 0, 0, 1 }; break; case HistogramMode.RGB: channels = new[] { 1, 1, 1, 0 }; break; case HistogramMode.Red: channels = new[] { 1, 0, 0, 0 }; break; case HistogramMode.Green: channels = new[] { 0, 1, 0, 0 }; break; case HistogramMode.Blue: channels = new[] { 0, 0, 1, 0 }; break; } cs.SetInts("_Channels", channels); cs.SetInt("_IsLinear", concreteTarget.isGammaColorSpace ? 0 : 1); cs.Dispatch(kernel, Mathf.CeilToInt(source.width / 32f), Mathf.CeilToInt(source.height / 32f), 1); kernel = cs.FindKernel("KHistogramScale"); cs.SetBuffer(kernel, "_Histogram", m_HistogramBuffer); cs.SetFloat("_Height", rect.height); cs.Dispatch(kernel, 1, 1, 1); if (m_HistogramTexture == null) { DestroyImmediate(m_HistogramTexture); m_HistogramTexture = new RenderTexture((int)rect.width, (int)rect.height, 0, RenderTextureFormat.ARGB32); m_HistogramTexture.hideFlags = HideFlags.HideAndDontSave; } m_HistogramMaterial.SetBuffer("_Histogram", m_HistogramBuffer); m_HistogramMaterial.SetVector("_Size", new Vector2(m_HistogramTexture.width, m_HistogramTexture.height)); m_HistogramMaterial.SetColor("_ColorR", redCurveColor); m_HistogramMaterial.SetColor("_ColorG", greenCurveColor); m_HistogramMaterial.SetColor("_ColorB", blueCurveColor); m_HistogramMaterial.SetColor("_ColorL", masterCurveColor); m_HistogramMaterial.SetInt("_Channel", (int)mode); Graphics.Blit(m_HistogramTexture, m_HistogramTexture, m_HistogramMaterial, (mode == HistogramMode.RGB) ? 1 : 0); } public static class ColorWheel { // Constants private const float PI_2 = Mathf.PI / 2f; private const float PI2 = Mathf.PI * 2f; // hue Wheel private static Texture2D s_WheelTexture; private static float s_LastDiameter; private static GUIStyle s_CenteredStyle; public static Color DoGUI(Rect area, string title, Color color, float diameter) { var labelrect = area; labelrect.height = EditorGUIUtility.singleLineHeight; if (s_CenteredStyle == null) { s_CenteredStyle = new GUIStyle(GUI.skin.GetStyle("Label")) { alignment = TextAnchor.UpperCenter }; } GUI.Label(labelrect, title, s_CenteredStyle); // Figure out the wheel draw area var wheelDrawArea = area; wheelDrawArea.y += EditorGUIUtility.singleLineHeight; wheelDrawArea.height = diameter; if (wheelDrawArea.width > wheelDrawArea.height) { wheelDrawArea.x += (wheelDrawArea.width - wheelDrawArea.height) / 2.0f; wheelDrawArea.width = area.height; } wheelDrawArea.width = wheelDrawArea.height; var radius = diameter / 2.0f; Vector3 hsv; Color.RGBToHSV(color, out hsv.x, out hsv.y, out hsv.z); // Retina/HDPI screens handling wheelDrawArea.width /= pixelRatio; wheelDrawArea.height /= pixelRatio; float scaledRadius = radius / pixelRatio; if (Event.current.type == EventType.Repaint) { if (!Mathf.Approximately(diameter, s_LastDiameter)) { s_LastDiameter = diameter; UpdateHueWheel((int)diameter); } // Wheel GUI.DrawTexture(wheelDrawArea, s_WheelTexture); // Thumb Vector2 thumbPos = Vector2.zero; float theta = hsv.x * PI2; float len = hsv.y * scaledRadius; thumbPos.x = Mathf.Cos(theta + PI_2); thumbPos.y = Mathf.Sin(theta - PI_2); thumbPos *= len; Vector2 thumbSize = s_Styles.thumb2DSize; Color oldColor = GUI.color; GUI.color = Color.black; Vector2 thumbSizeH = thumbSize / 2f; Handles.color = Color.white; Handles.DrawAAPolyLine(new Vector2(wheelDrawArea.x + scaledRadius + thumbSizeH.x, wheelDrawArea.y + scaledRadius + thumbSizeH.y), new Vector2(wheelDrawArea.x + scaledRadius + thumbPos.x, wheelDrawArea.y + scaledRadius + thumbPos.y)); s_Styles.thumb2D.Draw(new Rect(wheelDrawArea.x + scaledRadius + thumbPos.x - thumbSizeH.x, wheelDrawArea.y + scaledRadius + thumbPos.y - thumbSizeH.y, thumbSize.x, thumbSize.y), false, false, false, false); GUI.color = oldColor; } hsv = GetInput(wheelDrawArea, hsv, scaledRadius); var sliderDrawArea = wheelDrawArea; sliderDrawArea.y = sliderDrawArea.yMax; sliderDrawArea.height = EditorGUIUtility.singleLineHeight; hsv.y = GUI.HorizontalSlider(sliderDrawArea, hsv.y, 1e-04f, 1f); color = Color.HSVToRGB(hsv.x, hsv.y, hsv.z); return color; } private static readonly int k_ThumbHash = "colorWheelThumb".GetHashCode(); private static Vector3 GetInput(Rect bounds, Vector3 hsv, float radius) { Event e = Event.current; var id = GUIUtility.GetControlID(k_ThumbHash, FocusType.Passive, bounds); Vector2 mousePos = e.mousePosition; Vector2 relativePos = mousePos - new Vector2(bounds.x, bounds.y); if (e.type == EventType.MouseDown && e.button == 0 && GUIUtility.hotControl == 0) { if (bounds.Contains(mousePos)) { Vector2 center = new Vector2(bounds.x + radius, bounds.y + radius); float dist = Vector2.Distance(center, mousePos); if (dist <= radius) { e.Use(); GetWheelHueSaturation(relativePos.x, relativePos.y, radius, out hsv.x, out hsv.y); GUIUtility.hotControl = id; } } } else if (e.type == EventType.MouseDrag && e.button == 0 && GUIUtility.hotControl == id) { Vector2 center = new Vector2(bounds.x + radius, bounds.y + radius); float dist = Vector2.Distance(center, mousePos); if (dist <= radius) { e.Use(); GetWheelHueSaturation(relativePos.x, relativePos.y, radius, out hsv.x, out hsv.y); } } else if (e.type == EventType.MouseUp && e.button == 0 && GUIUtility.hotControl == id) { e.Use(); GUIUtility.hotControl = 0; } return hsv; } private static void GetWheelHueSaturation(float x, float y, float radius, out float hue, out float saturation) { float dx = (x - radius) / radius; float dy = (y - radius) / radius; float d = Mathf.Sqrt(dx * dx + dy * dy); hue = Mathf.Atan2(dx, -dy); hue = 1f - ((hue > 0) ? hue : PI2 + hue) / PI2; saturation = Mathf.Clamp01(d); } private static void UpdateHueWheel(int diameter) { CleanTexture(s_WheelTexture); s_WheelTexture = MakeTexture(diameter); var radius = diameter / 2.0f; Color[] pixels = s_WheelTexture.GetPixels(); for (int y = 0; y < diameter; y++) { for (int x = 0; x < diameter; x++) { int index = y * diameter + x; float dx = (x - radius) / radius; float dy = (y - radius) / radius; float d = Mathf.Sqrt(dx * dx + dy * dy); // Out of the wheel, early exit if (d >= 1f) { pixels[index] = new Color(0f, 0f, 0f, 0f); continue; } // red (0) on top, counter-clockwise (industry standard) float saturation = d; float hue = Mathf.Atan2(dx, dy); hue = 1f - ((hue > 0) ? hue : PI2 + hue) / PI2; Color color = Color.HSVToRGB(hue, saturation, 1f); // Quick & dirty antialiasing color.a = (saturation > 0.99) ? (1f - saturation) * 100f : 1f; pixels[index] = color; } } s_WheelTexture.SetPixels(pixels); s_WheelTexture.Apply(); } private static Texture2D MakeTexture(int dimension) { return new Texture2D(dimension, dimension, TextureFormat.ARGB32, false, true) { filterMode = FilterMode.Point, wrapMode = TextureWrapMode.Clamp, hideFlags = HideFlags.HideAndDontSave, alphaIsTransparency = true }; } private static void CleanTexture(Texture2D texture) { if (texture != null) DestroyImmediate(texture); } public static float GetColorWheelHeight(int renderSizePerWheel) { // wheel height + title label + alpha slider return renderSizePerWheel + 2 * EditorGUIUtility.singleLineHeight; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace DapWebApi.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter; using Microsoft.Protocols.TestSuites.FileSharing.Common.TestSuite; using Microsoft.Protocols.TestTools; using Microsoft.Protocols.TestTools.StackSdk; using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb2; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; namespace Microsoft.Protocols.TestSuites.FileSharing.SMB2.TestSuite { [TestClass] public class ValidateNegotiateInfo : SMB2TestBase { #region Variables private Smb2FunctionalClient client; private uint status; #endregion #region Test Initialize and Cleanup [ClassInitialize()] public static void ClassInitialize(TestContext testContext) { TestClassBase.Initialize(testContext); } [ClassCleanup()] public static void ClassCleanup() { TestClassBase.Cleanup(); } #endregion #region Test Case Initialize and Clean up protected override void TestInitialize() { base.TestInitialize(); client = new Smb2FunctionalClient(TestConfig.Timeout, TestConfig, BaseTestSite); client.ConnectToServer(TestConfig.UnderlyingTransport, TestConfig.SutComputerName, TestConfig.SutIPAddress); } protected override void TestCleanup() { if (client != null) { try { client.Disconnect(); } catch (Exception ex) { BaseTestSite.Log.Add( LogEntryKind.Debug, "Unexpected exception when disconnect client: {0}", ex.ToString()); } } base.TestCleanup(); } #endregion #region Test Case [TestMethod] [TestCategory(TestCategories.Bvt)] [TestCategory(TestCategories.Smb30)] [TestCategory(TestCategories.FsctlValidateNegotiateInfo)] [Description("Test whether server can handle IOCTL FSCTL_VALIDATE_NEGOTIATE_INFO.")] public void BVT_ValidateNegotiateInfo() { TestValidateNegotiateInfo(client, ValidateNegotiateInfoRequestType.None); } [TestMethod] [TestCategory(TestCategories.Smb30)] [TestCategory(TestCategories.FsctlValidateNegotiateInfo)] [TestCategory(TestCategories.UnexpectedFields)] [Description("Test whether server terminates the transport connection and free the connection object " + "if no dialect is matched when determine the greatest common dialect between the dialects it implements and the dialects array of VALIDATE_NEGOTIATE_INFO request.")] public void ValidateNegotiateInfo_Negative_InvalidDialects_NoCommonDialect() { TestValidateNegotiateInfo(client, ValidateNegotiateInfoRequestType.InvalidDialects, new DialectRevision[] { DialectRevision.Smb2Unknown }); } [TestMethod] [TestCategory(TestCategories.Smb30)] [TestCategory(TestCategories.FsctlValidateNegotiateInfo)] [TestCategory(TestCategories.UnexpectedFields)] [Description("Test whether the server terminates the transport connection and free the Connection object, " + "if the value is not equal to Connection.Dialect when determine the greatest common dialect between the dialects it implements and the Dialects array of the VALIDATE_NEGOTIATE_INFO request.")] public void ValidateNegotiateInfo_Negative_InvalidDialects_CommonDialectNotExpected() { TestValidateNegotiateInfo(client, ValidateNegotiateInfoRequestType.InvalidDialects, new DialectRevision[] { DialectRevision.Smb21 }); } [TestMethod] [TestCategory(TestCategories.Smb30)] [TestCategory(TestCategories.FsctlValidateNegotiateInfo)] [TestCategory(TestCategories.InvalidIdentifier)] [Description("Test whether the server terminates the transport connection and free the Connection object, " + "if the Guid received in the VALIDATE_NEGOTIATE_INFO request structure is not equal to the Connection.ClientGuid.")] public void ValidateNegotiateInfo_Negative_InvalidGuid() { TestValidateNegotiateInfo(client, ValidateNegotiateInfoRequestType.InvalidGuid); } [TestMethod] [TestCategory(TestCategories.Smb30)] [TestCategory(TestCategories.FsctlValidateNegotiateInfo)] [TestCategory(TestCategories.UnexpectedFields)] [Description("Test whether the server terminates the transport connection and free the Connection object, " + "if the SecurityMode received in the VALIDATE_NEGOTIATE_INFO request structure is not equal to Connection.ClientSecurityMode.")] public void ValidateNegotiateInfo_Negative_InvalidSecurityMode() { TestValidateNegotiateInfo(client, ValidateNegotiateInfoRequestType.InvalidSecurityMode); } [TestMethod] [TestCategory(TestCategories.Smb30)] [TestCategory(TestCategories.FsctlValidateNegotiateInfo)] [TestCategory(TestCategories.UnexpectedFields)] [Description("Test whether the server terminates the transport connection and free the Connection object, " + "if Connection.ClientCapabilities is not equal to the Capabilities received in the VALIDATE_NEGOTIATE_INFO request structure.")] public void ValidateNegotiateInfo_Negative_InvalidCapabilities() { TestValidateNegotiateInfo(client, ValidateNegotiateInfoRequestType.InvalidCapabilities); } [TestMethod] [TestCategory(TestCategories.Smb30)] [TestCategory(TestCategories.FsctlValidateNegotiateInfo)] [TestCategory(TestCategories.OutOfBoundary)] [Description("Test whether the server terminates the transport connection and free the Connection object, " + "if MaxOutputResponse in the IOCTL request is less than the size of a VALIDATE_NEGOTIATE_INFO Response.")] public void ValidateNegotiateInfo_Negative_InvalidMaxOutputResponse() { TestValidateNegotiateInfo(client, ValidateNegotiateInfoRequestType.InvalidMaxOutputResponse); } #endregion #region Common Methods // section 3.3.5.15: The server SHOULD<290> fail the request with STATUS_NOT_SUPPORTED when an FSCTL is not allowed on the server private void HandleValidateNegotiateInfoNotSupported() { if (testConfig.Platform != Platform.NonWindows) { BaseTestSite.Assert.AreEqual(Smb2Status.STATUS_NOT_SUPPORTED, status, "The server should fail the request with STATUS_NOT_SUPPORTED when an FSCTL is not allowed on the server"); } else { BaseTestSite.Assert.AreNotEqual(Smb2Status.STATUS_SUCCESS, status, "FSCTL_VALIDATE_NEGOTIATE_INFO is not supported in Server, so server should not return STATUS_SUCCESS"); } } private void TestValidateNegotiateInfo(Smb2FunctionalClient client, ValidateNegotiateInfoRequestType requestType, DialectRevision[] invalidDialects = null) { #region Check Applicability TestConfig.CheckDialect(DialectRevision.Smb30); TestConfig.CheckIOCTL(CtlCode_Values.FSCTL_VALIDATE_NEGOTIATE_INFO); TestConfig.CheckDialectIOCTLCompatibility(CtlCode_Values.FSCTL_VALIDATE_NEGOTIATE_INFO); // Server will terminate connection if Validate Negotiate Info Request is not signed. TestConfig.CheckSigning(); #endregion BaseTestSite.Log.Add(LogEntryKind.TestStep, "Start a client by sending the following requests: NEGOTIATE; SESSION_SETUP; TREE_CONNECT"); Guid clientGuid = Guid.NewGuid(); DialectRevision[] requestDialects = TestConfig.RequestDialects; Capabilities_Values clientCapabilities = Capabilities_Values.GLOBAL_CAP_DFS | Capabilities_Values.GLOBAL_CAP_DIRECTORY_LEASING | Capabilities_Values.GLOBAL_CAP_LARGE_MTU | Capabilities_Values.GLOBAL_CAP_LEASING | Capabilities_Values.GLOBAL_CAP_MULTI_CHANNEL | Capabilities_Values.GLOBAL_CAP_PERSISTENT_HANDLES; SecurityMode_Values clientSecurityMode = SecurityMode_Values.NEGOTIATE_SIGNING_ENABLED; NEGOTIATE_Response? negotiateResponse = null; status = client.Negotiate( requestDialects, TestConfig.IsSMB1NegotiateEnabled, clientSecurityMode, clientCapabilities, clientGuid, (Packet_Header header, NEGOTIATE_Response response) => { BaseTestSite.Assert.AreEqual( Smb2Status.STATUS_SUCCESS, header.Status, "Negotiation should succeed, actually server returns {0}.", Smb2Status.GetStatusCode(header.Status)); TestConfig.CheckNegotiateDialect(DialectRevision.Smb30, response); negotiateResponse = response; }); status = client.SessionSetup( TestConfig.DefaultSecurityPackage, TestConfig.SutComputerName, TestConfig.AccountCredential, TestConfig.UseServerGssToken); uint treeId; string ipcPath = Smb2Utility.GetIPCPath(TestConfig.SutComputerName); status = client.TreeConnect(ipcPath, out treeId); VALIDATE_NEGOTIATE_INFO_Request validateNegotiateInfoReq; switch (requestType) { case ValidateNegotiateInfoRequestType.None: case ValidateNegotiateInfoRequestType.InvalidMaxOutputResponse: validateNegotiateInfoReq.Guid = clientGuid; validateNegotiateInfoReq.Capabilities = clientCapabilities; validateNegotiateInfoReq.SecurityMode = clientSecurityMode; validateNegotiateInfoReq.DialectCount = (ushort)requestDialects.Length; validateNegotiateInfoReq.Dialects = requestDialects; break; case ValidateNegotiateInfoRequestType.InvalidDialects: validateNegotiateInfoReq.Guid = clientGuid; validateNegotiateInfoReq.Capabilities = clientCapabilities; validateNegotiateInfoReq.SecurityMode = clientSecurityMode; validateNegotiateInfoReq.DialectCount = (ushort)invalidDialects.Length; validateNegotiateInfoReq.Dialects = invalidDialects; break; case ValidateNegotiateInfoRequestType.InvalidGuid: validateNegotiateInfoReq.Guid = Guid.NewGuid(); validateNegotiateInfoReq.Capabilities = clientCapabilities; validateNegotiateInfoReq.SecurityMode = clientSecurityMode; validateNegotiateInfoReq.DialectCount = (ushort)requestDialects.Length; validateNegotiateInfoReq.Dialects = requestDialects; break; case ValidateNegotiateInfoRequestType.InvalidSecurityMode: validateNegotiateInfoReq.Guid = clientGuid; validateNegotiateInfoReq.Capabilities = clientCapabilities; validateNegotiateInfoReq.SecurityMode = SecurityMode_Values.NONE; validateNegotiateInfoReq.DialectCount = (ushort)requestDialects.Length; validateNegotiateInfoReq.Dialects = requestDialects; break; case ValidateNegotiateInfoRequestType.InvalidCapabilities: validateNegotiateInfoReq.Guid = clientGuid; validateNegotiateInfoReq.Capabilities = Capabilities_Values.NONE; validateNegotiateInfoReq.SecurityMode = clientSecurityMode; validateNegotiateInfoReq.DialectCount = (ushort)requestDialects.Length; validateNegotiateInfoReq.Dialects = requestDialects; break; default: throw new InvalidOperationException("Unexpected ValidateNegotiateInfo request type " + requestType); } byte[] inputBuffer = TypeMarshal.ToBytes<VALIDATE_NEGOTIATE_INFO_Request>(validateNegotiateInfoReq); byte[] outputBuffer; VALIDATE_NEGOTIATE_INFO_Response validateNegotiateInfoResp; BaseTestSite.Log.Add( LogEntryKind.TestStep, "Attempt to validate negotiate info with info Guid: {0}, Capabilities: {1}, SecurityMode: {2}, DialectCount: {3}, Dialects: {4}", validateNegotiateInfoReq.Guid, validateNegotiateInfoReq.Capabilities, validateNegotiateInfoReq.SecurityMode, validateNegotiateInfoReq.DialectCount, Smb2Utility.GetArrayString(validateNegotiateInfoReq.Dialects)); if (requestType == ValidateNegotiateInfoRequestType.None) { status = client.ValidateNegotiateInfo(treeId, inputBuffer, out outputBuffer, checker: (header, response) => { }); BaseTestSite.Assert.AreEqual(Smb2Status.STATUS_SUCCESS, status, "ValidateNegotiateInfo should succeed "); validateNegotiateInfoResp = TypeMarshal.ToStruct<VALIDATE_NEGOTIATE_INFO_Response>(outputBuffer); BaseTestSite.Log.Add( LogEntryKind.Debug, "Capabilities returned in ValidateNegotiateInfo response: {0}", validateNegotiateInfoResp.Capabilities); BaseTestSite.Assert.AreEqual( (Capabilities_Values)negotiateResponse.Value.Capabilities, validateNegotiateInfoResp.Capabilities, "Capabilities returned in ValidateNegotiateInfo response should be equal to server capabilities in original Negotiate response"); BaseTestSite.Log.Add( LogEntryKind.Debug, "Guid returned in ValidateNegotiateInfo response: {0}", validateNegotiateInfoResp.Guid); BaseTestSite.Assert.AreEqual( negotiateResponse.Value.ServerGuid, validateNegotiateInfoResp.Guid, "ServerGuid returned in ValidateNegotiateInfo response should be equal to server ServerGuid in original Negotiate response"); BaseTestSite.Log.Add( LogEntryKind.Debug, "SecurityMode returned in ValidateNegotiateInfo response: {0}", validateNegotiateInfoResp.SecurityMode); BaseTestSite.Assert.AreEqual( (SecurityMode_Values)negotiateResponse.Value.SecurityMode, validateNegotiateInfoResp.SecurityMode, "SecurityMode returned in ValidateNegotiateInfo response should be equal to server SecurityMode in original Negotiate response"); BaseTestSite.Log.Add( LogEntryKind.Debug, "Dialect returned in ValidateNegotiateInfo response: {0}", validateNegotiateInfoResp.Dialect); BaseTestSite.Assert.AreEqual( negotiateResponse.Value.DialectRevision, validateNegotiateInfoResp.Dialect, "DialectRevision returned in ValidateNegotiateInfo response should be equal to server DialectRevision in original Negotiate response"); client.TreeDisconnect(treeId); client.LogOff(); return; } uint maxOutputResponse = (requestType == ValidateNegotiateInfoRequestType.InvalidMaxOutputResponse) ? (uint)0: 64 * 1024; try { client.ValidateNegotiateInfo(treeId, inputBuffer, out outputBuffer, maxOutputResponse, (header, response) => { }); client.TreeDisconnect(treeId); client.LogOff(); return; } catch { } string errCondition = requestType == ValidateNegotiateInfoRequestType.InvalidMaxOutputResponse ? "MaxOutputResponse in the request is less than the size of a VALIDATE_NEGOTIATE_INFO Response" : "there's invalid info in the request"; BaseTestSite.Assert.IsTrue(client.Smb2Client.IsServerDisconnected, "Transport connection should be terminated when {0}", errCondition); } [TestMethod] [TestCategory(TestCategories.Smb311)] [TestCategory(TestCategories.FsctlValidateNegotiateInfo)] [TestCategory(TestCategories.Compatibility)] [Description("Test whether the server can terminate the transport connection when receiving a VALIDATE_NEGOTIATE_INFO request with dialect 3.1.1.")] public void ValidateNegotiateInfo_Negative_SMB311() { #region Check Applicability TestConfig.CheckDialect(DialectRevision.Smb311); // Server will terminate connection if Validate Negotiate Info Request is not signed. TestConfig.CheckSigning(); #endregion Smb2FunctionalClient testClient = new Smb2FunctionalClient(testConfig.Timeout, testConfig, this.Site); testClient.ConnectToServer(testConfig.UnderlyingTransport, testConfig.SutComputerName, testConfig.SutIPAddress); BaseTestSite.Log.Add(LogEntryKind.TestStep, "Start a client by sending the following requests: NEGOTIATE; SESSION_SETUP; TREE_CONNECT"); Guid clientGuid = Guid.NewGuid(); DialectRevision[] requestDialects = Smb2Utility.GetDialects(DialectRevision.Smb311); Capabilities_Values clientCapabilities = Capabilities_Values.GLOBAL_CAP_DFS | Capabilities_Values.GLOBAL_CAP_DIRECTORY_LEASING | Capabilities_Values.GLOBAL_CAP_LARGE_MTU | Capabilities_Values.GLOBAL_CAP_LEASING | Capabilities_Values.GLOBAL_CAP_MULTI_CHANNEL | Capabilities_Values.GLOBAL_CAP_PERSISTENT_HANDLES; SecurityMode_Values clientSecurityMode = SecurityMode_Values.NEGOTIATE_SIGNING_ENABLED; NEGOTIATE_Response? negotiateResponse = null; status = client.Negotiate( requestDialects, TestConfig.IsSMB1NegotiateEnabled, clientSecurityMode, clientCapabilities, clientGuid, (Packet_Header header, NEGOTIATE_Response response) => { BaseTestSite.Assert.AreEqual( Smb2Status.STATUS_SUCCESS, header.Status, "Negotiation should succeed, actually server returns {0}.", Smb2Status.GetStatusCode(header.Status)); TestConfig.CheckNegotiateDialect(DialectRevision.Smb311, response); negotiateResponse = response; }); status = client.SessionSetup( TestConfig.DefaultSecurityPackage, TestConfig.SutComputerName, TestConfig.AccountCredential, TestConfig.UseServerGssToken); uint treeId; string ipcPath = Smb2Utility.GetIPCPath(TestConfig.SutComputerName); status = client.TreeConnect(ipcPath, out treeId); VALIDATE_NEGOTIATE_INFO_Request validateNegotiateInfoReq = new VALIDATE_NEGOTIATE_INFO_Request(); validateNegotiateInfoReq.Guid = clientGuid; validateNegotiateInfoReq.Capabilities = clientCapabilities; validateNegotiateInfoReq.SecurityMode = SecurityMode_Values.NONE; validateNegotiateInfoReq.DialectCount = (ushort)requestDialects.Length; validateNegotiateInfoReq.Dialects = requestDialects; byte[] inputBuffer = TypeMarshal.ToBytes<VALIDATE_NEGOTIATE_INFO_Request>(validateNegotiateInfoReq); byte[] outputBuffer; BaseTestSite.Log.Add( LogEntryKind.TestStep, "Attempt to validate negotiate info with info Guid: {0}, Capabilities: {1}, SecurityMode: {2}, DialectCount: {3}, Dialects: {4}", validateNegotiateInfoReq.Guid, validateNegotiateInfoReq.Capabilities, validateNegotiateInfoReq.SecurityMode, validateNegotiateInfoReq.DialectCount, Smb2Utility.GetArrayString(validateNegotiateInfoReq.Dialects)); try { BaseTestSite.Log.Add( LogEntryKind.TestStep, "Attempt to send a request with an SMB2 header with a Command value equal to SMB2 IOCTL, and a CtlCode of FSCTL_VALIDATE_NEGOTIATE_INFO."); client.ValidateNegotiateInfo( treeId, inputBuffer, out outputBuffer ); } catch { } BaseTestSite.Assert.IsTrue(client.Smb2Client.IsServerDisconnected, "Transport connection should be terminated when Connection.Dialect is \"3.1.1\"."); } #endregion } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Collections.Specialized; using System.Text; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Components_PagingLink : Vevo.WebUI.International.BaseLanguageUserControl { private int _limitPage = 10; private void DeterminePageRange( out int low, out int high ) { low = CurrentPage - _limitPage / 2; if (low < 1) low = 1; // Assuming high value according to low value high = low + _limitPage - 1; if (high > NumberOfPages) high = NumberOfPages; // Need to re-adjust low value if the current page is around the upper bound value if (high - low + 1 < _limitPage) { low = high - _limitPage + 1; if (low < 1) low = 1; } } private string CreateUrlWithPageNumber( int page ) { Uri url = new Uri( Request.Url.Scheme + "://" + Request.Url.Host + Request.RawUrl ); StringBuilder sb = new StringBuilder(); sb.Append( url.AbsolutePath ); sb.Append( '?' ); NameValueCollection query = Request.QueryString; string key; for (int i = 0; i < query.Count; i++) { if (query.AllKeys[i] != null && query.AllKeys[i].ToString().ToLower() != "categoryname" && query.AllKeys[i].ToString().ToLower() != "categoryid" && query.AllKeys[i].ToString().ToLower() != "productname") { key = query.AllKeys[i].ToString(); if (key.ToLower() != "page") sb.AppendFormat( "{0}={1}&", key, query[i] ); } } sb.AppendFormat( "Page={0}", page ); return sb.ToString(); } private void AddText( string text ) { Literal space = new Literal(); space.Text = text; uxPanel.Controls.Add( space ); } private void AddSpace() { AddText( "&nbsp;" ); } private void AddDots() { AddText( ".." ); } private void AddOnePageLink( int pageNumber ) { HyperLink link = new HyperLink(); link.Text = pageNumber.ToString(); link.NavigateUrl = CreateUrlWithPageNumber( pageNumber ); uxPanel.Controls.Add( link ); } private void AddLinkPrevious() { HyperLink previous = new HyperLink(); previous.Text = "[$Previous]"; if (CurrentPage > 1) { previous.Enabled = true; previous.NavigateUrl = CreateUrlWithPageNumber( CurrentPage - 1 ); } else { previous.Enabled = false; } uxPanel.Controls.Add( previous ); } private void AddLinkNext() { HyperLink next = new HyperLink(); next.Text = "[$Next]"; if (CurrentPage < NumberOfPages) { next.Enabled = true; next.NavigateUrl = CreateUrlWithPageNumber( CurrentPage + 1 ); } else { next.Enabled = false; } uxPanel.Controls.Add( next ); } private void AddLinkPreviousPageNumber() { if (CurrentPage < (_limitPage / 2)) { for (int pageNumber = 1; pageNumber <= (_limitPage / 2); pageNumber++) { if (pageNumber == CurrentPage) AddText( pageNumber.ToString() ); else AddOnePageLink( pageNumber ); AddSpace(); } } else { AddOnePageLink( 1 ); AddSpace(); for(int pageNumber = (CurrentPage - (_limitPage / 2));pageNumber <= CurrentPage;pageNumber++) { if (pageNumber == CurrentPage) AddText( pageNumber.ToString() ); else AddOnePageLink( pageNumber ); AddSpace(); } } } private void AddFirstLinkIfNecessary( int low ) { if (low > 1) { AddSpace(); AddOnePageLink( 1 ); if (low > 2) { AddSpace(); AddDots(); } } } private void AddLastLinkIfNecessary( int high ) { if (high < NumberOfPages) { if (high < NumberOfPages - 1) { AddDots(); AddSpace(); } AddOnePageLink( NumberOfPages ); AddSpace(); } } private void AddLinkPageNumber( int low, int high ) { AddSpace(); for (int pageNumber = low; pageNumber <= high; pageNumber++) { if (pageNumber == CurrentPage) AddText( pageNumber.ToString() ); else AddOnePageLink( pageNumber ); AddSpace(); } } protected void Page_Load( object sender, EventArgs e ) { } // Update control status in PreRender event. Wait parent page to set // number of pages first protected void Page_PreRender( object sender, EventArgs e ) { int low, high; DeterminePageRange( out low, out high ); AddLinkPrevious(); AddFirstLinkIfNecessary( low ); AddLinkPageNumber( low, high ); AddLastLinkIfNecessary( high ); AddLinkNext(); } public int CurrentPage { get { int result; string page = Request.QueryString["Page"]; if (String.IsNullOrEmpty( page ) || !int.TryParse( page, out result )) return 1; else return result; } } public int NumberOfPages { get { if (ViewState["NumberOfPages"] == null) return 1; else return (int) ViewState["NumberOfPages"]; } set { ViewState["NumberOfPages"] = value; } } }
#region License // Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // The latest version of this file can be found at http://www.codeplex.com/FluentValidation #endregion namespace FluentValidation { using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using Internal; using Results; using Validators; /// <summary> /// Base class for entity validator classes. /// </summary> /// <typeparam name="T">The type of the object being validated</typeparam> public abstract class AbstractValidator<T> : IValidator<T>, IEnumerable<IValidationRule> { readonly TrackingCollection<IValidationRule> nestedValidators = new TrackingCollection<IValidationRule>(); // Work-around for reflection bug in .NET 4.5 static Func<CascadeMode> s_cascadeMode = () => ValidatorOptions.CascadeMode; Func<CascadeMode> cascadeMode = s_cascadeMode; /// <summary> /// Sets the cascade mode for all rules within this validator. /// </summary> public CascadeMode CascadeMode { get { return cascadeMode(); } set { cascadeMode = () => value; } } ValidationResult IValidator.Validate(object instance) { instance.Guard("Cannot pass null to Validate."); if(! ((IValidator)this).CanValidateInstancesOfType(instance.GetType())) { throw new InvalidOperationException(string.Format("Cannot validate instances of type '{0}'. This validator can only validate instances of type '{1}'.", instance.GetType().Name, typeof(T).Name)); } return Validate((T)instance); } Task<ValidationResult> IValidator.ValidateAsync(object instance, CancellationToken cancellation = new CancellationToken()) { instance.Guard("Cannot pass null to Validate."); if (!((IValidator) this).CanValidateInstancesOfType(instance.GetType())) { throw new InvalidOperationException(string.Format("Cannot validate instances of type '{0}'. This validator can only validate instances of type '{1}'.", instance.GetType().Name, typeof (T).Name)); } return ValidateAsync((T) instance, cancellation); } ValidationResult IValidator.Validate(ValidationContext context) { context.Guard("Cannot pass null to Validate"); var newContext = new ValidationContext<T>((T)context.InstanceToValidate, context.PropertyChain, context.Selector) { IsChildContext = context.IsChildContext }; return Validate(newContext); } Task<ValidationResult> IValidator.ValidateAsync(ValidationContext context, CancellationToken cancellation) { context.Guard("Cannot pass null to Validate"); var newContext = new ValidationContext<T>((T) context.InstanceToValidate, context.PropertyChain, context.Selector) { IsChildContext = context.IsChildContext }; return ValidateAsync(newContext, cancellation); } /// <summary> /// Validates the specified instance /// </summary> /// <param name="instance">The object to validate</param> /// <returns>A ValidationResult object containing any validation failures</returns> public virtual ValidationResult Validate(T instance) { return Validate(new ValidationContext<T>(instance, new PropertyChain(), new DefaultValidatorSelector())); } /// <summary> /// Validates the specified instance asynchronously /// </summary> /// <param name="instance">The object to validate</param> /// <returns>A ValidationResult object containing any validation failures</returns> public Task<ValidationResult> ValidateAsync(T instance, CancellationToken cancellation = new CancellationToken()) { return ValidateAsync(new ValidationContext<T>(instance, new PropertyChain(), new DefaultValidatorSelector()), cancellation); } /// <summary> /// Validates the specified instance. /// </summary> /// <param name="context">Validation Context</param> /// <returns>A ValidationResult object containing any validation failures.</returns> public virtual ValidationResult Validate(ValidationContext<T> context) { context.Guard("Cannot pass null to Validate"); var failures = nestedValidators.SelectMany(x => x.Validate(context)).ToList(); return new ValidationResult(failures); } /// <summary> /// Validates the specified instance asynchronously. /// </summary> /// <param name="context">Validation Context</param> /// <returns>A ValidationResult object containing any validation failures.</returns> public virtual Task<ValidationResult> ValidateAsync(ValidationContext<T> context, CancellationToken cancellation = new CancellationToken()) { context.Guard("Cannot pass null to Validate"); var failures = new List<ValidationFailure>(); return TaskHelpers.Iterate( nestedValidators .Select(v => v.ValidateAsync(context, cancellation).Then(fs => failures.AddRange(fs), runSynchronously: true)) ).Then( () => new ValidationResult(failures) ); } /// <summary> /// Adds a rule to the current validator. /// </summary> /// <param name="rule"></param> public void AddRule(IValidationRule rule) { nestedValidators.Add(rule); } /// <summary> /// Creates a <see cref="IValidatorDescriptor" /> that can be used to obtain metadata about the current validator. /// </summary> public virtual IValidatorDescriptor CreateDescriptor() { return new ValidatorDescriptor<T>(nestedValidators); } bool IValidator.CanValidateInstancesOfType(Type type) { return type.CanAssignTo(typeof(T)); } /// <summary> /// Defines a validation rule for a specify property. /// </summary> /// <example> /// RuleFor(x => x.Surname)... /// </example> /// <typeparam name="TProperty">The type of property being validated</typeparam> /// <param name="expression">The expression representing the property to validate</param> /// <returns>an IRuleBuilder instance on which validators can be defined</returns> public IRuleBuilderInitial<T, TProperty> RuleFor<TProperty>(Expression<Func<T, TProperty>> expression) { expression.Guard("Cannot pass null to RuleFor"); var rule = PropertyRule.Create(expression, () => CascadeMode); AddRule(rule); var ruleBuilder = new RuleBuilder<T, TProperty>(rule); return ruleBuilder; } public IRuleBuilderInitial<T, TProperty> RuleForEach<TProperty>(Expression<Func<T, IEnumerable<TProperty>>> expression) { expression.Guard("Cannot pass null to RuleForEach"); var rule = CollectionPropertyRule<TProperty>.Create(expression, () => CascadeMode); AddRule(rule); var ruleBuilder = new RuleBuilder<T, TProperty>(rule); return ruleBuilder; } /// <summary> /// Defines a custom validation rule using a lambda expression. /// If the validation rule fails, it should return a instance of a <see cref="ValidationFailure">ValidationFailure</see> /// If the validation rule succeeds, it should return null. /// </summary> /// <param name="customValidator">A lambda that executes custom validation rules.</param> public void Custom(Func<T, ValidationFailure> customValidator) { customValidator.Guard("Cannot pass null to Custom"); AddRule(new DelegateValidator<T>(x => new[] { customValidator(x) })); } /// <summary> /// Defines a custom validation rule using a lambda expression. /// If the validation rule fails, it should return an instance of <see cref="ValidationFailure">ValidationFailure</see> /// If the validation rule succeeds, it should return null. /// </summary> /// <param name="customValidator">A lambda that executes custom validation rules</param> public void Custom(Func<T, ValidationContext<T>, ValidationFailure> customValidator) { customValidator.Guard("Cannot pass null to Custom"); AddRule(new DelegateValidator<T>((x, ctx) => new[] { customValidator(x, ctx) })); } /// <summary> /// Defines a custom asynchronous validation rule using a lambda expression. /// If the validation rule fails, it should asynchronously return a instance of a <see cref="ValidationFailure">ValidationFailure</see> /// If the validation rule succeeds, it should return null. /// </summary> /// <param name="customValidator">A lambda that executes custom validation rules.</param> public void CustomAsync(Func<T, Task<ValidationFailure>> customValidator) { customValidator.Guard("Cannot pass null to Custom"); AddRule(new DelegateValidator<T>(x => customValidator(x).Then(f => new[] {f}.AsEnumerable(), runSynchronously: true))); } /// <summary> /// Defines a custom asynchronous validation rule using a lambda expression. /// If the validation rule fails, it should asynchronously return an instance of <see cref="ValidationFailure">ValidationFailure</see> /// If the validation rule succeeds, it should return null. /// </summary> /// <param name="customValidator">A lambda that executes custom validation rules</param> public void CustomAsync(Func<T, ValidationContext<T>, CancellationToken, Task<ValidationFailure>> customValidator) { customValidator.Guard("Cannot pass null to Custom"); AddRule(new DelegateValidator<T>((x, ctx, cancel) => customValidator(x, ctx, cancel).Then(f => new[] {f}.AsEnumerable(), runSynchronously: true))); } /// <summary> /// Defines a RuleSet that can be used to group together several validators. /// </summary> /// <param name="ruleSetName">The name of the ruleset.</param> /// <param name="action">Action that encapsulates the rules in the ruleset.</param> public void RuleSet(string ruleSetName, Action action) { ruleSetName.Guard("A name must be specified when calling RuleSet."); action.Guard("A ruleset definition must be specified when calling RuleSet."); using (nestedValidators.OnItemAdded(r => r.RuleSet = ruleSetName)) { action(); } } /// <summary> /// Defines a condition that applies to several rules /// </summary> /// <param name="predicate">The condition that should apply to multiple rules</param> /// <param name="action">Action that encapsulates the rules.</param> /// <returns></returns> public void When(Func<T, bool> predicate, Action action) { var propertyRules = new List<IValidationRule>(); Action<IValidationRule> onRuleAdded = propertyRules.Add; using(nestedValidators.OnItemAdded(onRuleAdded)) { action(); } // Must apply the predicate after the rule has been fully created to ensure any rules-specific conditions have already been applied. propertyRules.ForEach(x => x.ApplyCondition(predicate.CoerceToNonGeneric())); } /// <summary> /// Defines an inverse condition that applies to several rules /// </summary> /// <param name="predicate">The condition that should be applied to multiple rules</param> /// <param name="action">Action that encapsulates the rules</param> public void Unless(Func<T, bool> predicate, Action action) { When(x => !predicate(x), action); } /// <summary> /// Defines an asynchronous condition that applies to several rules /// </summary> /// <param name="predicate">The asynchronous condition that should apply to multiple rules</param> /// <param name="action">Action that encapsulates the rules.</param> /// <returns></returns> public void WhenAsync(Func<T, Task<bool>> predicate, Action action) { var propertyRules = new List<IValidationRule>(); Action<IValidationRule> onRuleAdded = propertyRules.Add; using (nestedValidators.OnItemAdded(onRuleAdded)) { action(); } // Must apply the predicate after the rule has been fully created to ensure any rules-specific conditions have already been applied. propertyRules.ForEach(x => x.ApplyAsyncCondition(predicate.CoerceToNonGeneric())); } /// <summary> /// Defines an inverse asynchronous condition that applies to several rules /// </summary> /// <param name="predicate">The asynchronous condition that should be applied to multiple rules</param> /// <param name="action">Action that encapsulates the rules</param> public void UnlessAsync(Func<T, Task<bool>> predicate, Action action) { WhenAsync(x => predicate(x).Then(y => !y), action); } /// <summary> /// Returns an enumerator that iterates through the collection of validation rules. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection. /// </returns> /// <filterpriority>1</filterpriority> public IEnumerator<IValidationRule> GetEnumerator() { return nestedValidators.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class DependentRules<T> : AbstractValidator<T> { } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------ using System.Diagnostics; using System.Data.Common; using System.IO; using Res = System.SR; namespace System.Data.SqlTypes { internal enum SqlBytesCharsState { Null = 0, Buffer = 1, //IntPtr = 2, Stream = 3, } public sealed class SqlBytes : System.Data.SqlTypes.INullable { // -------------------------------------------------------------- // Data members // -------------------------------------------------------------- // SqlBytes has five possible states // 1) SqlBytes is Null // - m_stream must be null, m_lCuLen must be x_lNull. // 2) SqlBytes contains a valid buffer, // - m_rgbBuf must not be null,m_stream must be null // 3) SqlBytes contains a valid pointer // - m_rgbBuf could be null or not, // if not null, content is garbage, should never look into it. // - m_stream must be null. // 4) SqlBytes contains a Stream // - m_stream must not be null // - m_rgbBuf could be null or not. if not null, content is garbage, should never look into it. // - m_lCurLen must be x_lNull. // 5) SqlBytes contains a Lazy Materialized Blob (ie, StorageState.Delayed) // internal byte[] m_rgbBuf; // Data buffer private long _lCurLen; // Current data length internal Stream m_stream; private SqlBytesCharsState _state; private byte[] _rgbWorkBuf; // A 1-byte work buffer. // The max data length that we support at this time. private const long x_lMaxLen = (long)System.Int32.MaxValue; private const long x_lNull = -1L; // -------------------------------------------------------------- // Constructor(s) // -------------------------------------------------------------- // Public default constructor used for XML serialization public SqlBytes() { SetNull(); } // Create a SqlBytes with an in-memory buffer public SqlBytes(byte[] buffer) { m_rgbBuf = buffer; m_stream = null; if (m_rgbBuf == null) { _state = SqlBytesCharsState.Null; _lCurLen = x_lNull; } else { _state = SqlBytesCharsState.Buffer; _lCurLen = (long)m_rgbBuf.Length; } _rgbWorkBuf = null; AssertValid(); } // Create a SqlBytes from a SqlBinary public SqlBytes(SqlBinary value) : this(value.IsNull ? (byte[])null : value.Value) { } public SqlBytes(Stream s) { // Create a SqlBytes from a Stream m_rgbBuf = null; _lCurLen = x_lNull; m_stream = s; _state = (s == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream; _rgbWorkBuf = null; AssertValid(); } // -------------------------------------------------------------- // Public properties // -------------------------------------------------------------- // INullable public bool IsNull { get { return _state == SqlBytesCharsState.Null; } } // Property: the in-memory buffer of SqlBytes // Return Buffer even if SqlBytes is Null. public byte[] Buffer { get { if (FStream()) { CopyStreamToBuffer(); } return m_rgbBuf; } } // Property: the actual length of the data public long Length { get { switch (_state) { case SqlBytesCharsState.Null: throw new SqlNullValueException(); case SqlBytesCharsState.Stream: return m_stream.Length; default: return _lCurLen; } } } // Property: the max length of the data // Return MaxLength even if SqlBytes is Null. // When the buffer is also null, return -1. // If containing a Stream, return -1. public long MaxLength { get { switch (_state) { case SqlBytesCharsState.Stream: return -1L; default: return (m_rgbBuf == null) ? -1L : (long)m_rgbBuf.Length; } } } // Property: get a copy of the data in a new byte[] array. public byte[] Value { get { byte[] buffer; switch (_state) { case SqlBytesCharsState.Null: throw new SqlNullValueException(); case SqlBytesCharsState.Stream: if (m_stream.Length > x_lMaxLen) throw new SqlTypeException(Res.GetString(Res.SqlMisc_BufferInsufficientMessage)); buffer = new byte[m_stream.Length]; if (m_stream.Position != 0) m_stream.Seek(0, SeekOrigin.Begin); m_stream.Read(buffer, 0, checked((int)m_stream.Length)); break; default: buffer = new byte[_lCurLen]; Array.Copy(m_rgbBuf, buffer, (int)_lCurLen); break; } return buffer; } } // class indexer public byte this[long offset] { get { if (offset < 0 || offset >= this.Length) throw new ArgumentOutOfRangeException("offset"); if (_rgbWorkBuf == null) _rgbWorkBuf = new byte[1]; Read(offset, _rgbWorkBuf, 0, 1); return _rgbWorkBuf[0]; } set { if (_rgbWorkBuf == null) _rgbWorkBuf = new byte[1]; _rgbWorkBuf[0] = value; Write(offset, _rgbWorkBuf, 0, 1); } } public StorageState Storage { get { switch (_state) { case SqlBytesCharsState.Null: throw new SqlNullValueException(); case SqlBytesCharsState.Stream: return StorageState.Stream; case SqlBytesCharsState.Buffer: return StorageState.Buffer; default: return StorageState.UnmanagedBuffer; } } } public Stream Stream { get { return FStream() ? m_stream : new StreamOnSqlBytes(this); } set { _lCurLen = x_lNull; m_stream = value; _state = (value == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream; AssertValid(); } } // -------------------------------------------------------------- // Public methods // -------------------------------------------------------------- public void SetNull() { _lCurLen = x_lNull; m_stream = null; _state = SqlBytesCharsState.Null; AssertValid(); } // Set the current length of the data // If the SqlBytes is Null, setLength will make it non-Null. public void SetLength(long value) { if (value < 0) throw new ArgumentOutOfRangeException("value"); if (FStream()) { m_stream.SetLength(value); } else { // If there is a buffer, even the value of SqlBytes is Null, // still allow setting length to zero, which will make it not Null. // If the buffer is null, raise exception // if (null == m_rgbBuf) throw new SqlTypeException(Res.GetString(Res.SqlMisc_NoBufferMessage)); if (value > (long)m_rgbBuf.Length) throw new ArgumentOutOfRangeException("value"); else if (IsNull) // At this point we know that value is small enough // Go back in buffer mode _state = SqlBytesCharsState.Buffer; _lCurLen = value; } AssertValid(); } // Read data of specified length from specified offset into a buffer public long Read(long offset, byte[] buffer, int offsetInBuffer, int count) { if (IsNull) throw new SqlNullValueException(); // Validate the arguments if (buffer == null) throw new ArgumentNullException("buffer"); if (offset > this.Length || offset < 0) throw new ArgumentOutOfRangeException("offset"); if (offsetInBuffer > buffer.Length || offsetInBuffer < 0) throw new ArgumentOutOfRangeException("offsetInBuffer"); if (count < 0 || count > buffer.Length - offsetInBuffer) throw new ArgumentOutOfRangeException("count"); // Adjust count based on data length if (count > this.Length - offset) count = (int)(this.Length - offset); if (count != 0) { switch (_state) { case SqlBytesCharsState.Stream: if (m_stream.Position != offset) m_stream.Seek(offset, SeekOrigin.Begin); m_stream.Read(buffer, offsetInBuffer, count); break; default: // ProjectK\Core doesn't support long-typed array indexers Debug.Assert(offset < int.MaxValue); Array.Copy(m_rgbBuf, checked((int)offset), buffer, offsetInBuffer, count); break; } } return count; } // Write data of specified length into the SqlBytes from specified offset public void Write(long offset, byte[] buffer, int offsetInBuffer, int count) { if (FStream()) { if (m_stream.Position != offset) m_stream.Seek(offset, SeekOrigin.Begin); m_stream.Write(buffer, offsetInBuffer, count); } else { // Validate the arguments if (buffer == null) throw new ArgumentNullException("buffer"); if (m_rgbBuf == null) throw new SqlTypeException(Res.GetString(Res.SqlMisc_NoBufferMessage)); if (offset < 0) throw new ArgumentOutOfRangeException("offset"); if (offset > m_rgbBuf.Length) throw new SqlTypeException(Res.GetString(Res.SqlMisc_BufferInsufficientMessage)); if (offsetInBuffer < 0 || offsetInBuffer > buffer.Length) throw new ArgumentOutOfRangeException("offsetInBuffer"); if (count < 0 || count > buffer.Length - offsetInBuffer) throw new ArgumentOutOfRangeException("count"); if (count > m_rgbBuf.Length - offset) throw new SqlTypeException(Res.GetString(Res.SqlMisc_BufferInsufficientMessage)); if (IsNull) { // If NULL and there is buffer inside, we only allow writing from // offset zero. // if (offset != 0) throw new SqlTypeException(Res.GetString(Res.SqlMisc_WriteNonZeroOffsetOnNullMessage)); // treat as if our current length is zero. // Note this has to be done after all inputs are validated, so that // we won't throw exception after this point. // _lCurLen = 0; _state = SqlBytesCharsState.Buffer; } else if (offset > _lCurLen) { // Don't allow writing from an offset that this larger than current length. // It would leave uninitialized data in the buffer. // throw new SqlTypeException(Res.GetString(Res.SqlMisc_WriteOffsetLargerThanLenMessage)); } if (count != 0) { // ProjectK\Core doesn't support long-typed array indexers Debug.Assert(offset < int.MaxValue); Array.Copy(buffer, offsetInBuffer, m_rgbBuf, checked((int)offset), count); // If the last position that has been written is after // the current data length, reset the length if (_lCurLen < offset + count) _lCurLen = offset + count; } } AssertValid(); } public SqlBinary ToSqlBinary() { return IsNull ? SqlBinary.Null : new SqlBinary(Value); } // -------------------------------------------------------------- // Conversion operators // -------------------------------------------------------------- // Alternative method: ToSqlBinary() public static explicit operator SqlBinary(SqlBytes value) { return value.ToSqlBinary(); } // Alternative method: constructor SqlBytes(SqlBinary) public static explicit operator SqlBytes(SqlBinary value) { return new SqlBytes(value); } // -------------------------------------------------------------- // Private utility functions // -------------------------------------------------------------- [System.Diagnostics.Conditional("DEBUG")] private void AssertValid() { Debug.Assert(_state >= SqlBytesCharsState.Null && _state <= SqlBytesCharsState.Stream); if (IsNull) { } else { Debug.Assert((_lCurLen >= 0 && _lCurLen <= x_lMaxLen) || FStream()); Debug.Assert(FStream() || (m_rgbBuf != null && _lCurLen <= m_rgbBuf.Length)); Debug.Assert(!FStream() || (_lCurLen == x_lNull)); } Debug.Assert(_rgbWorkBuf == null || _rgbWorkBuf.Length == 1); } // Copy the data from the Stream to the array buffer. // If the SqlBytes doesn't hold a buffer or the buffer // is not big enough, allocate new byte array. private void CopyStreamToBuffer() { Debug.Assert(FStream()); long lStreamLen = m_stream.Length; if (lStreamLen >= x_lMaxLen) throw new SqlTypeException(Res.GetString(Res.SqlMisc_WriteOffsetLargerThanLenMessage)); if (m_rgbBuf == null || m_rgbBuf.Length < lStreamLen) m_rgbBuf = new byte[lStreamLen]; if (m_stream.Position != 0) m_stream.Seek(0, SeekOrigin.Begin); m_stream.Read(m_rgbBuf, 0, (int)lStreamLen); m_stream = null; _lCurLen = lStreamLen; _state = SqlBytesCharsState.Buffer; AssertValid(); } // whether the SqlBytes contains a pointer // whether the SqlBytes contains a Stream internal bool FStream() { return _state == SqlBytesCharsState.Stream; } private void SetBuffer(byte[] buffer) { m_rgbBuf = buffer; _lCurLen = (m_rgbBuf == null) ? x_lNull : (long)m_rgbBuf.Length; m_stream = null; _state = (m_rgbBuf == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Buffer; AssertValid(); } // -------------------------------------------------------------- // Static fields, properties // -------------------------------------------------------------- // Get a Null instance. // Since SqlBytes is mutable, have to be property and create a new one each time. public static SqlBytes Null { get { return new SqlBytes((byte[])null); } } } // class SqlBytes // StreamOnSqlBytes is a stream build on top of SqlBytes, and // provides the Stream interface. The purpose is to help users // to read/write SqlBytes object. After getting the stream from // SqlBytes, users could create a BinaryReader/BinaryWriter object // to easily read and write primitive types. internal sealed class StreamOnSqlBytes : Stream { // -------------------------------------------------------------- // Data members // -------------------------------------------------------------- private SqlBytes _sb; // the SqlBytes object private long _lPosition; // -------------------------------------------------------------- // Constructor(s) // -------------------------------------------------------------- internal StreamOnSqlBytes(SqlBytes sb) { _sb = sb; _lPosition = 0; } // -------------------------------------------------------------- // Public properties // -------------------------------------------------------------- // Always can read/write/seek, unless sb is null, // which means the stream has been closed. public override bool CanRead { get { return _sb != null && !_sb.IsNull; } } public override bool CanSeek { get { return _sb != null; } } public override bool CanWrite { get { return _sb != null && (!_sb.IsNull || _sb.m_rgbBuf != null); } } public override long Length { get { CheckIfStreamClosed("get_Length"); return _sb.Length; } } public override long Position { get { CheckIfStreamClosed("get_Position"); return _lPosition; } set { CheckIfStreamClosed("set_Position"); if (value < 0 || value > _sb.Length) throw new ArgumentOutOfRangeException("value"); else _lPosition = value; } } // -------------------------------------------------------------- // Public methods // -------------------------------------------------------------- public override long Seek(long offset, SeekOrigin origin) { CheckIfStreamClosed("Seek"); long lPosition = 0; switch (origin) { case SeekOrigin.Begin: if (offset < 0 || offset > _sb.Length) throw new ArgumentOutOfRangeException("offset"); _lPosition = offset; break; case SeekOrigin.Current: lPosition = _lPosition + offset; if (lPosition < 0 || lPosition > _sb.Length) throw new ArgumentOutOfRangeException("offset"); _lPosition = lPosition; break; case SeekOrigin.End: lPosition = _sb.Length + offset; if (lPosition < 0 || lPosition > _sb.Length) throw new ArgumentOutOfRangeException("offset"); _lPosition = lPosition; break; default: throw ADP.InvalidSeekOrigin("offset"); } return _lPosition; } // The Read/Write/ReadByte/WriteByte simply delegates to SqlBytes public override int Read(byte[] buffer, int offset, int count) { CheckIfStreamClosed("Read"); if (buffer == null) throw new ArgumentNullException("buffer"); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException("offset"); if (count < 0 || count > buffer.Length - offset) throw new ArgumentOutOfRangeException("count"); int iBytesRead = (int)_sb.Read(_lPosition, buffer, offset, count); _lPosition += iBytesRead; return iBytesRead; } public override void Write(byte[] buffer, int offset, int count) { CheckIfStreamClosed("Write"); if (buffer == null) throw new ArgumentNullException("buffer"); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException("offset"); if (count < 0 || count > buffer.Length - offset) throw new ArgumentOutOfRangeException("count"); _sb.Write(_lPosition, buffer, offset, count); _lPosition += count; } public override int ReadByte() { CheckIfStreamClosed("ReadByte"); // If at the end of stream, return -1, rather than call SqlBytes.ReadByte, // which will throw exception. This is the behavior for Stream. // if (_lPosition >= _sb.Length) return -1; int ret = _sb[_lPosition]; _lPosition++; return ret; } public override void WriteByte(byte value) { CheckIfStreamClosed("WriteByte"); _sb[_lPosition] = value; _lPosition++; } public override void SetLength(long value) { CheckIfStreamClosed("SetLength"); _sb.SetLength(value); if (_lPosition > value) _lPosition = value; } // Flush is a no-op for stream on SqlBytes, because they are all in memory public override void Flush() { if (_sb.FStream()) _sb.m_stream.Flush(); } protected override void Dispose(bool disposing) { // When m_sb is null, it means the stream has been closed, and // any opearation in the future should fail. // This is the only case that m_sb is null. try { _sb = null; } finally { base.Dispose(disposing); } } // -------------------------------------------------------------- // Private utility functions // -------------------------------------------------------------- private bool FClosed() { return _sb == null; } private void CheckIfStreamClosed(string methodname) { if (FClosed()) throw ADP.StreamClosed(methodname); } } // class StreamOnSqlBytes } // namespace System.Data.SqlTypes
namespace LexLib { /* * Class: Emit */ using System; using System.Text; using System.IO; using System.Collections; public class Emit { /* * Member Variables */ private Spec spec; private StreamWriter outstream; /* * Constants: Anchor Types */ private const int START = 1; private const int END = 2; private const int NONE = 4; /* * Constants */ private const bool EDBG = true; private const bool NOT_EDBG = false; /* * Function: Emit * Description: Constructor. */ public Emit() { reset(); } /* * Function: reset * Description: Clears member variables. */ private void reset() { spec = null; outstream = null; } /* * Function: set * Description: Initializes member variables. */ private void set(Spec s, StreamWriter o) { #if DEBUG Utility.assert(null != s); Utility.assert(null != o); #endif spec = s; outstream = o; } /* * Function: print_details * Description: Debugging output. */ private void print_details() { int i; int j; int next; int state; DTrans dtrans; Accept accept; bool tr; System.Console.WriteLine("---------------------- Transition Table ----------------------"); for (i = 0; i < spec.row_map.Length; ++i) { System.Console.Write("State " + i); accept = (Accept)spec.accept_list[i]; if (null == accept) { System.Console.WriteLine(" [nonaccepting]"); } else { System.Console.WriteLine(" [accepting, line " + accept.line_number + " <" + accept.action + ">]"); } dtrans = (DTrans)spec.dtrans_list[spec.row_map[i]]; tr = false; state = dtrans.GetDTrans(spec.col_map[0]); if (DTrans.F != state) { tr = true; System.Console.Write("\tgoto " + state.ToString() + " on ["); } for (j = 1; j < spec.dtrans_ncols; j++) { next = dtrans.GetDTrans(spec.col_map[j]); if (state == next) { if (DTrans.F != state) { System.Console.Write((char)j); } } else { state = next; if (tr) { System.Console.WriteLine("]"); tr = false; } if (DTrans.F != state) { tr = true; System.Console.Write("\tgoto " + state.ToString() + " on [" + Char.ToString((char)j)); } } } if (tr) { System.Console.WriteLine("]"); } } System.Console.WriteLine("---------------------- Transition Table ----------------------"); } /* * Function: Write * Description: High-level access function to module. */ public void Write(Spec spec, StreamWriter o) { set(spec, o); #if DEBUG Utility.assert(null != spec); Utility.assert(null != o); #endif #if OLD_DEBUG print_details(); #endif Header(); Construct(); States(); Helpers(); Driver(); Footer(); outstream.Flush(); reset(); } /* * Function: construct * Description: Emits constructor, member variables, * and constants. */ private void Construct() { #if DEBUG Utility.assert(null != spec); Utility.assert(null != outstream); #endif /* Constants */ outstream.Write(@" #region constants {0} const int YY_BUFFER_SIZE = 512; const int YY_F = -1; const int YY_NO_STATE = -1; const int YY_NOT_ACCEPT = 0; const int YY_START = 1; const int YY_END = 2; const int YY_NO_ANCHOR = 4; const int YY_BOL = {1}; const int YY_EOF = {2}; #endregion ", (spec.integer_type || spec.yyeof) ? "public const int YYEOF = -1;" : "", spec.BOL, spec.EOF); /* type declarations */ outstream.WriteLine(@" delegate {0} AcceptMethod(); AcceptMethod[] accept_dispatch; ", spec.type_name); /* User specified class code */ if (null != spec.class_code) { outstream.Write(spec.class_code); } /* Member Variables */ outstream.Write( @" #region private members TextReader yy_reader; int yy_buffer_index; int yy_buffer_read; int yy_buffer_start; int yy_buffer_end; char[] yy_buffer = new char[YY_BUFFER_SIZE]; int yychar; int yyline; bool yy_at_bol = true; int yy_lexical_state = YYINITIAL; #endregion "); /* Function: first constructor (Reader) */ string spec_access = "internal "; if (spec.lex_public) spec_access = "public "; outstream.Write(@" #region constructors {0} {1}(TextReader reader) : this() {{ if (reader == null) throw new ApplicationException(""Error: Bad input stream initializer.""); yy_reader = reader; }} {0} {1}(FileStream instream) : this() {{ if (instream == null) throw new ApplicationException(""Error: Bad input stream initializer.""); yy_reader = new StreamReader(instream); }} {1}() {{ actionInit(); userInit(); }} #endregion ", spec_access, spec.class_name); // action init var actioninit = Action_Methods_Init(); outstream.Write(actioninit); // User specified constructor init code var userinit = User_Init(); outstream.Write(userinit); var actions = Action_Methods_Body(); outstream.Write(actions); } /* * Function: states * Description: Emits constants that serve as lexical states, * including YYINITIAL. */ private void States() { foreach (string state in spec.states.Keys) { #if DEBUG Utility.assert(null != state); #endif outstream.Write( "private const int " + state + " = " + spec.states[state] + ";\n"); } outstream.Write("private static int[] yy_state_dtrans = new int[] \n" + " { "); for (int index = 0; index < spec.state_dtrans.Length; ++index) { outstream.Write(" " + spec.state_dtrans[index]); if (index < spec.state_dtrans.Length - 1) outstream.Write(",\n"); else outstream.Write("\n"); } outstream.Write(" };\n"); } /* * Function: Helpers * Description: Emits helper functions, particularly * error handling and input buffering. */ private void Helpers() { #if DEBUG Utility.assert(null != spec); Utility.assert(null != outstream); #endif outstream.WriteLine("#region helpers"); /* Function: yy_do_eof */ if (spec.eof_code != null) { outstream.Write("private bool yy_eof_done = false;\n" + "private void yy_do_eof ()\n" + " {\n" + " if (!yy_eof_done)\n" + " {\n" + " " + spec.eof_code + "\n" + " }\n" + " yy_eof_done = true;\n" + " }\n\n"); } /* Function: yybegin */ outstream.Write( "private void yybegin (int state)\n" + " {\n" + " yy_lexical_state = state;\n" + " }\n\n"); /* Function: yy_advance */ outstream.Write( "private char yy_advance ()\n" + " {\n" + " int next_read;\n" + " int i;\n" + " int j;\n" + "\n" + " if (yy_buffer_index < yy_buffer_read)\n" + " {\n" + " return yy_buffer[yy_buffer_index++];\n" + " }\n" + "\n" + " if (0 != yy_buffer_start)\n" + " {\n" + " i = yy_buffer_start;\n" + " j = 0;\n" + " while (i < yy_buffer_read)\n" + " {\n" + " yy_buffer[j] = yy_buffer[i];\n" + " i++;\n" + " j++;\n" + " }\n" + " yy_buffer_end = yy_buffer_end - yy_buffer_start;\n" + " yy_buffer_start = 0;\n" + " yy_buffer_read = j;\n" + " yy_buffer_index = j;\n" + " next_read = yy_reader.Read(yy_buffer,yy_buffer_read,\n" + " yy_buffer.Length - yy_buffer_read);\n" // + " if (-1 == next_read)\n" + " if (next_read <= 0)\n" + " {\n" + " return (char) YY_EOF;\n" + " }\n" + " yy_buffer_read = yy_buffer_read + next_read;\n" + " }\n" + " while (yy_buffer_index >= yy_buffer_read)\n" + " {\n" + " if (yy_buffer_index >= yy_buffer.Length)\n" + " {\n" + " yy_buffer = yy_double(yy_buffer);\n" + " }\n" + " next_read = yy_reader.Read(yy_buffer,yy_buffer_read,\n" + " yy_buffer.Length - yy_buffer_read);\n" // + " if (-1 == next_read)\n" + " if (next_read <= 0)\n" + " {\n" + " return (char) YY_EOF;\n" + " }\n" + " yy_buffer_read = yy_buffer_read + next_read;\n" + " }\n" + " return yy_buffer[yy_buffer_index++];\n" + " }\n"); /* Function: yy_move_end */ outstream.Write( "private void yy_move_end ()\n" + " {\n" + " if (yy_buffer_end > yy_buffer_start && \n" + " '\\n' == yy_buffer[yy_buffer_end-1])\n" + " yy_buffer_end--;\n" + " if (yy_buffer_end > yy_buffer_start &&\n" + " '\\r' == yy_buffer[yy_buffer_end-1])\n" + " yy_buffer_end--;\n" + " }\n" ); /* Function: yy_mark_start */ outstream.Write("private bool yy_last_was_cr=false;\n" + "private void yy_mark_start ()\n" + " {\n"); if (spec.count_lines) { outstream.Write( " int i;\n" + " for (i = yy_buffer_start; i < yy_buffer_index; i++)\n" + " {\n" + " if (yy_buffer[i] == '\\n' && !yy_last_was_cr)\n" + " {\n" + " yyline++;\n" + " }\n" + " if (yy_buffer[i] == '\\r')\n" + " {\n" + " yyline++;\n" + " yy_last_was_cr=true;\n" + " }\n" + " else\n" + " {\n" + " yy_last_was_cr=false;\n" + " }\n" + " }\n" ); } if (spec.count_chars) { outstream.Write( " yychar = yychar + yy_buffer_index - yy_buffer_start;\n"); } outstream.Write( " yy_buffer_start = yy_buffer_index;\n" + " }\n"); /* Function: yy_mark_end */ outstream.Write( "private void yy_mark_end ()\n" + " {\n" + " yy_buffer_end = yy_buffer_index;\n" + " }\n"); /* Function: yy_to_mark */ outstream.Write( "private void yy_to_mark ()\n" + " {\n" + " yy_buffer_index = yy_buffer_end;\n" + " yy_at_bol = (yy_buffer_end > yy_buffer_start) &&\n" + " (yy_buffer[yy_buffer_end-1] == '\\r' ||\n" + " yy_buffer[yy_buffer_end-1] == '\\n');\n" + " }\n"); /* Function: yytext */ outstream.Write( "internal string yytext()\n" + " {\n" + " return (new string(yy_buffer,\n" + " yy_buffer_start,\n" + " yy_buffer_end - yy_buffer_start)\n" + " );\n" + " }\n"); /* Function: yylength */ outstream.Write( "private int yylength ()\n" + " {\n" + " return yy_buffer_end - yy_buffer_start;\n" + " }\n"); /* Function: yy_double */ outstream.Write( "private char[] yy_double (char[] buf)\n" + " {\n" + " int i;\n" + " char[] newbuf;\n" + " newbuf = new char[2*buf.Length];\n" + " for (i = 0; i < buf.Length; i++)\n" + " {\n" + " newbuf[i] = buf[i];\n" + " }\n" + " return newbuf;\n" + " }\n"); /* Function: yy_error */ outstream.Write( "private const int YY_E_INTERNAL = 0;\n" + "private const int YY_E_MATCH = 1;\n" + "private static string[] yy_error_string = new string[]\n" + " {\n" + " \"Error: Internal error.\\n\",\n" + " \"Error: Unmatched input.\\n\"\n" + " };\n"); outstream.Write( "private void yy_error (int code,bool fatal)\n" + " {\n" + " System.Console.Write(yy_error_string[code]);\n" + " if (fatal)\n" + " {\n" + " throw new System.ApplicationException(\"Fatal Error.\\n\");\n" + " }\n" + " }\n"); // /* Function: yy_next */ // outstream.Write("\tprivate int yy_next (int current,char lookahead) {\n" // + " return yy_nxt[yy_rmap[current],yy_cmap[lookahead]];\n" // + "\t}\n"); // /* Function: yy_accept */ // outstream.Write("\tprivate int yy_accept (int current) {\n"); // + " return yy_acpt[current];\n" // + "\t}\n"); outstream.WriteLine("#endregion"); } /* * Function: Header * Description: Emits class header. */ private void Header() { #if DEBUG Utility.assert(null != spec); Utility.assert(null != outstream); #endif outstream.Write("namespace " + spec.namespace_name + "\n{\n"); outstream.Write(spec.usercode); outstream.Write("/* test */\n"); outstream.Write("\n\n"); string spec_access = "internal "; if (spec.lex_public) spec_access = "public "; outstream.Write(spec_access + "class " + spec.class_name); if (spec.implements_name != null) { outstream.Write(" : "); outstream.Write(spec.implements_name); } outstream.Write("\n{\n"); } StringBuilder Accept_table() { int size = spec.accept_list.Count; int lastelem = size - 1; StringBuilder sb = new StringBuilder(Properties.Settings.Default.MaxStr); sb.Append(@" static int[] yy_acpt = new int[] {"); for (int elem = 0; elem < size; elem++) { sb.AppendFormat(@" /* {0} */ {1}{2}", elem, getAccept(elem), elem < lastelem ? "," : ""); } sb.Append(@" }; "); return sb; } string getAccept(int elem) { string s = " YY_NOT_ACCEPT"; // default to NOT Accept accept = (Accept)spec.accept_list[elem]; if (accept != null) { bool is_start = ((spec.anchor_array[elem] & Spec.START) != 0); bool is_end = ((spec.anchor_array[elem] & Spec.END) != 0); if (is_start && is_end) s = " YY_START | YY_END"; else if (is_start) s = " YY_START"; else if (is_end) s = " YY_END"; else s = " YY_NO_ANCHOR"; } return s; } StringBuilder CMap_table() { // int size = spec.col_map.Length; int size = spec.ccls_map.Length; int lastelem = size - 1; StringBuilder sb = new StringBuilder(); sb.Append(@" static int[] yy_cmap = new int[] {"); for (int i = 0; i < size; i++) { if (i%8 == 0) sb.AppendFormat(@" /* {0}-{1} */ ", i, i + 7); sb.Append(spec.col_map[spec.ccls_map[i]]); if (i < lastelem) sb.Append(", "); } sb.Append(@" }; "); return sb; } StringBuilder RMap_table() { int size = spec.row_map.Length; int lastelem = size - 1; StringBuilder sb = new StringBuilder(); sb.Append(@" static int[] yy_rmap = new int[] {"); for (int i = 0; i < size; ++i) { if (i % 8 == 0) sb.AppendFormat(@" /* {0}-{1} */ ", i, i + 7); sb.Append(spec.row_map[i]); if (i < lastelem) sb.Append(", "); } sb.Append(@" }; "); return sb; } StringBuilder YYNXT_table() { int size = spec.dtrans_list.Count; int lastelem = size - 1; int lastcol = spec.dtrans_ncols - 1; StringBuilder sb = new StringBuilder(); sb.Append(@" static int[,] yy_nxt = new int[,] {"); for (int elem = 0; elem < size; elem++) { DTrans cdt_list = (DTrans)spec.dtrans_list[elem]; #if DEBUG Utility.assert(spec.dtrans_ncols <= cdt_list.GetDTransLength()); #endif sb.Append(@" {"); for (int i = 0; i < spec.dtrans_ncols; i++) { if (i % 8 == 0) sb.AppendFormat(@" /* {0}-{1} */ ", i, i + 7); sb.Append(cdt_list.GetDTrans(i)); if (i < lastcol) sb.Append(", "); } sb.AppendFormat(@" }}{0}", elem < lastelem ? "," : ""); } sb.Append(@" }; "); return sb; } /* * Function: Table * Description: Emits transition table. */ private void Table() { #if DEBUG Utility.assert(null != spec); Utility.assert(null != outstream); #endif StringBuilder sb = new StringBuilder(); sb.Append(@" #region tables "); sb.Append(Accept_table()); sb.Append(CMap_table()); sb.Append(RMap_table()); sb.Append(YYNXT_table()); sb.Append(@" #endregion "); outstream.Write(sb); } string EOF_Test() { StringBuilder sb = new StringBuilder(); if (spec.eof_code != null) sb.AppendLine(" yy_do_eof();"); if (spec.integer_type) sb.AppendLine(" return YYEOF;"); else if (spec.eof_value_code != null) sb.Append(spec.eof_value_code); else sb.AppendLine(" return null;"); return sb.ToString(); } /* * Function: Driver * Description: */ void Driver() { #if DEBUG Utility.assert(null != spec); Utility.assert(null != outstream); #endif Table(); //string begin_str = ""; //string state_str = ""; #if NOT_EDBG begin_str = " System.Console.WriteLine(\"Begin\");\n"; state_str = " System.Console.WriteLine(\"\\n\\nCurrent state: \" + yy_state);\n" + " System.Console.Write(\"Lookahead input: " + " (\" + yy_lookahead + \")\");\n" + " if (yy_lookahead < 32)\n" + " System.Console.WriteLine(" + " \"'^\" + System.Convert.ToChar(yy_lookahead+'A'-1).ToString() + \"'\");\n" + " else if (yy_lookahead > 127)\n" + " System.Console.WriteLine(" + " \"'^\" + yy_lookahead + \"'\");\n" + " else\n" + " System.Console.WriteLine(" + " \"'\" + yy_lookahead.ToString() + \"'\");\n" + " System.Console.WriteLine(\"State = \"+ yy_state);\n" + " System.Console.WriteLine(\"Accepting status = \"+ yy_this_accept);\n" + " System.Console.WriteLine(\"Last accepting state = \"+ yy_last_accept_state);\n" + " System.Console.WriteLine(\"Next state = \"+ yy_next_state);\n" ; #endif var sb = new StringBuilder(); sb.AppendFormat(@" #region driver public {0} {1}() {{ char yy_lookahead; int yy_anchor = YY_NO_ANCHOR; int yy_state = yy_state_dtrans[yy_lexical_state]; int yy_next_state = YY_NO_STATE; int yy_last_accept_state = YY_NO_STATE; bool yy_initial = true; int yy_this_accept; yy_mark_start(); yy_this_accept = yy_acpt[yy_state]; if (YY_NOT_ACCEPT != yy_this_accept) {{ yy_last_accept_state = yy_state; yy_mark_end(); }} // begin_str while (true) {{ if (yy_initial && yy_at_bol) {{ yy_lookahead = (char)YY_BOL; }} else {{ yy_lookahead = yy_advance(); }} yy_next_state = yy_nxt[yy_rmap[yy_state], yy_cmap[yy_lookahead]]; // state_str if (YY_EOF == yy_lookahead && yy_initial) {{ // EOF_Test() {2} }} if (YY_F != yy_next_state) {{ yy_state = yy_next_state; yy_initial = false; yy_this_accept = yy_acpt[yy_state]; if (YY_NOT_ACCEPT != yy_this_accept) {{ yy_last_accept_state = yy_state; yy_mark_end(); }} }} else {{ if (YY_NO_STATE == yy_last_accept_state) {{ throw new ApplicationException(""Lexical Error: Unmatched Input.""); }} else {{ yy_anchor = yy_acpt[yy_last_accept_state]; if (0 != (YY_END & yy_anchor)) {{ yy_move_end(); }} yy_to_mark(); if (yy_last_accept_state< 0) {{ if (yy_last_accept_state< {3}) // spec.accept_list.Count yy_error(YY_E_INTERNAL, false); }} else {{ AcceptMethod m = accept_dispatch[yy_last_accept_state]; if (m != null) {{ Yytoken tmp = m(); // spec.type_name if (tmp != null) return tmp; }} }} yy_initial = true; yy_state = yy_state_dtrans[yy_lexical_state]; yy_next_state = YY_NO_STATE; yy_last_accept_state = YY_NO_STATE; yy_mark_start(); yy_this_accept = yy_acpt[yy_state]; if (YY_NOT_ACCEPT != yy_this_accept) {{ yy_last_accept_state = yy_state; yy_mark_end(); }} }} }} }} #endregion ", getDriverType(), spec.function_name, EOF_Test(), spec.accept_list.Count); outstream.Write(sb); } string getDriverType() { string type = spec.type_name; if (spec.integer_type) type = "int"; else if (spec.intwrap_type) type = "Int32"; return type; } /* * Function: Actions * Description: */ private string Actions() { int size = spec.accept_list.Count; int bogus_index = -2; Accept accept; StringBuilder sb = new StringBuilder(Properties.Settings.Default.MaxStr); #if DEBUG Utility.assert(spec.accept_list.Count == spec.anchor_array.Length); #endif string prefix = ""; for (int elem = 0; elem < size; elem++) { accept = (Accept)spec.accept_list[elem]; if (accept != null) { sb.Append(" " + prefix + "if (yy_last_accept_state == "); sb.Append(elem); sb.Append(")\n"); sb.Append(" { // begin accept action #"); sb.Append(elem); sb.Append("\n"); sb.Append(accept.action); sb.Append("\n"); sb.Append(" } // end accept action #"); sb.Append(elem); sb.Append("\n"); sb.Append(" else if (yy_last_accept_state == "); sb.Append(bogus_index); sb.Append(")\n"); sb.Append(" { /* no work */ }\n"); prefix = "else "; bogus_index--; } } return sb.ToString(); } string User_Init() { var s = string.Format(@" #region user init void userInit() {{ {0} }} #endregion ", spec.init_code == null ? "// no user init" : spec.init_code); return s; } private StringBuilder Action_Methods_Init() { int size = spec.accept_list.Count; Accept accept; StringBuilder tbl = new StringBuilder(); tbl.Append(@" #region action init void actionInit() { "); #if DEBUG Utility.assert(spec.accept_list.Count == spec.anchor_array.Length); #endif tbl.Append(@" accept_dispatch = new AcceptMethod[] { "); for (int elem = 0; elem < size; elem++) { accept = (Accept)spec.accept_list[elem]; if (accept != null && accept.action != null) { tbl.AppendFormat(@" new AcceptMethod(this.Accept_{0}), ", elem); } else tbl.Append(@" null, "); } tbl.Append(@" }; } #endregion "); return tbl; } /* * Function: Action_Methods_Body */ private StringBuilder Action_Methods_Body() { int size = spec.accept_list.Count; Accept accept; StringBuilder sb = new StringBuilder(Properties.Settings.Default.MaxStr); sb.Append(@" #region action methods "); #if DEBUG Utility.assert(spec.accept_list.Count == spec.anchor_array.Length); #endif for (int elem = 0; elem < size; elem++) { accept = (Accept)spec.accept_list[elem]; if (accept != null && accept.action != null) { sb.AppendFormat(@" {1} Accept_{0}() {2} ", elem, spec.type_name, accept.action); } } sb.Append(@" #endregion "); return sb; } /* * Function: Footer * Description: */ private void Footer() { #if DEBUG Utility.assert(null != spec); Utility.assert(null != outstream); #endif outstream.Write(@" } } "); } } }
/** * 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.Collections.Generic; using ArrayUtil = Lucene.Net.Util.ArrayUtil; using RAMOutputStream = Lucene.Net.Store.RAMOutputStream; namespace Lucene.Net.Index { /** This is a DocFieldConsumer that writes stored fields. */ internal sealed class StoredFieldsWriter : DocFieldConsumer { internal FieldsWriter fieldsWriter; internal readonly DocumentsWriter docWriter; internal int lastDocID; internal PerDoc[] docFreeList = new PerDoc[1]; internal int freeCount; public StoredFieldsWriter(DocumentsWriter docWriter) { this.docWriter = docWriter; } internal override DocFieldConsumerPerThread addThread(DocFieldProcessorPerThread docFieldProcessorPerThread) { return new StoredFieldsWriterPerThread(docFieldProcessorPerThread, this); } internal override void flush(IDictionary<object, ICollection<object>> threadsAndFields, DocumentsWriter.FlushState state) { lock (this) { if (state.numDocsInStore > 0) { // It's possible that all documents seen in this segment // hit non-aborting exceptions, in which case we will // not have yet init'd the FieldsWriter: initFieldsWriter(); // Fill fdx file to include any final docs that we // skipped because they hit non-aborting exceptions fill(state.numDocsInStore - docWriter.GetDocStoreOffset()); } if (fieldsWriter != null) fieldsWriter.Flush(); } } private void initFieldsWriter() { if (fieldsWriter == null) { string docStoreSegment = docWriter.GetDocStoreSegment(); if (docStoreSegment != null) { System.Diagnostics.Debug.Assert(docStoreSegment != null); fieldsWriter = new FieldsWriter(docWriter.directory, docStoreSegment, fieldInfos); docWriter.AddOpenFile(docStoreSegment + "." + IndexFileNames.FIELDS_EXTENSION); docWriter.AddOpenFile(docStoreSegment + "." + IndexFileNames.FIELDS_INDEX_EXTENSION); lastDocID = 0; } } } internal override void closeDocStore(DocumentsWriter.FlushState state) { lock (this) { int inc = state.numDocsInStore - lastDocID; if (inc > 0) { initFieldsWriter(); fill(state.numDocsInStore - docWriter.GetDocStoreOffset()); } if (fieldsWriter != null) { fieldsWriter.Close(); fieldsWriter = null; lastDocID = 0; System.Diagnostics.Debug.Assert(state.docStoreSegmentName != null); string fdtFile = state.docStoreSegmentName + "." + IndexFileNames.FIELDS_EXTENSION; string fdxFile = state.docStoreSegmentName + "." + IndexFileNames.FIELDS_INDEX_EXTENSION; state.flushedFiles[fdtFile] = fdtFile; state.flushedFiles[fdxFile] = fdxFile; state.docWriter.RemoveOpenFile(fdtFile); state.docWriter.RemoveOpenFile(fdxFile); if (4 + state.numDocsInStore * 8 != state.directory.FileLength(fdxFile)) throw new System.SystemException("after flush: fdx size mismatch: " + state.numDocsInStore + " docs vs " + state.directory.FileLength(fdxFile) + " length in bytes of " + fdxFile); } } } internal int allocCount; internal PerDoc getPerDoc() { lock (this) { if (freeCount == 0) { allocCount++; if (allocCount > docFreeList.Length) { // Grow our free list up front to make sure we have // enough space to recycle all outstanding PerDoc // instances System.Diagnostics.Debug.Assert(allocCount == 1 + docFreeList.Length); docFreeList = new PerDoc[ArrayUtil.GetNextSize(allocCount)]; } return new PerDoc(this); } else return docFreeList[--freeCount]; } } internal override void Abort() { lock (this) { if (fieldsWriter != null) { try { fieldsWriter.Close(); } catch (System.Exception) { } fieldsWriter = null; lastDocID = 0; } } } /** Fills in any hole in the docIDs */ internal void fill(int docID) { int docStoreOffset = docWriter.GetDocStoreOffset(); // We must "catch up" for all docs before us // that had no stored fields: int end = docID + docStoreOffset; while (lastDocID < end) { fieldsWriter.SkipDocument(); lastDocID++; } } internal void finishDocument(PerDoc perDoc) { lock (this) { System.Diagnostics.Debug.Assert(docWriter.writer.TestPoint("StoredFieldsWriter.finishDocument start")); initFieldsWriter(); fill(perDoc.docID); // Append stored fields to the real FieldsWriter: fieldsWriter.FlushDocument(perDoc.numStoredFields, perDoc.fdt); lastDocID++; perDoc.reset(); free(perDoc); System.Diagnostics.Debug.Assert(docWriter.writer.TestPoint("StoredFieldsWriter.finishDocument end")); } } internal override bool freeRAM() { return false; } internal void free(PerDoc perDoc) { lock (this) { System.Diagnostics.Debug.Assert(freeCount < docFreeList.Length); System.Diagnostics.Debug.Assert(0 == perDoc.numStoredFields); System.Diagnostics.Debug.Assert(0 == perDoc.fdt.Length()); System.Diagnostics.Debug.Assert(0 == perDoc.fdt.GetFilePointer()); docFreeList[freeCount++] = perDoc; } } internal class PerDoc : DocumentsWriter.DocWriter { // TODO: use something more memory efficient; for small // docs the 1024 buffer size of RAMOutputStream wastes alot internal RAMOutputStream fdt = new RAMOutputStream(); internal int numStoredFields; private StoredFieldsWriter enclosing_instance; internal PerDoc(StoredFieldsWriter enclosing_instance) { this.enclosing_instance = enclosing_instance; } internal void reset() { fdt.Reset(); numStoredFields = 0; } internal override void Abort() { reset(); enclosing_instance.free(this); } internal override long SizeInBytes() { return fdt.SizeInBytes(); } internal override void Finish() { enclosing_instance.finishDocument(this); } } } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.Collections.Generic; using System.Data; using System.Data.OleDb; using System.IO; namespace Revit.SDK.Samples.RoomSchedule { /// <summary> /// An integrated class to connect .xls data source, retrieve / update data /// </summary> class XlsDBConnector : IDisposable { #region Class Memeber Variables // The connection created private System.Data.OleDb.OleDbConnection m_objConn; // One command for this connection private OleDbCommand m_command; // The connection string private String m_connectStr; // All available tables(work sheets) in xls data source private List<String> m_tables = new List<String>(); #endregion #region Class Constructor & Destructor /// <summary> /// Class constructor, to retrieve data from .xls data source /// </summary> /// <param name="strXlsFile">The .xls file to be connected. /// This file should exist and it can be writable.</param> public XlsDBConnector(String strXlsFile) { // Validate the specified if (!ValidateFile(strXlsFile)) { throw new ArgumentException("The specified file doesn't exists or has readonly attribute.", strXlsFile); } // establish a connection to the data source. m_connectStr = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = \"" + strXlsFile + "\"; Extended Properties = \"Excel 8.0;HDR=YES;\""; // create the .xls connection m_objConn = new System.Data.OleDb.OleDbConnection(m_connectStr); m_objConn.Open(); } /// <summary> /// Close the OleDb connection /// </summary> public void Dispose() { if (null != m_objConn) { // close the OleDbConnection m_objConn.Close(); m_objConn = null; GC.SuppressFinalize(this); } } /// <summary> /// Finalizer, we need to ensure the connection was closed /// This destructor will run only if the Dispose method does not get called. /// </summary> ~XlsDBConnector() { Dispose(); } #endregion #region Class Member Methods /// <summary> /// Get all available table names from .xls data source /// </summary> public List<String> RetrieveAllTables() { // clear the old tables list firstly m_tables.Clear(); // get all table names from data source DataTable schemaTable = m_objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); for (int i = 0; i < schemaTable.Rows.Count; i++) { m_tables.Add(schemaTable.Rows[i].ItemArray[2].ToString().TrimEnd('$')); } return m_tables; } /// <summary> /// Generate a DataTable data from xls data source, by a specified table name /// </summary> /// <param name="tableName">Table name to be retrieved </param> /// <returns>The generated DataTable from work sheet</returns> public DataTable GenDataTable(String tableName) { // Get all data via command and then fill data to table string strCom = "Select * From [" + tableName + "$]"; OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, m_objConn); DataSet myDataSet = new DataSet(); myCommand.Fill(myDataSet, "[" + tableName + "$]"); try { // check to see whether the constant columns(defined in RoomsData class) exist in spread sheet. // These columns are necessary when updating spread sheet // define a flag variable to remember whether column is found // duplicate column is not allowed in spreadsheet bool[] bHasColumn = new bool[5]; Array.Clear(bHasColumn, 0, 5); // clear the variable to false // five constant columns which must exist and to be checked String[] constantNames = { RoomsData.RoomID, RoomsData.RoomName, RoomsData.RoomNumber, RoomsData.RoomArea, RoomsData.RoomComments }; // remember all duplicate columns, used to pop up error message String duplicateColumns = String.Empty; for (int i = 0; i < myDataSet.Tables[0].Columns.Count; i++) { // get each column and check it String columnName = myDataSet.Tables[0].Columns[i].ColumnName; // check whether there are expected columns one by one for (int col = 0; col < bHasColumn.Length; col++) { bool bDupliate = CheckSameColName(columnName, constantNames[col]); if (bDupliate) { if (false == bHasColumn[col]) { bHasColumn[col] = true; } else { // this column is duplicate, reserve it duplicateColumns += String.Format("[{0}], ", constantNames[col]); } } } } // check to see whether there are duplicate columns if (duplicateColumns.Length > 0) { // duplicate columns are not allowed String message = String.Format("There are duplicate column(s) in the spread sheet: {0}.", duplicateColumns); throw new Exception(message); } // check whether all required columns are there. String missingColumns = String.Empty; // reserve all column names which are missing. for (int col = 0; col < bHasColumn.Length; col++) { if (bHasColumn[col] == false) { missingColumns += String.Format("[{0}], ", constantNames[col]); } } // check to see whether any required columns are missing. if (missingColumns.Length != 0) { // some columns are missing, pop up these column names String message = String.Format("Required columns are missing: {0}.", missingColumns); throw new Exception(message); } // if no exception occurs, return the table of dataset directly return myDataSet.Tables[0]; } catch (Exception ex) { // throw exception throw new Exception(ex.Message); } } /// <summary> /// Execute SQL command, such as: update and insert /// </summary> /// <param name="strCmd">command to be executed</param> /// <returns>the number of rows affected by this command</returns> public int ExecuteCommnand(String strCmd) { try { if (null == m_command) { m_command = m_objConn.CreateCommand(); } m_command.CommandText = strCmd; return m_command.ExecuteNonQuery(); } catch (Exception ex) { throw new Exception(ex.ToString() + strCmd); } } #endregion #region Class Implementation /// <summary> /// This method will validate and update attributes the specified file. /// The file should exist and it should have writable attribute. /// If it's readonly, this method will try to set the attribute to writable. /// </summary> /// <param name="strFile"></param> /// <returns></returns> private bool ValidateFile(String strFile) { // exists check if(!File.Exists(strFile)) { return false; } // // writable attribute set File.SetAttributes(strFile, FileAttributes.Normal); return (FileAttributes.Normal == File.GetAttributes(strFile)); } /// <summary> /// Check if two columns names are the same /// </summary> /// <param name="baseName">first name</param> /// <param name="compName">second name</param> /// <returns>true, the two names are same; false, they are different.</returns> private static bool CheckSameColName(String baseName, String compName) { if (String.Compare(baseName, compName) == 0) { return true; } else { return false; } } #endregion }; }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) Under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You Under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed Under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations Under the License. ==================================================================== */ namespace NPOI.HSSF.Record { using System; using System.Text; using NPOI.Util; /** * Title: Row Record * Description: stores the row information for the sheet. * REFERENCE: PG 379 Microsoft Excel 97 Developer's Kit (ISBN: 1-57231-498-2) * @author Andrew C. Oliver (acoliver at apache dot org) * @author Jason Height (jheight at chariot dot net dot au) * @version 2.0-pre */ public class RowRecord : StandardRecord, IComparable { public const short sid = 0x208; public const int ENCODED_SIZE = 20; private const int OPTION_BITS_ALWAYS_SET = 0x0100; //private const int DEFAULT_HEIGHT_BIT = 0x8000; /** The maximum row number that excel can handle (zero based) ie 65536 rows Is * max number of rows. */ [Obsolete] public const int MAX_ROW_NUMBER = 65535; private int field_1_row_number; private int field_2_first_col; private int field_3_last_col; // plus 1 private short field_4_height; private short field_5_optimize; // hint field for gui, can/should be Set to zero // for generated sheets. private short field_6_reserved; /** 16 bit options flags */ private int field_7_option_flags; private static BitField outlineLevel = BitFieldFactory.GetInstance(0x07); // bit 3 reserved private static BitField colapsed = BitFieldFactory.GetInstance(0x10); private static BitField zeroHeight = BitFieldFactory.GetInstance(0x20); private static BitField badFontHeight = BitFieldFactory.GetInstance(0x40); private static BitField formatted = BitFieldFactory.GetInstance(0x80); private int field_8_option_flags; // only if isFormatted private static BitField xfIndex = BitFieldFactory.GetInstance(0xFFF); private static BitField topBorder = BitFieldFactory.GetInstance(0x1000); private static BitField bottomBorder = BitFieldFactory.GetInstance(0x2000); private static BitField phoeneticGuide = BitFieldFactory.GetInstance(0x4000); public RowRecord(int rowNumber) { if (rowNumber < 0) { throw new ArgumentException("Invalid row number (" + rowNumber + ")"); } field_1_row_number = rowNumber; //field_2_first_col = -1; //field_3_last_col = -1; field_4_height = (short)0x00FF; field_5_optimize = (short)0; field_6_reserved = (short)0; field_7_option_flags = OPTION_BITS_ALWAYS_SET; // seems necessary for outlining field_8_option_flags = (short)0xf; SetEmpty(); } /** * Constructs a Row record and Sets its fields appropriately. * @param in the RecordInputstream to Read the record from */ public RowRecord(RecordInputStream in1) { field_1_row_number = in1.ReadUShort(); if (field_1_row_number < 0) { throw new ArgumentException("Invalid row number " + field_1_row_number + " found in InputStream"); } field_2_first_col = in1.ReadShort(); field_3_last_col = in1.ReadShort(); field_4_height = in1.ReadShort(); field_5_optimize = in1.ReadShort(); field_6_reserved = in1.ReadShort(); field_7_option_flags = in1.ReadShort(); field_8_option_flags = in1.ReadShort(); } public void SetEmpty() { field_2_first_col = 0; field_3_last_col = 0; } /** * Get the logical row number for this row (0 based index) * @return row - the row number */ public bool IsEmpty { get { return (field_2_first_col | field_3_last_col) == 0; } } //public short RowNumber public int RowNumber { get { return field_1_row_number; } set { field_1_row_number = value; } } /** * Get the logical col number for the first cell this row (0 based index) * @return col - the col number */ public int FirstCol { get{return field_2_first_col;} set { field_2_first_col = value; } } /** * Get the logical col number for the last cell this row plus one (0 based index) * @return col - the last col number + 1 */ public int LastCol { get { return field_3_last_col; } set { field_3_last_col = value; } } /** * Get the height of the row * @return height of the row */ public short Height { get{return field_4_height;} set { field_4_height = value; } } /** * Get whether to optimize or not (Set to 0) * @return optimize (Set to 0) */ public short Optimize { get { return field_5_optimize; } set { field_5_optimize = value; } } /** * Gets the option bitmask. (use the individual bit Setters that refer to this * method) * @return options - the bitmask */ public short OptionFlags { get { return (short)field_7_option_flags; } set { field_7_option_flags = value | (short)OPTION_BITS_ALWAYS_SET; } } // option bitfields /** * Get the outline level of this row * @return ol - the outline level * @see #GetOptionFlags() */ public short OutlineLevel { get { return (short)outlineLevel.GetValue(field_7_option_flags); } set { field_7_option_flags = outlineLevel.SetValue(field_7_option_flags, value); } } /** * Get whether or not to colapse this row * @return c - colapse or not * @see #GetOptionFlags() */ public bool Colapsed { get { return (colapsed.IsSet(field_7_option_flags)); } set { field_7_option_flags = colapsed.SetBoolean(field_7_option_flags, value); } } /** * Get whether or not to Display this row with 0 height * @return - z height is zero or not. * @see #GetOptionFlags() */ public bool ZeroHeight { get { return zeroHeight.IsSet(field_7_option_flags); } set { field_7_option_flags = zeroHeight.SetBoolean(field_7_option_flags, value); } } /** * Get whether the font and row height are not compatible * @return - f -true if they aren't compatible (damn not logic) * @see #GetOptionFlags() */ public bool BadFontHeight { get { return badFontHeight.IsSet(field_7_option_flags); } set { field_7_option_flags = badFontHeight.SetBoolean(field_7_option_flags, value); } } /** * Get whether the row has been formatted (even if its got all blank cells) * @return formatted or not * @see #GetOptionFlags() */ public bool Formatted { get { return formatted.IsSet(field_7_option_flags); } set { field_7_option_flags = formatted.SetBoolean(field_7_option_flags, value); } } // end bitfields public short OptionFlags2 { get { return (short)this.field_8_option_flags; } } /** * if the row is formatted then this is the index to the extended format record * @see org.apache.poi.hssf.record.ExtendedFormatRecord * @return index to the XF record or bogus value (undefined) if Isn't formatted */ public short XFIndex { get { return xfIndex.GetShortValue((short)field_8_option_flags); } set { field_8_option_flags = xfIndex.SetValue(field_8_option_flags, value); } } /** * bit that specifies whether any cell in the row has a thick top border, or any * cell in the row directly above the current row has a thick bottom border. * @param f has thick top border */ public bool TopBorder { get { return topBorder.IsSet(field_8_option_flags); } set { field_8_option_flags = topBorder.SetBoolean(field_8_option_flags, value); } } /** * A bit that specifies whether any cell in the row has a medium or thick * bottom border, or any cell in the row directly below the current row has * a medium or thick top border. * @param f has thick bottom border */ public bool BottomBorder { get { return bottomBorder.IsSet(field_8_option_flags); } set { field_8_option_flags = bottomBorder.SetBoolean(field_8_option_flags, value); } } /** * A bit that specifies whether the phonetic guide feature is enabled for * any cell in this row. * @param f use phoenetic guide */ public bool PhoeneticGuide { get { return phoeneticGuide.IsSet(field_8_option_flags); } set { field_8_option_flags = phoeneticGuide.SetBoolean(field_8_option_flags, value); } } public override String ToString() { StringBuilder buffer = new StringBuilder(); buffer.Append("[ROW]\n"); buffer.Append(" .rownumber = ").Append(StringUtil.ToHexString(RowNumber)).Append("\n"); buffer.Append(" .firstcol = ").Append(StringUtil.ToHexString(FirstCol)).Append("\n"); buffer.Append(" .lastcol = ").Append(StringUtil.ToHexString(LastCol)).Append("\n"); buffer.Append(" .height = ").Append(StringUtil.ToHexString(Height)).Append("\n"); buffer.Append(" .optimize = ").Append(StringUtil.ToHexString(Optimize)).Append("\n"); buffer.Append(" .reserved = ").Append(StringUtil.ToHexString(field_6_reserved)).Append("\n"); buffer.Append(" .optionflags = ").Append(StringUtil.ToHexString(OptionFlags)).Append("\n"); buffer.Append(" .outlinelvl = ").Append(StringUtil.ToHexString(OutlineLevel)).Append("\n"); buffer.Append(" .colapsed = ").Append(Colapsed).Append("\n"); buffer.Append(" .zeroheight = ").Append(ZeroHeight).Append("\n"); buffer.Append(" .badfontheig= ").Append(BadFontHeight).Append("\n"); buffer.Append(" .formatted = ").Append(Formatted).Append("\n"); buffer.Append(" .optionsflags2 = ").Append(StringUtil.ToHexString(OptionFlags2)).Append("\n"); buffer.Append(" .xFindex = ").Append(StringUtil.ToHexString(XFIndex)).Append("\n"); buffer.Append(" .topBorder = ").Append(TopBorder).Append("\n"); buffer.Append(" .bottomBorder = ").Append(BottomBorder).Append("\n"); buffer.Append(" .phoeneticGuide= ").Append(PhoeneticGuide).Append("\n"); buffer.Append("[/ROW]\n"); return buffer.ToString(); } public override void Serialize(ILittleEndianOutput out1) { out1.WriteShort(RowNumber); out1.WriteShort(FirstCol == -1 ? (short)0 : FirstCol); out1.WriteShort(LastCol == -1 ? (short)0 : LastCol); out1.WriteShort(Height); out1.WriteShort(Optimize); out1.WriteShort(field_6_reserved); out1.WriteShort(OptionFlags); out1.WriteShort(OptionFlags2); } protected override int DataSize { get { return ENCODED_SIZE - 4; } } public override int RecordSize { get { return 20; } } public override short Sid { get { return sid; } } public int CompareTo(Object obj) { RowRecord loc = (RowRecord)obj; if (this.RowNumber == loc.RowNumber) { return 0; } if (this.RowNumber < loc.RowNumber) { return -1; } if (this.RowNumber > loc.RowNumber) { return 1; } return -1; } public override bool Equals(Object obj) { if (!(obj is RowRecord)) { return false; } RowRecord loc = (RowRecord)obj; if (this.RowNumber == loc.RowNumber) { return true; } return false; } public override int GetHashCode () { return RowNumber; } public override Object Clone() { RowRecord rec = new RowRecord(field_1_row_number); rec.field_2_first_col = field_2_first_col; rec.field_3_last_col = field_3_last_col; rec.field_4_height = field_4_height; rec.field_5_optimize = field_5_optimize; rec.field_6_reserved = field_6_reserved; rec.field_7_option_flags = field_7_option_flags; rec.field_8_option_flags = field_8_option_flags; return rec; } } }
// // 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. // IMPORTANT: This code was machine generated and then modified by humans. // Updating this file with the machine generated one might overwrite important changes. // Please review and revert unintended changes carefully. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Xml; using Hyak.Common; using Microsoft.Azure.Insights.Legacy; using Microsoft.Azure.Insights.Legacy.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Insights.Legacy { /// <summary> /// Operations for metric values. /// </summary> internal partial class MetricOperations : IServiceOperations<InsightsClient>, IMetricOperations { /// <summary> /// Initializes a new instance of the MetricOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal MetricOperations(InsightsClient client) { this._client = client; } private InsightsClient _client; /// <summary> /// Gets a reference to the Microsoft.Azure.Insights.Legacy.InsightsClient. /// </summary> public InsightsClient Client { get { return this._client; } } /// <summary> /// The List Metric operation lists the metric value sets for the /// resource metrics. /// </summary> /// <param name='resourceUri'> /// Required. The resource identifier of the target resource to get /// metrics for. /// </param> /// <param name='filterString'> /// Optional. An OData $filter expression that supports querying by the /// name, startTime, endTime and timeGrain of the metric value sets. /// For example, "(name.value eq 'Percentage CPU') and startTime eq /// 2014-07-02T01:00Z and endTime eq 2014-08-21T01:00:00Z and /// timeGrain eq duration'PT1H'". In the expression, startTime, /// endTime and timeGrain are required. Name is optional. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Metric values operation response. /// </returns> public async Task<MetricListResponse> GetMetricsInternalAsync(string resourceUri, string filterString, CancellationToken cancellationToken) { // Validate if (resourceUri == null) { throw new ArgumentNullException("resourceUri"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceUri", resourceUri); tracingParameters.Add("filterString", filterString); TracingAdapter.Enter(invocationId, this, "GetMetricsAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; url = url + resourceUri; url = url + "/metrics"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); List<string> odataFilter = new List<string>(); if (filterString != null) { odataFilter.Add(Uri.EscapeDataString(filterString)); } if (odataFilter.Count > 0) { queryParameters.Add("$filter=" + string.Join(null, odataFilter)); } if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-04-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result MetricListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new MetricListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { MetricCollection metricCollectionInstance = new MetricCollection(); result.MetricCollection = metricCollectionInstance; JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Metric metricInstance = new Metric(); metricCollectionInstance.Value.Add(metricInstance); JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { LocalizableString nameInstance = new LocalizableString(); metricInstance.Name = nameInstance; JToken valueValue2 = nameValue["value"]; if (valueValue2 != null && valueValue2.Type != JTokenType.Null) { string valueInstance = ((string)valueValue2); nameInstance.Value = valueInstance; } JToken localizedValueValue = nameValue["localizedValue"]; if (localizedValueValue != null && localizedValueValue.Type != JTokenType.Null) { string localizedValueInstance = ((string)localizedValueValue); nameInstance.LocalizedValue = localizedValueInstance; } } JToken unitValue = valueValue["unit"]; if (unitValue != null && unitValue.Type != JTokenType.Null) { Unit unitInstance = ((Unit)Enum.Parse(typeof(Unit), ((string)unitValue), true)); metricInstance.Unit = unitInstance; } JToken timeGrainValue = valueValue["timeGrain"]; if (timeGrainValue != null && timeGrainValue.Type != JTokenType.Null) { TimeSpan timeGrainInstance = XmlConvert.ToTimeSpan(((string)timeGrainValue)); metricInstance.TimeGrain = timeGrainInstance; } JToken startTimeValue = valueValue["startTime"]; if (startTimeValue != null && startTimeValue.Type != JTokenType.Null) { DateTime startTimeInstance = ((DateTime)startTimeValue); metricInstance.StartTime = startTimeInstance; } JToken endTimeValue = valueValue["endTime"]; if (endTimeValue != null && endTimeValue.Type != JTokenType.Null) { DateTime endTimeInstance = ((DateTime)endTimeValue); metricInstance.EndTime = endTimeInstance; } JToken metricValuesArray = valueValue["metricValues"]; if (metricValuesArray != null && metricValuesArray.Type != JTokenType.Null) { foreach (JToken metricValuesValue in ((JArray)metricValuesArray)) { MetricValue metricValueInstance = new MetricValue(); metricInstance.MetricValues.Add(metricValueInstance); JToken timestampValue = metricValuesValue["timestamp"]; if (timestampValue != null && timestampValue.Type != JTokenType.Null) { DateTime timestampInstance = ((DateTime)timestampValue); metricValueInstance.Timestamp = timestampInstance; } JToken averageValue = metricValuesValue["average"]; if (averageValue != null && averageValue.Type != JTokenType.Null) { double averageInstance = ((double)averageValue); metricValueInstance.Average = averageInstance; } JToken minimumValue = metricValuesValue["minimum"]; if (minimumValue != null && minimumValue.Type != JTokenType.Null) { double minimumInstance = ((double)minimumValue); metricValueInstance.Minimum = minimumInstance; } JToken maximumValue = metricValuesValue["maximum"]; if (maximumValue != null && maximumValue.Type != JTokenType.Null) { double maximumInstance = ((double)maximumValue); metricValueInstance.Maximum = maximumInstance; } JToken totalValue = metricValuesValue["total"]; if (totalValue != null && totalValue.Type != JTokenType.Null) { double totalInstance = ((double)totalValue); metricValueInstance.Total = totalInstance; } JToken countValue = metricValuesValue["count"]; if (countValue != null && countValue.Type != JTokenType.Null) { long countInstance = ((long)countValue); metricValueInstance.Count = countInstance; } JToken lastValue = metricValuesValue["last"]; if (lastValue != null && lastValue.Type != JTokenType.Null) { double lastInstance = ((double)lastValue); metricValueInstance.Last = lastInstance; } JToken propertiesSequenceElement = ((JToken)metricValuesValue["properties"]); if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in propertiesSequenceElement) { string propertiesKey = ((string)property.Name); string propertiesValue = ((string)property.Value); metricValueInstance.Properties.Add(propertiesKey, propertiesValue); } } } } JToken resourceIdValue = valueValue["resourceId"]; if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null) { string resourceIdInstance = ((string)resourceIdValue); metricInstance.ResourceId = resourceIdInstance; } JToken propertiesSequenceElement2 = ((JToken)valueValue["properties"]); if (propertiesSequenceElement2 != null && propertiesSequenceElement2.Type != JTokenType.Null) { foreach (JProperty property2 in propertiesSequenceElement2) { string propertiesKey2 = ((string)property2.Name); string propertiesValue2 = ((string)property2.Value); metricInstance.Properties.Add(propertiesKey2, propertiesValue2); } } JToken dimensionNameValue = valueValue["dimensionName"]; if (dimensionNameValue != null && dimensionNameValue.Type != JTokenType.Null) { LocalizableString dimensionNameInstance = new LocalizableString(); metricInstance.DimensionName = dimensionNameInstance; JToken valueValue3 = dimensionNameValue["value"]; if (valueValue3 != null && valueValue3.Type != JTokenType.Null) { string valueInstance2 = ((string)valueValue3); dimensionNameInstance.Value = valueInstance2; } JToken localizedValueValue2 = dimensionNameValue["localizedValue"]; if (localizedValueValue2 != null && localizedValueValue2.Type != JTokenType.Null) { string localizedValueInstance2 = ((string)localizedValueValue2); dimensionNameInstance.LocalizedValue = localizedValueInstance2; } } JToken dimensionValueValue = valueValue["dimensionValue"]; if (dimensionValueValue != null && dimensionValueValue.Type != JTokenType.Null) { LocalizableString dimensionValueInstance = new LocalizableString(); metricInstance.DimensionValue = dimensionValueInstance; JToken valueValue4 = dimensionValueValue["value"]; if (valueValue4 != null && valueValue4.Type != JTokenType.Null) { string valueInstance3 = ((string)valueValue4); dimensionValueInstance.Value = valueInstance3; } JToken localizedValueValue3 = dimensionValueValue["localizedValue"]; if (localizedValueValue3 != null && localizedValueValue3.Type != JTokenType.Null) { string localizedValueInstance3 = ((string)localizedValueValue3); dimensionValueInstance.LocalizedValue = localizedValueInstance3; } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // // Licensed under the MIT license. using System; using System.Collections; using System.Reflection; using Microsoft.AppCenter.Unity.Internal; using UnityEngine; using System.Runtime.InteropServices; namespace Microsoft.AppCenter.Unity { #if UNITY_IOS || UNITY_ANDROID using ServiceType = System.IntPtr; #else using ServiceType = System.Type; #endif public class AppCenter { private static AppCenterTask<string> _secretTask = new AppCenterTask<string>(); private static AppCenterTask<string> _logUrlTask = new AppCenterTask<string>(); private static AppCenterTask<long> _storageSizeTask = new AppCenterTask<long>(); public static LogLevel LogLevel { get { return (LogLevel)AppCenterInternal.GetLogLevel(); } set { AppCenterInternal.SetLogLevel((int)value); } } public static AppCenterTask SetEnabledAsync(bool enabled) { return AppCenterInternal.SetEnabledAsync(enabled); } public static void StartFromLibrary(Type[] servicesArray) { AppCenterInternal.StartFromLibrary(AppCenterInternal.ServicesToNativeTypes(servicesArray)); } public static AppCenterTask<bool> IsEnabledAsync() { return AppCenterInternal.IsEnabledAsync(); } /// <summary> /// Get the unique installation identifier for this application installation on this device. /// </summary> /// <remarks> /// The identifier is lost if clearing application data or uninstalling application. /// </remarks> public static AppCenterTask<Guid?> GetInstallIdAsync() { var stringTask = AppCenterInternal.GetInstallIdAsync(); var guidTask = new AppCenterTask<Guid?>(); stringTask.ContinueWith(t => { var installId = !string.IsNullOrEmpty(t.Result) ? new Guid(t.Result) : (Guid?)null; guidTask.SetResult(installId); }); return guidTask; } public static string GetSdkVersion() { return AppCenterInternal.GetSdkVersion(); } public static AppCenterTask<string> GetLogUrl() { if (_logUrlTask == null) { _logUrlTask = new AppCenterTask<string>(); } return _logUrlTask; } public static AppCenterTask<long> GetStorageSize() { if (_storageSizeTask == null) { _storageSizeTask = new AppCenterTask<long>(); } return _storageSizeTask; } /// <summary> /// Change the base URL (scheme + authority + port only) used to communicate with the backend. /// </summary> /// <param name="logUrl">Base URL to use for server communication.</param> public static void SetLogUrl(string logUrl) { AppCenterInternal.SetLogUrl(logUrl); } public static void CacheStorageSize(long storageSize) { if (_storageSizeTask != null) { _storageSizeTask.SetResult(storageSize); } } public static void CacheLogUrl(string logUrl) { if (_logUrlTask != null) { _logUrlTask.SetResult(logUrl); } } /// <summary> /// Check whether SDK has already been configured or not. /// </summary> public static bool Configured { get { return AppCenterInternal.IsConfigured(); } } /// <summary> /// Set the custom properties. /// </summary> /// <param name="customProperties">Custom properties object.</param> public static void SetCustomProperties(Unity.CustomProperties customProperties) { var rawCustomProperties = customProperties.GetRawObject(); AppCenterInternal.SetCustomProperties(rawCustomProperties); } public static void SetWrapperSdk() { AppCenterInternal.SetWrapperSdk(WrapperSdk.WrapperSdkVersion, WrapperSdk.Name, WrapperSdk.WrapperRuntimeVersion, null, null, null); } /// <summary> // Gets cached secret. /// </summary> public static AppCenterTask<string> GetSecretForPlatform() { if (_secretTask == null) { _secretTask = new AppCenterTask<string>(); } return _secretTask; } // Gets the first instance of an app secret corresponding to the given platform name, or returns the string // as-is if no identifier can be found. public static string ParseAndSaveSecretForPlatform(string secrets) { var platformIdentifier = GetPlatformIdentifier(); if (platformIdentifier == null) { // Return as is for unsupported platform. return secrets; } if (secrets == null) { // If "secrets" is null, return that and let the error be dealt // with downstream. return secrets; } // If there are no equals signs, then there are no named identifiers if (!secrets.Contains("=")) { return secrets; } var platformIndicator = platformIdentifier + "="; var secretIdx = secrets.IndexOf(platformIndicator, StringComparison.Ordinal); if (secretIdx == -1) { // If the platform indicator can't be found, return the original // string and let the error be dealt with downstream. return secrets; } secretIdx += platformIndicator.Length; var platformSecret = string.Empty; while (secretIdx < secrets.Length) { var nextChar = secrets[secretIdx++]; if (nextChar == ';') { break; } platformSecret += nextChar; } if (_secretTask != null) { _secretTask.SetResult(platformSecret); } return platformSecret; } public static void SetUserId(string userId) { AppCenterInternal.SetUserId(userId); } #if ENABLE_IL2CPP [UnmanagedFunctionPointer(CallingConvention.Cdecl)] #endif public delegate void SetMaxStorageSizeCompletionHandler(bool result); private static string GetPlatformIdentifier() { #if UNITY_IOS return "ios"; #elif UNITY_ANDROID return "android"; #elif UNITY_WSA_10_0 return "uwp"; #else return null; #endif } public static Type Analytics { get { return AppCenterAssembly.GetType("Microsoft.AppCenter.Unity.Analytics.Analytics"); } } public static Type Crashes { get { return AppCenterAssembly.GetType("Microsoft.AppCenter.Unity.Crashes.Crashes"); } } public static Type Distribute { get { return AppCenterAssembly.GetType("Microsoft.AppCenter.Unity.Distribute.Distribute"); } } public static Type Push { get { return AppCenterAssembly.GetType("Microsoft.AppCenter.Unity.Push.Push"); } } private static Assembly AppCenterAssembly { get { #if !UNITY_EDITOR && UNITY_WSA_10_0 return typeof(AppCenterSettings).GetTypeInfo().Assembly; #else return Assembly.GetExecutingAssembly(); #endif } } } }
using Microsoft.TeamFoundation.TestManagement.WebApi; using Microsoft.VisualStudio.Services.Agent.Util; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.Services.WebApi; namespace Microsoft.VisualStudio.Services.Agent.Worker.CodeCoverage { public sealed class CodeCoverageCommandExtension : AgentService, IWorkerCommandExtension { private int _buildId; // publish code coverage inputs private string _summaryFileLocation; private List<string> _additionalCodeCoverageFiles; private string _codeCoverageTool; private string _reportDirectory; public HostTypes SupportedHostTypes => HostTypes.Build; public void ProcessCommand(IExecutionContext context, Command command) { if (string.Equals(command.Event, WellKnownResultsCommand.PublishCodeCoverage, StringComparison.OrdinalIgnoreCase)) { ProcessPublishCodeCoverageCommand(context, command.Properties); } else if (string.Equals(command.Event, WellKnownResultsCommand.EnableCodeCoverage, StringComparison.OrdinalIgnoreCase)) { ProcessEnableCodeCoverageCommand(context, command.Properties); } else { throw new Exception(StringUtil.Loc("CodeCoverageCommandNotFound", command.Event)); } } public Type ExtensionType { get { return typeof(IWorkerCommandExtension); } } public string CommandArea { get { return "codecoverage"; } } #region enable code coverage helper methods private void ProcessEnableCodeCoverageCommand(IExecutionContext context, Dictionary<string, string> eventProperties) { string codeCoverageTool; eventProperties.TryGetValue(EnableCodeCoverageEventProperties.CodeCoverageTool, out codeCoverageTool); if (string.IsNullOrWhiteSpace(codeCoverageTool)) { // no code coverage tool specified. Dont enable code coverage. return; } codeCoverageTool = codeCoverageTool.Trim(); string buildTool; eventProperties.TryGetValue(EnableCodeCoverageEventProperties.BuildTool, out buildTool); if (string.IsNullOrEmpty(buildTool)) { throw new ArgumentException(StringUtil.Loc("ArgumentNeeded", "BuildTool")); } buildTool = buildTool.Trim(); var codeCoverageInputs = new CodeCoverageEnablerInputs(context, buildTool, eventProperties); ICodeCoverageEnabler ccEnabler = GetCodeCoverageEnabler(buildTool, codeCoverageTool); ccEnabler.EnableCodeCoverage(context, codeCoverageInputs); } private ICodeCoverageEnabler GetCodeCoverageEnabler(string buildTool, string codeCoverageTool) { var extensionManager = HostContext.GetService<IExtensionManager>(); ICodeCoverageEnabler codeCoverageEnabler = (extensionManager.GetExtensions<ICodeCoverageEnabler>()).FirstOrDefault( x => x.Name.Equals(codeCoverageTool + "_" + buildTool, StringComparison.OrdinalIgnoreCase)); if (codeCoverageEnabler == null) { throw new ArgumentException(StringUtil.Loc("InvalidBuildOrCoverageTool", buildTool, codeCoverageTool)); } return codeCoverageEnabler; } #endregion #region publish code coverage helper methods private void ProcessPublishCodeCoverageCommand(IExecutionContext context, Dictionary<string, string> eventProperties) { ArgUtil.NotNull(context, nameof(context)); _buildId = context.Variables.Build_BuildId ?? -1; if (!IsHostTypeBuild(context) || _buildId < 0) { //In case the publishing codecoverage is not applicable for current Host type we continue without publishing context.Warning(StringUtil.Loc("CodeCoveragePublishIsValidOnlyForBuild")); return; } LoadPublishCodeCoverageInputs(eventProperties); string project = context.Variables.System_TeamProject; long? containerId = context.Variables.Build_ContainerId; ArgUtil.NotNull(containerId, nameof(containerId)); Guid projectId = context.Variables.System_TeamProjectId ?? Guid.Empty; ArgUtil.NotEmpty(projectId, nameof(projectId)); //step 1: read code coverage summary var reader = GetCodeCoverageSummaryReader(_codeCoverageTool); context.Output(StringUtil.Loc("ReadingCodeCoverageSummary", _summaryFileLocation)); var coverageData = reader.GetCodeCoverageSummary(context, _summaryFileLocation); if (coverageData == null || coverageData.Count() == 0) { context.Warning(StringUtil.Loc("CodeCoverageDataIsNull")); } VssConnection connection = WorkerUtilities.GetVssConnection(context); var codeCoveragePublisher = HostContext.GetService<ICodeCoveragePublisher>(); codeCoveragePublisher.InitializePublisher(_buildId, connection); var commandContext = HostContext.CreateService<IAsyncCommandContext>(); commandContext.InitializeCommandContext(context, StringUtil.Loc("PublishCodeCoverage")); commandContext.Task = PublishCodeCoverageAsync(context, commandContext, codeCoveragePublisher, coverageData, project, projectId, containerId.Value, context.CancellationToken); context.AsyncCommands.Add(commandContext); } private async Task PublishCodeCoverageAsync( IExecutionContext executionContext, IAsyncCommandContext commandContext, ICodeCoveragePublisher codeCoveragePublisher, IEnumerable<CodeCoverageStatistics> coverageData, string project, Guid projectId, long containerId, CancellationToken cancellationToken) { //step 2: publish code coverage summary to TFS if (coverageData != null && coverageData.Count() > 0) { commandContext.Output(StringUtil.Loc("PublishingCodeCoverage")); foreach (var coverage in coverageData) { commandContext.Output(StringUtil.Format(" {0}- {1} of {2} covered.", coverage.Label, coverage.Covered, coverage.Total)); } await codeCoveragePublisher.PublishCodeCoverageSummaryAsync(coverageData, project, cancellationToken); } // step 3: publish code coverage files as build artifacts string additionalCodeCoverageFilePath = null; string destinationSummaryFile = null; var newReportDirectory = _reportDirectory; try { var filesToPublish = new List<Tuple<string, string>>(); if (!Directory.Exists(newReportDirectory)) { if (!string.IsNullOrWhiteSpace(newReportDirectory)) { // user gave a invalid report directory. Write warning and continue. executionContext.Warning(StringUtil.Loc("DirectoryNotFound", newReportDirectory)); } newReportDirectory = GetCoverageDirectory(_buildId.ToString(), CodeCoverageConstants.ReportDirectory); Directory.CreateDirectory(newReportDirectory); } var summaryFileName = Path.GetFileName(_summaryFileLocation); destinationSummaryFile = Path.Combine(newReportDirectory, CodeCoverageConstants.SummaryFileDirectory + _buildId, summaryFileName); Directory.CreateDirectory(Path.GetDirectoryName(destinationSummaryFile)); File.Copy(_summaryFileLocation, destinationSummaryFile, true); commandContext.Output(StringUtil.Loc("ModifyingCoberturaIndexFile")); ModifyCoberturaIndexDotHTML(newReportDirectory, executionContext); filesToPublish.Add(new Tuple<string, string>(newReportDirectory, GetCoverageDirectoryName(_buildId.ToString(), CodeCoverageConstants.ReportDirectory))); if (_additionalCodeCoverageFiles != null && _additionalCodeCoverageFiles.Count != 0) { additionalCodeCoverageFilePath = GetCoverageDirectory(_buildId.ToString(), CodeCoverageConstants.RawFilesDirectory); CodeCoverageUtilities.CopyFilesFromFileListWithDirStructure(_additionalCodeCoverageFiles, ref additionalCodeCoverageFilePath); filesToPublish.Add(new Tuple<string, string>(additionalCodeCoverageFilePath, GetCoverageDirectoryName(_buildId.ToString(), CodeCoverageConstants.RawFilesDirectory))); } commandContext.Output(StringUtil.Loc("PublishingCodeCoverageFiles")); ChangeHtmExtensionToHtmlIfRequired(newReportDirectory, executionContext); await codeCoveragePublisher.PublishCodeCoverageFilesAsync(commandContext, projectId, containerId, filesToPublish, File.Exists(Path.Combine(newReportDirectory, CodeCoverageConstants.DefaultIndexFile)), cancellationToken); } catch (IOException ex) { executionContext.Warning(StringUtil.Loc("ErrorOccurredWhilePublishingCCFiles", ex.Message)); } finally { // clean temporary files. if (!string.IsNullOrEmpty(additionalCodeCoverageFilePath)) { if (Directory.Exists(additionalCodeCoverageFilePath)) { Directory.Delete(path: additionalCodeCoverageFilePath, recursive: true); } } if (!string.IsNullOrEmpty(destinationSummaryFile)) { var summaryFileDirectory = Path.GetDirectoryName(destinationSummaryFile); if (Directory.Exists(summaryFileDirectory)) { Directory.Delete(path: summaryFileDirectory, recursive: true); } } if (!Directory.Exists(_reportDirectory)) { if (Directory.Exists(newReportDirectory)) { //delete the generated report directory Directory.Delete(path: newReportDirectory, recursive: true); } } } } private ICodeCoverageSummaryReader GetCodeCoverageSummaryReader(string codeCoverageTool) { var extensionManager = HostContext.GetService<IExtensionManager>(); ICodeCoverageSummaryReader summaryReader = (extensionManager.GetExtensions<ICodeCoverageSummaryReader>()).FirstOrDefault(x => codeCoverageTool.Equals(x.Name, StringComparison.OrdinalIgnoreCase)); if (summaryReader == null) { throw new ArgumentException(StringUtil.Loc("UnknownCodeCoverageTool", codeCoverageTool)); } return summaryReader; } private bool IsHostTypeBuild(IExecutionContext context) { var hostType = context.Variables.System_HostType; if (hostType.HasFlag(HostTypes.Build)) { return true; } return false; } private void LoadPublishCodeCoverageInputs(Dictionary<string, string> eventProperties) { //validate codecoverage tool input eventProperties.TryGetValue(PublishCodeCoverageEventProperties.CodeCoverageTool, out _codeCoverageTool); if (string.IsNullOrEmpty(_codeCoverageTool)) { throw new ArgumentException(StringUtil.Loc("ArgumentNeeded", "CodeCoverageTool")); } //validate summary file input eventProperties.TryGetValue(PublishCodeCoverageEventProperties.SummaryFile, out _summaryFileLocation); if (string.IsNullOrEmpty(_summaryFileLocation)) { throw new ArgumentException(StringUtil.Loc("ArgumentNeeded", "SummaryFile")); } eventProperties.TryGetValue(PublishCodeCoverageEventProperties.ReportDirectory, out _reportDirectory); string additionalFilesInput; eventProperties.TryGetValue(PublishCodeCoverageEventProperties.AdditionalCodeCoverageFiles, out additionalFilesInput); if (!string.IsNullOrEmpty(additionalFilesInput) && additionalFilesInput.Split(',').Count() > 0) { _additionalCodeCoverageFiles = additionalFilesInput.Split(',').ToList<string>(); } } // Changes the index.htm file to index.html if index.htm exists private void ChangeHtmExtensionToHtmlIfRequired(string reportDirectory, IExecutionContext executionContext) { var defaultIndexFile = Path.Combine(reportDirectory, CodeCoverageConstants.DefaultIndexFile); var htmIndexFile = Path.Combine(reportDirectory, CodeCoverageConstants.HtmIndexFile); // If index.html does not exist and index.htm exists, copy the .html file from .htm file. // Don't delete the .htm file as it might be referenced by other .htm/.html files. if (!File.Exists(defaultIndexFile) && File.Exists(htmIndexFile)) { try { File.Copy(sourceFileName: htmIndexFile, destFileName: defaultIndexFile); } catch (Exception ex) { // In the warning text, prefer using ex.InnerException when available, for more-specific details executionContext.Warning(StringUtil.Loc("RenameIndexFileCoberturaFailed", htmIndexFile, defaultIndexFile, _codeCoverageTool, (ex.InnerException ?? ex).ToString())); } } } /// <summary> /// This method replaces the default index.html generated by cobertura with /// the non-framed version /// </summary> /// <param name="reportDirectory"></param> private void ModifyCoberturaIndexDotHTML(string reportDirectory, IExecutionContext executionContext) { try { string newIndexHtml = Path.Combine(reportDirectory, CodeCoverageConstants.NewIndexFile); string indexHtml = Path.Combine(reportDirectory, CodeCoverageConstants.DefaultIndexFile); string nonFrameHtml = Path.Combine(reportDirectory, CodeCoverageConstants.DefaultNonFrameFileCobertura); if (_codeCoverageTool.Equals("cobertura", StringComparison.OrdinalIgnoreCase) && File.Exists(indexHtml) && File.Exists(nonFrameHtml)) { // duplicating frame-summary.html to index.html and renaming index.html to newindex.html File.Delete(newIndexHtml); File.Move(indexHtml, newIndexHtml); File.Copy(nonFrameHtml, indexHtml, overwrite: true); } } catch (Exception ex) { // In the warning text, prefer using ex.InnerException when available, for more-specific details executionContext.Warning(StringUtil.Loc("RenameIndexFileCoberturaFailed", CodeCoverageConstants.DefaultNonFrameFileCobertura, CodeCoverageConstants.DefaultIndexFile, _codeCoverageTool, (ex.InnerException ?? ex).ToString())); } } private string GetCoverageDirectory(string buildId, string directoryName) { return Path.Combine(Path.GetTempPath(), GetCoverageDirectoryName(buildId, directoryName)); } private string GetCoverageDirectoryName(string buildId, string directoryName) { return directoryName + "_" + buildId; } #endregion internal static class WellKnownResultsCommand { internal static readonly string PublishCodeCoverage = "publish"; internal static readonly string EnableCodeCoverage = "enable"; } internal static class EnableCodeCoverageEventProperties { internal static readonly string BuildTool = "buildtool"; internal static readonly string BuildFile = "buildfile"; internal static readonly string CodeCoverageTool = "codecoveragetool"; internal static readonly string ClassFilesDirectories = "classfilesdirectories"; internal static readonly string ClassFilter = "classfilter"; internal static readonly string SourceDirectories = "sourcedirectories"; internal static readonly string SummaryFile = "summaryfile"; internal static readonly string ReportDirectory = "reportdirectory"; internal static readonly string CCReportTask = "ccreporttask"; internal static readonly string ReportBuildFile = "reportbuildfile"; internal static readonly string IsMultiModule = "ismultimodule"; } internal static class PublishCodeCoverageEventProperties { internal static readonly string CodeCoverageTool = "codecoveragetool"; internal static readonly string SummaryFile = "summaryfile"; internal static readonly string ReportDirectory = "reportdirectory"; internal static readonly string AdditionalCodeCoverageFiles = "additionalcodecoveragefiles"; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Magecrawl.Actors; using Magecrawl.EngineInterfaces; using Magecrawl.GameEngine.Interface; using Magecrawl.GameEngine.Magic; using Magecrawl.GameEngine.Physics; using Magecrawl.GameEngine.SaveLoad; using Magecrawl.Interfaces; using Magecrawl.Items; using Magecrawl.Maps; using Magecrawl.Maps.Generator; using Magecrawl.Maps.Generator.Cave; using Magecrawl.Maps.Generator.Stitch; using Magecrawl.Maps.MapObjects; using Magecrawl.StatusEffects.Interfaces; using Magecrawl.Utilities; namespace Magecrawl.GameEngine { // This class mostly coordinates between a bunch of helper classes to provide what PublicGameEngine needs. internal sealed class CoreGameEngine : IDisposable { private Player m_player; private Dictionary<int, Map> m_dungeon; private SaveLoadCore m_saveLoad; private PathfindingMap m_pathFinding; private PhysicsEngine m_physicsEngine; private CoreTimingEngine m_timingEngine; private MonsterSkillEffectEngine m_monsterSkillEngine; internal int TurnCount { get; set; } internal event TextOutputFromGame TextOutputEvent; internal event PlayerDied PlayerDiedEvent; internal event RangedAttack RangedAttackEvent; internal FOVManager FOVManager { get { return m_physicsEngine.FOVManager; } } internal IMonsterSkillEngine MonsterSkillEngine { get { return m_monsterSkillEngine; } } // Almost every member of the GameEngine component will need to call CoreGameEngine at some point. // As opossed to have everyone stash a copy of it, just make it a singleton. private static CoreGameEngine m_instance; public static CoreGameEngine Instance { get { return m_instance; } } public CoreGameEngine() { m_instance = this; m_saveLoad = new SaveLoadCore(); m_timingEngine = new CoreTimingEngine(); m_monsterSkillEngine = new MonsterSkillEffectEngine(this); m_dungeon = new Dictionary<int, Map>(); StairsMapping.Setup(); CoreGameEngineInterface.SetupCoreGameEngineInterface(this); } public void CreateNewWorld(string playerName, string startingBackground) { // Don't use property so we don't hit validation code m_currentLevel = 0; Stairs incommingStairs = null; Random random = new Random(); bool generateCave = false; for (int i = 0; i < 5; ++i) { generateCave = random.Chance(50); MapGeneratorBase mapGenerator = generateCave ? (MapGeneratorBase)new SimpleCaveGenerator(random) : (MapGeneratorBase)new StitchtogeatherMapGenerator(random); m_dungeon[i] = mapGenerator.GenerateMap(incommingStairs, i); incommingStairs = m_dungeon[i].MapObjects.Where(x => x.Type == MapObjectType.StairsDown).OfType<Stairs>().First(); } Point initialStairsUpPosition = m_dungeon[0].MapObjects.Where(x => x.Type == MapObjectType.StairsUp).OfType<Stairs>().First().Position; ClearMonstersFromStartingArea(initialStairsUpPosition); m_player = new Player(playerName, initialStairsUpPosition); PlayerBackgrounds.SetupBackground(m_player, startingBackground); TurnCount = 0; m_physicsEngine = new PhysicsEngine(Player, Map); m_pathFinding = new PathfindingMap(Player, Map); // If the player isn't the first actor, let others go. See archtecture note in PublicGameEngine. m_physicsEngine.AfterPlayerAction(this); } private void ClearMonstersFromStartingArea(Point initialStairsUpPosition) { List<Point> monsterFreePoints = PointListUtils.PointListFromBurstPosition(initialStairsUpPosition, 8); Random random = new Random(); bool[,] moveablePoints = m_dungeon[0].CalculateMoveablePointGrid(true, initialStairsUpPosition); foreach(Monster monsterToMove in m_dungeon[0].Monsters.Where(m => monsterFreePoints.Contains(m.Position)).OfType<Monster>()) { int attempts = 0; while (true) { int possibleX = random.getInt(0, m_dungeon[0].Width - 1); int possibleY = random.getInt(0, m_dungeon[0].Height - 1); if (moveablePoints[possibleX, possibleY]) { monsterToMove.Position = new Point(possibleX, possibleY); moveablePoints[possibleX, possibleY] = false; break; } else { attempts++; } // If we try 10000 random points and fail, throw an exception, since something is seriously wrong if (attempts > 10000) throw new MapGenerationFailureException("ClearMonstersFromStartingArea can't find spot to move monster"); } } } public void LoadSaveFile(string saveGameName) { string saveGameDirectory = GetSaveDirectoryCreateIfNotExist(); m_saveLoad.LoadGame(Path.Combine(saveGameDirectory, saveGameName)); m_physicsEngine = new PhysicsEngine(Player, Map); m_pathFinding = new PathfindingMap(Player, Map); } public void Dispose() { m_instance = null; } internal CombatEngine CombatEngine { get { return m_physicsEngine.CombatEngine; } } internal Player Player { get { return m_player; } } internal Map Map { get { return m_dungeon[CurrentLevel]; } } private int m_currentLevel; public int CurrentLevel { get { return m_currentLevel; } internal set { m_currentLevel = value; m_pathFinding = new PathfindingMap(Player, Map); m_physicsEngine.NewMapPlayerInfo(Player, Map); } } internal Map GetSpecificFloor(int i) { return m_dungeon[i]; } internal int NumberOfLevels { get { return m_dungeon.Keys.Count; } } // Due to the way XML serialization works, we grab the Instance version of this // class, not any that we could pass in. This allows us to set the map data. internal void SetWithSaveData(Player p, Dictionary<int, Map> d, int currentLevel) { m_player = p; m_dungeon = d; // Don't use property so we don't hit state changing code m_currentLevel = currentLevel; } internal void Save() { SendTextOutput("Saving Game."); string saveGameDirectory = GetSaveDirectoryCreateIfNotExist(); m_saveLoad.SaveGame(Path.Combine(saveGameDirectory, m_player.Name) + ".sav"); } private static string GetSaveDirectoryCreateIfNotExist() { string saveGameDirectory = Path.Combine(AssemblyDirectory.CurrentAssemblyDirectory, "Saves"); if (!Directory.Exists(saveGameDirectory)) Directory.CreateDirectory(saveGameDirectory); return saveGameDirectory; } internal bool Move(Character c, Direction direction) { return m_physicsEngine.Move(c, direction); } internal bool Attack(Character attacker, Point target) { return m_physicsEngine.Attack(attacker, target); } internal bool CastSpell(Player caster, Spell spell, Point target) { return m_physicsEngine.CastSpell(caster, spell, target); } internal List<Point> TargettedDrawablePoints(object targettingObject, Point target) { return m_physicsEngine.TargettedDrawablePoints(targettingObject, target); } internal bool UseMonsterSkill(Character invoker, MonsterSkillType skill, Point target) { return m_monsterSkillEngine.UseSkill(invoker, skill, target); } public bool Operate(Character characterOperating, Point pointToOperateAt) { // Right now, you can only operate next to a thing if (PointDirectionUtils.LatticeDistance(characterOperating.Position, pointToOperateAt) != 1) return false; return m_physicsEngine.Operate(characterOperating, pointToOperateAt); } internal bool Wait(Character c) { return m_physicsEngine.Wait(c); } internal bool ReloadWeapon(Player player) { return m_physicsEngine.ReloadWeapon(player); } internal bool PlayerGetItem() { return m_physicsEngine.PlayerGetItem(); } internal bool PlayerGetItem(IItem item) { return m_physicsEngine.PlayerGetItem(item); } internal bool PlayerMoveUpStairs() { return m_physicsEngine.PlayerMoveUpStairs(Player, Map); } internal bool PlayerMoveDownStairs() { return m_physicsEngine.PlayerMoveDownStairs(Player, Map); } // Called by PublicGameEngine after any call to CoreGameEngine which passes time. internal void AfterPlayerAction() { m_physicsEngine.AfterPlayerAction(this); TurnCount++; } // Called by PublicGameEngine after any call to CoreGameEngine which passes time. internal void BeforePlayerAction() { m_physicsEngine.BeforePlayerAction(this); } internal List<Point> PathToPoint(Character actor, Point dest, bool canOperate, bool usePlayerLOS, bool monstersBlockPath) { return m_pathFinding.Travel(actor, dest, canOperate, m_physicsEngine, usePlayerLOS, monstersBlockPath); } public bool IsRangedPathBetweenPoints(Point x, Point y) { return m_physicsEngine.IsRangedPathBetweenPoints(x, y); } public void FilterNotTargetablePointsFromList(List<EffectivePoint> pointList, Point characterPosition, int visionRange, bool needsToBeVisible) { m_physicsEngine.FilterNotTargetablePointsFromList(pointList, characterPosition, visionRange, needsToBeVisible); } public void FilterNotTargetablePointsFromList(List<Point> pointList, Point characterPosition, int visionRange, bool needsToBeVisible) { m_physicsEngine.FilterNotTargetablePointsFromList(pointList, characterPosition, visionRange, needsToBeVisible); } public TileVisibility[,] CalculateTileVisibility() { return m_physicsEngine.CalculateTileVisibility(); } internal void PlayerDied() { PlayerDiedEvent(); } internal void SendTextOutput(string s) { TextOutputEvent(s); } internal void ShowRangedAttack(object attackingMethod, ShowRangedAttackType type, object data, bool targetAtEndPoint) { RangedAttackEvent(attackingMethod, type, data, targetAtEndPoint); } public bool DangerPlayerInLOS() { return m_physicsEngine.DangerPlayerInLOS(); } public bool CurrentOrRecentDanger() { return m_physicsEngine.CurrentOrRecentDanger(); } public List<Character> MonstersInCharactersLOS(Character chacter) { List<Character> returnList = new List<Character>(); FOVManager.CalculateForMultipleCalls(Map, chacter.Position, chacter.Vision); foreach (Monster m in Map.Monsters) { if (FOVManager.Visible(m.Position)) returnList.Add(m); } return returnList; } public List<ICharacter> MonstersInPlayerLOS() { List<ICharacter> returnList = new List<ICharacter>(); FOVManager.CalculateForMultipleCalls(Map, Player.Position, Player.Vision); foreach (Monster m in Map.Monsters) { if (FOVManager.Visible(m.Position)) returnList.Add(m); } return returnList; } internal List<ItemOptions> GetOptionsForInventoryItem(Item item) { List<ItemOptions> optionList = new List<ItemOptions>(); if (item is IWeapon) { bool canEquip = m_player.CanEquipWeapon((IWeapon)item); optionList.Add(new ItemOptions("Equip", canEquip )); optionList.Add(new ItemOptions("Equip as Secondary", canEquip )); } if (item is IArmor) { optionList.Add(new ItemOptions("Equip", Player.CanEquipArmor((IArmor)item))); } if (item.ContainsAttribute("Invokable")) optionList.Add(new ItemOptions(item.GetAttribute("InvokeActionName"), true)); optionList.Add(new ItemOptions("Drop", true)); return optionList; } internal List<ItemOptions> GetOptionsForEquipmentItem(Item item) { List<ItemOptions> optionList = new List<ItemOptions>(); // If the item isn't a secondary, we can unequip it. if (Player.SecondaryWeapon == item) optionList.Add(new ItemOptions("Unequip as Secondary", true)); else optionList.Add(new ItemOptions("Unequip", true)); // TODO - Unsure how this'd work but it should be possible if (item.ContainsAttribute("Invokable")) optionList.Add(new ItemOptions(item.GetAttribute("InvokeActionName"), true)); return optionList; } internal bool SwapPrimarySecondaryWeapons(Player player) { bool didSomething = player.SwapPrimarySecondaryWeapons(); if (didSomething) m_timingEngine.ActorDidMinorAction(m_player); return didSomething; } internal bool PlayerSelectedItemOption(IItem item, string option, object argument) { bool didSomething = m_physicsEngine.HandleItemAction(item, option, argument); if (didSomething) m_timingEngine.ActorDidAction(m_player); return didSomething; } internal void FilterNotVisibleBothWaysFromList(Point centerPoint, List<EffectivePoint> pointList, Point pointToSaveFromList) { if (pointList == null) return; bool pointToSaveInList = pointList.Exists(x => x.Position == pointToSaveFromList); float effectiveStrengthAtPlayerPosition = pointToSaveInList ? pointList.First(x => x.Position == CoreGameEngine.Instance.Player.Position).EffectiveStrength : 0; pointList.RemoveAll(x => !IsRangedPathBetweenPoints(centerPoint, x.Position)); pointList.RemoveAll(x => !IsRangedPathBetweenPoints(x.Position, centerPoint)); if (pointToSaveInList) pointList.Add(new EffectivePoint(pointToSaveFromList, effectiveStrengthAtPlayerPosition)); } internal void FilterNotVisibleBothWaysFromList(Point centerPoint, List<Point> pointList) { if (pointList == null) return; bool centerPointInList = pointList.Exists(x => x == centerPoint); pointList.RemoveAll(x => !IsRangedPathBetweenPoints(centerPoint, x)); pointList.RemoveAll(x => !IsRangedPathBetweenPoints(x, centerPoint)); if (centerPointInList) pointList.Add(centerPoint); } internal ILongTermStatusEffect GetLongTermEffectSpellWouldProduce(string effectName) { return m_physicsEngine.GetLongTermEffectSpellWouldProduce(effectName); } } }
// =========================================================== // 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.Concurrent; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Diagnostics; using System.Linq; using System.Threading; using ECQRS.Commons.Bus; using MassTransit.Services.Routing.Configuration; using Newtonsoft.Json; using MassTransit; using MassTransit.BusConfigurators; using System.Reflection; namespace ECQRS.MassTransit.Bus { public interface IHasUnsubscribe { UnsubscribeAction Unsubscribe { get; set; } void ConsumeGeneric(object obj); } public class InternalConsumer<T> : Consumes<T>.All, IHasUnsubscribe where T : class { private IBusHandler _handler; private MethodInfo _method; public UnsubscribeAction Unsubscribe { get; set; } public InternalConsumer() { } public InternalConsumer(MethodInfo method, IBusHandler handler) { _handler = handler; _method = method; } public void Consume(T message) { _method.Invoke(_handler, new[] { message }); } public void ConsumeGeneric(object message) { _method.Invoke(_handler, new[] { message }); } } internal class QueueInstance : IDisposable { private List<PersistentSubscription> _persistentSubscriptions; private readonly Dictionary<Type, Dictionary<object, IHasUnsubscribe>> _subscriptions; private readonly bool _multiple; private readonly string _queueId; private readonly Guid _handler; private readonly Dictionary<string, Type> _types; private Action<ServiceBusConfigurator> _configPublishContext; private string _massTransitRoot; private IServiceBus _bus; private bool _started; internal IServiceBus Bus { get { return _bus; } } public bool IsMultiple { get { return _multiple; } } public QueueInstance(bool multiple, string queueId, Action<ServiceBusConfigurator> configPublishContext, string massTransitRoot) { _handler = Guid.NewGuid(); _multiple = multiple; _queueId = queueId; _subscriptions = new Dictionary<Type, Dictionary<object, IHasUnsubscribe>>(); _types = new Dictionary<string, Type>(); _configPublishContext = configPublishContext; _massTransitRoot = massTransitRoot; _started = false; _persistentSubscriptions = new List<PersistentSubscription>(); } public void Start() { _bus = ServiceBusFactory.New(x => { _configPublishContext(x); x.ReceiveFrom(_massTransitRoot + "/" + _queueId.Trim('/')+".rx"); //http://functionsoftware.co.uk/2015/05/01/masstransit-msmq-setup-and-configuration/ x.Subscribe(subs => { foreach (var sub in _persistentSubscriptions) { Type classType = typeof(InternalConsumer<>); Type[] typeParams = new Type[] { sub.MessageType }; Type constructedType = classType.MakeGenericType(typeParams); var consumer = (IHasUnsubscribe)Activator.CreateInstance(constructedType, new object[] { sub.Method, sub.HandlerInstance }); _subscriptions[sub.MessageType].Add(sub.HandlerInstance, consumer); subs.Consumer(sub.MessageType, (t) => consumer).Permanent(); //subs.Handler() } }); }); Thread.Sleep(5*1000); _started = true; } public void Subscribe(Type type, IBusHandler handlerInstance, string queueId) { if (!_subscriptions.ContainsKey(type)) { _types[type.Name] = type; _subscriptions.Add(type, new Dictionary<object, IHasUnsubscribe>()); } var action = handlerInstance.GetType().GetMethod("Handle", new[] { type }); if (!_started) { _persistentSubscriptions.Add(new PersistentSubscription(type, handlerInstance, action)); return; } /*_bus.SubscribeHandler<TIn>(msg => { var output = hostedClassesFunc.Invoke(msg); var context = _bus.MessageContext<TIn>(); context.Respond(output); });*/ Type classType = typeof(InternalConsumer<>); Type[] typeParams = new Type[] { type }; Type constructedType = classType.MakeGenericType(typeParams); var consumer = (IHasUnsubscribe)Activator.CreateInstance(constructedType, new object[] { action, handlerInstance }); _subscriptions[type].Add(handlerInstance, consumer); consumer.Unsubscribe = _bus.SubscribeConsumer(type, (t) => consumer); } public void Unsubscribe(Type type, IBusHandler handlerInstance, string queueId) { if (!_subscriptions.ContainsKey(type)) { return; } if (!_subscriptions[type].ContainsKey(handlerInstance)) { return; } var unsub = _subscriptions[type][handlerInstance]; _subscriptions[type].Remove(handlerInstance); unsub.Unsubscribe.Invoke(); } public void Dispose() { _bus.Dispose(); _bus = null; } internal void Publish(Message message) { _bus.GetEndpoint(new Uri(_massTransitRoot + "/" + _queueId.Trim('/')+".tx")).Send(message); } internal void RunSync(IEnumerable<Message> messages) { foreach (var message in messages) { var realType = message.GetType(); if (_subscriptions.ContainsKey(realType)) { foreach (var handler in _subscriptions[realType]) { handler.Value.ConsumeGeneric(message); } } } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Threading; using log4net; using log4net.Appender; using log4net.Core; using log4net.Repository; using Nini.Config; using OpenSim.Framework.Console; using OpenSim.Framework.Monitoring; namespace OpenSim.Framework.Servers { public class ServerBase { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public IConfigSource Config { get; protected set; } /// <summary> /// Console to be used for any command line output. Can be null, in which case there should be no output. /// </summary> protected ICommandConsole m_console; protected OpenSimAppender m_consoleAppender; protected FileAppender m_logFileAppender; protected DateTime m_startuptime; protected string m_startupDirectory = Environment.CurrentDirectory; protected string m_pidFile = String.Empty; protected ServerStatsCollector m_serverStatsCollector; /// <summary> /// Server version information. Usually VersionInfo + information about git commit, operating system, etc. /// </summary> protected string m_version; public ServerBase() { m_startuptime = DateTime.Now; m_version = VersionInfo.Version; EnhanceVersionInformation(); } protected void CreatePIDFile(string path) { if (File.Exists(path)) m_log.ErrorFormat( "[SERVER BASE]: Previous pid file {0} still exists on startup. Possibly previously unclean shutdown.", path); try { string pidstring = System.Diagnostics.Process.GetCurrentProcess().Id.ToString(); using (FileStream fs = File.Create(path)) { Byte[] buf = Encoding.ASCII.GetBytes(pidstring); fs.Write(buf, 0, buf.Length); } m_pidFile = path; m_log.InfoFormat("[SERVER BASE]: Created pid file {0}", m_pidFile); } catch (Exception e) { m_log.Warn(string.Format("[SERVER BASE]: Could not create PID file at {0} ", path), e); } } protected void RemovePIDFile() { if (m_pidFile != String.Empty) { try { File.Delete(m_pidFile); } catch (Exception e) { m_log.Error(string.Format("[SERVER BASE]: Error whilst removing {0} ", m_pidFile), e); } m_pidFile = String.Empty; } } /// <summary> /// Log information about the circumstances in which we're running (OpenSimulator version number, CLR details, /// etc.). /// </summary> public void LogEnvironmentInformation() { // FIXME: This should be done down in ServerBase but we need to sort out and refactor the log4net // XmlConfigurator calls first accross servers. m_log.InfoFormat("[SERVER BASE]: Starting in {0}", m_startupDirectory); m_log.InfoFormat("[SERVER BASE]: OpenSimulator version: {0}", m_version); // clr version potentially is more confusing than helpful, since it doesn't tell us if we're running under Mono/MS .NET and // the clr version number doesn't match the project version number under Mono. //m_log.Info("[STARTUP]: Virtual machine runtime version: " + Environment.Version + Environment.NewLine); m_log.InfoFormat( "[SERVER BASE]: Operating system version: {0}, .NET platform {1}, {2}-bit", Environment.OSVersion, Environment.OSVersion.Platform, Util.Is64BitProcess() ? "64" : "32"); } public void RegisterCommonAppenders(IConfig startupConfig) { ILoggerRepository repository = LogManager.GetRepository(); IAppender[] appenders = repository.GetAppenders(); foreach (IAppender appender in appenders) { if (appender.Name == "Console") { m_consoleAppender = (OpenSimAppender)appender; } else if (appender.Name == "LogFileAppender") { m_logFileAppender = (FileAppender)appender; } } if (null == m_consoleAppender) { Notice("No appender named Console found (see the log4net config file for this executable)!"); } else { // FIXME: This should be done through an interface rather than casting. m_consoleAppender.Console = (ConsoleBase)m_console; // If there is no threshold set then the threshold is effectively everything. if (null == m_consoleAppender.Threshold) m_consoleAppender.Threshold = Level.All; Notice(String.Format("Console log level is {0}", m_consoleAppender.Threshold)); } if (m_logFileAppender != null && startupConfig != null) { string cfgFileName = startupConfig.GetString("LogFile", null); if (cfgFileName != null) { m_logFileAppender.File = cfgFileName; m_logFileAppender.ActivateOptions(); } m_log.InfoFormat("[SERVER BASE]: Logging started to file {0}", m_logFileAppender.File); } } /// <summary> /// Register common commands once m_console has been set if it is going to be set /// </summary> public void RegisterCommonCommands() { if (m_console == null) return; m_console.Commands.AddCommand( "General", false, "show info", "show info", "Show general information about the server", HandleShow); m_console.Commands.AddCommand( "General", false, "show version", "show version", "Show server version", HandleShow); m_console.Commands.AddCommand( "General", false, "show uptime", "show uptime", "Show server uptime", HandleShow); m_console.Commands.AddCommand( "General", false, "get log level", "get log level", "Get the current console logging level", (mod, cmd) => ShowLogLevel()); m_console.Commands.AddCommand( "General", false, "set log level", "set log level <level>", "Set the console logging level for this session.", HandleSetLogLevel); m_console.Commands.AddCommand( "General", false, "config set", "config set <section> <key> <value>", "Set a config option. In most cases this is not useful since changed parameters are not dynamically reloaded. Neither do changed parameters persist - you will have to change a config file manually and restart.", HandleConfig); m_console.Commands.AddCommand( "General", false, "config get", "config get [<section>] [<key>]", "Synonym for config show", HandleConfig); m_console.Commands.AddCommand( "General", false, "config show", "config show [<section>] [<key>]", "Show config information", "If neither section nor field are specified, then the whole current configuration is printed." + Environment.NewLine + "If a section is given but not a field, then all fields in that section are printed.", HandleConfig); m_console.Commands.AddCommand( "General", false, "config save", "config save <path>", "Save current configuration to a file at the given path", HandleConfig); m_console.Commands.AddCommand( "General", false, "command-script", "command-script <script>", "Run a command script from file", HandleScript); m_console.Commands.AddCommand( "General", false, "show threads", "show threads", "Show thread status", HandleShow); m_console.Commands.AddCommand( "Debug", false, "threads abort", "threads abort <thread-id>", "Abort a managed thread. Use \"show threads\" to find possible threads.", HandleThreadsAbort); m_console.Commands.AddCommand( "General", false, "threads show", "threads show", "Show thread status. Synonym for \"show threads\"", (string module, string[] args) => Notice(GetThreadsReport())); m_console.Commands.AddCommand ( "Debug", false, "debug comms set", "debug comms set serialosdreq true|false", "Set comms parameters. For debug purposes.", HandleDebugCommsSet); m_console.Commands.AddCommand ( "Debug", false, "debug comms status", "debug comms status", "Show current debug comms parameters.", HandleDebugCommsStatus); m_console.Commands.AddCommand ( "Debug", false, "debug threadpool set", "debug threadpool set worker|iocp min|max <n>", "Set threadpool parameters. For debug purposes.", HandleDebugThreadpoolSet); m_console.Commands.AddCommand ( "Debug", false, "debug threadpool status", "debug threadpool status", "Show current debug threadpool parameters.", HandleDebugThreadpoolStatus); m_console.Commands.AddCommand( "Debug", false, "debug threadpool level", "debug threadpool level 0.." + Util.MAX_THREADPOOL_LEVEL, "Turn on logging of activity in the main thread pool.", "Log levels:\n" + " 0 = no logging\n" + " 1 = only first line of stack trace; don't log common threads\n" + " 2 = full stack trace; don't log common threads\n" + " 3 = full stack trace, including common threads\n", HandleDebugThreadpoolLevel); // m_console.Commands.AddCommand( // "Debug", false, "show threadpool calls active", // "show threadpool calls active", // "Show details about threadpool calls that are still active (currently waiting or in progress)", // HandleShowThreadpoolCallsActive); m_console.Commands.AddCommand( "Debug", false, "show threadpool calls complete", "show threadpool calls complete", "Show details about threadpool calls that have been completed.", HandleShowThreadpoolCallsComplete); m_console.Commands.AddCommand( "Debug", false, "force gc", "force gc", "Manually invoke runtime garbage collection. For debugging purposes", HandleForceGc); m_console.Commands.AddCommand( "General", false, "quit", "quit", "Quit the application", (mod, args) => Shutdown()); m_console.Commands.AddCommand( "General", false, "shutdown", "shutdown", "Quit the application", (mod, args) => Shutdown()); ChecksManager.RegisterConsoleCommands(m_console); StatsManager.RegisterConsoleCommands(m_console); } public void RegisterCommonComponents(IConfigSource configSource) { IConfig networkConfig = configSource.Configs["Network"]; if (networkConfig != null) { WebUtil.SerializeOSDRequestsPerEndpoint = networkConfig.GetBoolean("SerializeOSDRequests", false); } m_serverStatsCollector = new ServerStatsCollector(); m_serverStatsCollector.Initialise(configSource); m_serverStatsCollector.Start(); } private void HandleDebugCommsStatus(string module, string[] args) { Notice("serialosdreq is {0}", WebUtil.SerializeOSDRequestsPerEndpoint); } private void HandleDebugCommsSet(string module, string[] args) { if (args.Length != 5) { Notice("Usage: debug comms set serialosdreq true|false"); return; } if (args[3] != "serialosdreq") { Notice("Usage: debug comms set serialosdreq true|false"); return; } bool setSerializeOsdRequests; if (!ConsoleUtil.TryParseConsoleBool(m_console, args[4], out setSerializeOsdRequests)) return; WebUtil.SerializeOSDRequestsPerEndpoint = setSerializeOsdRequests; Notice("serialosdreq is now {0}", setSerializeOsdRequests); } private void HandleShowThreadpoolCallsActive(string module, string[] args) { List<KeyValuePair<string, int>> calls = Util.GetFireAndForgetCallsInProgress().ToList(); calls.Sort((kvp1, kvp2) => kvp2.Value.CompareTo(kvp1.Value)); int namedCalls = 0; ConsoleDisplayList cdl = new ConsoleDisplayList(); foreach (KeyValuePair<string, int> kvp in calls) { if (kvp.Value > 0) { cdl.AddRow(kvp.Key, kvp.Value); namedCalls += kvp.Value; } } cdl.AddRow("TOTAL NAMED", namedCalls); long allQueuedCalls = Util.TotalQueuedFireAndForgetCalls; long allRunningCalls = Util.TotalRunningFireAndForgetCalls; cdl.AddRow("TOTAL QUEUED", allQueuedCalls); cdl.AddRow("TOTAL RUNNING", allRunningCalls); cdl.AddRow("TOTAL ANONYMOUS", allQueuedCalls + allRunningCalls - namedCalls); cdl.AddRow("TOTAL ALL", allQueuedCalls + allRunningCalls); MainConsole.Instance.Output(cdl.ToString()); } private void HandleShowThreadpoolCallsComplete(string module, string[] args) { List<KeyValuePair<string, int>> calls = Util.GetFireAndForgetCallsMade().ToList(); calls.Sort((kvp1, kvp2) => kvp2.Value.CompareTo(kvp1.Value)); int namedCallsMade = 0; ConsoleDisplayList cdl = new ConsoleDisplayList(); foreach (KeyValuePair<string, int> kvp in calls) { cdl.AddRow(kvp.Key, kvp.Value); namedCallsMade += kvp.Value; } cdl.AddRow("TOTAL NAMED", namedCallsMade); long allCallsMade = Util.TotalFireAndForgetCallsMade; cdl.AddRow("TOTAL ANONYMOUS", allCallsMade - namedCallsMade); cdl.AddRow("TOTAL ALL", allCallsMade); MainConsole.Instance.Output(cdl.ToString()); } private void HandleDebugThreadpoolStatus(string module, string[] args) { int workerThreads, iocpThreads; ThreadPool.GetMinThreads(out workerThreads, out iocpThreads); Notice("Min worker threads: {0}", workerThreads); Notice("Min IOCP threads: {0}", iocpThreads); ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads); Notice("Max worker threads: {0}", workerThreads); Notice("Max IOCP threads: {0}", iocpThreads); ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads); Notice("Available worker threads: {0}", workerThreads); Notice("Available IOCP threads: {0}", iocpThreads); } private void HandleDebugThreadpoolSet(string module, string[] args) { if (args.Length != 6) { Notice("Usage: debug threadpool set worker|iocp min|max <n>"); return; } int newThreads; if (!ConsoleUtil.TryParseConsoleInt(m_console, args[5], out newThreads)) return; string poolType = args[3]; string bound = args[4]; bool fail = false; int workerThreads, iocpThreads; if (poolType == "worker") { if (bound == "min") { ThreadPool.GetMinThreads(out workerThreads, out iocpThreads); if (!ThreadPool.SetMinThreads(newThreads, iocpThreads)) fail = true; } else { ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads); if (!ThreadPool.SetMaxThreads(newThreads, iocpThreads)) fail = true; } } else { if (bound == "min") { ThreadPool.GetMinThreads(out workerThreads, out iocpThreads); if (!ThreadPool.SetMinThreads(workerThreads, newThreads)) fail = true; } else { ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads); if (!ThreadPool.SetMaxThreads(workerThreads, newThreads)) fail = true; } } if (fail) { Notice("ERROR: Could not set {0} {1} threads to {2}", poolType, bound, newThreads); } else { int minWorkerThreads, maxWorkerThreads, minIocpThreads, maxIocpThreads; ThreadPool.GetMinThreads(out minWorkerThreads, out minIocpThreads); ThreadPool.GetMaxThreads(out maxWorkerThreads, out maxIocpThreads); Notice("Min worker threads now {0}", minWorkerThreads); Notice("Min IOCP threads now {0}", minIocpThreads); Notice("Max worker threads now {0}", maxWorkerThreads); Notice("Max IOCP threads now {0}", maxIocpThreads); } } private static void HandleDebugThreadpoolLevel(string module, string[] cmdparams) { if (cmdparams.Length < 4) { MainConsole.Instance.Output("Usage: debug threadpool level 0.." + Util.MAX_THREADPOOL_LEVEL); return; } string rawLevel = cmdparams[3]; int newLevel; if (!int.TryParse(rawLevel, out newLevel)) { MainConsole.Instance.OutputFormat("{0} is not a valid debug level", rawLevel); return; } if (newLevel < 0 || newLevel > Util.MAX_THREADPOOL_LEVEL) { MainConsole.Instance.OutputFormat("{0} is outside the valid debug level range of 0.." + Util.MAX_THREADPOOL_LEVEL, newLevel); return; } Util.LogThreadPool = newLevel; MainConsole.Instance.OutputFormat("LogThreadPool set to {0}", newLevel); } private void HandleForceGc(string module, string[] args) { Notice("Manually invoking runtime garbage collection"); GC.Collect(); } public virtual void HandleShow(string module, string[] cmd) { List<string> args = new List<string>(cmd); args.RemoveAt(0); string[] showParams = args.ToArray(); switch (showParams[0]) { case "info": ShowInfo(); break; case "version": Notice(GetVersionText()); break; case "uptime": Notice(GetUptimeReport()); break; case "threads": Notice(GetThreadsReport()); break; } } /// <summary> /// Change and load configuration file data. /// </summary> /// <param name="module"></param> /// <param name="cmd"></param> private void HandleConfig(string module, string[] cmd) { List<string> args = new List<string>(cmd); args.RemoveAt(0); string[] cmdparams = args.ToArray(); if (cmdparams.Length > 0) { string firstParam = cmdparams[0].ToLower(); switch (firstParam) { case "set": if (cmdparams.Length < 4) { Notice("Syntax: config set <section> <key> <value>"); Notice("Example: config set ScriptEngine.DotNetEngine NumberOfScriptThreads 5"); } else { IConfig c; IConfigSource source = new IniConfigSource(); c = source.AddConfig(cmdparams[1]); if (c != null) { string _value = String.Join(" ", cmdparams, 3, cmdparams.Length - 3); c.Set(cmdparams[2], _value); Config.Merge(source); Notice("In section [{0}], set {1} = {2}", c.Name, cmdparams[2], _value); } } break; case "get": case "show": if (cmdparams.Length == 1) { foreach (IConfig config in Config.Configs) { Notice("[{0}]", config.Name); string[] keys = config.GetKeys(); foreach (string key in keys) Notice(" {0} = {1}", key, config.GetString(key)); } } else if (cmdparams.Length == 2 || cmdparams.Length == 3) { IConfig config = Config.Configs[cmdparams[1]]; if (config == null) { Notice("Section \"{0}\" does not exist.",cmdparams[1]); break; } else { if (cmdparams.Length == 2) { Notice("[{0}]", config.Name); foreach (string key in config.GetKeys()) Notice(" {0} = {1}", key, config.GetString(key)); } else { Notice( "config get {0} {1} : {2}", cmdparams[1], cmdparams[2], config.GetString(cmdparams[2])); } } } else { Notice("Syntax: config {0} [<section>] [<key>]", firstParam); Notice("Example: config {0} ScriptEngine.DotNetEngine NumberOfScriptThreads", firstParam); } break; case "save": if (cmdparams.Length < 2) { Notice("Syntax: config save <path>"); return; } string path = cmdparams[1]; Notice("Saving configuration file: {0}", path); if (Config is IniConfigSource) { IniConfigSource iniCon = (IniConfigSource)Config; iniCon.Save(path); } else if (Config is XmlConfigSource) { XmlConfigSource xmlCon = (XmlConfigSource)Config; xmlCon.Save(path); } break; } } } private void HandleSetLogLevel(string module, string[] cmd) { if (cmd.Length != 4) { Notice("Usage: set log level <level>"); return; } if (null == m_consoleAppender) { Notice("No appender named Console found (see the log4net config file for this executable)!"); return; } string rawLevel = cmd[3]; ILoggerRepository repository = LogManager.GetRepository(); Level consoleLevel = repository.LevelMap[rawLevel]; if (consoleLevel != null) m_consoleAppender.Threshold = consoleLevel; else Notice( "{0} is not a valid logging level. Valid logging levels are ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF", rawLevel); ShowLogLevel(); } private void ShowLogLevel() { Notice("Console log level is {0}", m_consoleAppender.Threshold); } protected virtual void HandleScript(string module, string[] parms) { if (parms.Length != 2) { Notice("Usage: command-script <path-to-script"); return; } RunCommandScript(parms[1]); } /// <summary> /// Run an optional startup list of commands /// </summary> /// <param name="fileName"></param> protected void RunCommandScript(string fileName) { if (m_console == null) return; if (File.Exists(fileName)) { m_log.Info("[SERVER BASE]: Running " + fileName); using (StreamReader readFile = File.OpenText(fileName)) { string currentCommand; while ((currentCommand = readFile.ReadLine()) != null) { currentCommand = currentCommand.Trim(); if (!(currentCommand == "" || currentCommand.StartsWith(";") || currentCommand.StartsWith("//") || currentCommand.StartsWith("#"))) { m_log.Info("[SERVER BASE]: Running '" + currentCommand + "'"); m_console.RunCommand(currentCommand); } } } } } /// <summary> /// Return a report about the uptime of this server /// </summary> /// <returns></returns> protected string GetUptimeReport() { StringBuilder sb = new StringBuilder(String.Format("Time now is {0}\n", DateTime.Now)); sb.Append(String.Format("Server has been running since {0}, {1}\n", m_startuptime.DayOfWeek, m_startuptime)); sb.Append(String.Format("That is an elapsed time of {0}\n", DateTime.Now - m_startuptime)); return sb.ToString(); } protected void ShowInfo() { Notice(GetVersionText()); Notice("Startup directory: " + m_startupDirectory); if (null != m_consoleAppender) Notice(String.Format("Console log level: {0}", m_consoleAppender.Threshold)); } /// <summary> /// Enhance the version string with extra information if it's available. /// </summary> protected void EnhanceVersionInformation() { string buildVersion = string.Empty; // The subversion information is deprecated and will be removed at a later date // Add subversion revision information if available // Try file "svn_revision" in the current directory first, then the .svn info. // This allows to make the revision available in simulators not running from the source tree. // FIXME: Making an assumption about the directory we're currently in - we do this all over the place // elsewhere as well string gitDir = "../.git/"; string gitRefPointerPath = gitDir + "HEAD"; string svnRevisionFileName = "svn_revision"; string svnFileName = ".svn/entries"; string manualVersionFileName = ".version"; string inputLine; int strcmp; if (File.Exists(manualVersionFileName)) { using (StreamReader CommitFile = File.OpenText(manualVersionFileName)) buildVersion = CommitFile.ReadLine(); m_version += buildVersion ?? ""; } else if (File.Exists(gitRefPointerPath)) { // m_log.DebugFormat("[SERVER BASE]: Found {0}", gitRefPointerPath); string rawPointer = ""; using (StreamReader pointerFile = File.OpenText(gitRefPointerPath)) rawPointer = pointerFile.ReadLine(); // m_log.DebugFormat("[SERVER BASE]: rawPointer [{0}]", rawPointer); Match m = Regex.Match(rawPointer, "^ref: (.+)$"); if (m.Success) { // m_log.DebugFormat("[SERVER BASE]: Matched [{0}]", m.Groups[1].Value); string gitRef = m.Groups[1].Value; string gitRefPath = gitDir + gitRef; if (File.Exists(gitRefPath)) { // m_log.DebugFormat("[SERVER BASE]: Found gitRefPath [{0}]", gitRefPath); using (StreamReader refFile = File.OpenText(gitRefPath)) { string gitHash = refFile.ReadLine(); m_version += gitHash.Substring(0, 7); } } } } else { // Remove the else logic when subversion mirror is no longer used if (File.Exists(svnRevisionFileName)) { StreamReader RevisionFile = File.OpenText(svnRevisionFileName); buildVersion = RevisionFile.ReadLine(); buildVersion.Trim(); RevisionFile.Close(); } if (string.IsNullOrEmpty(buildVersion) && File.Exists(svnFileName)) { StreamReader EntriesFile = File.OpenText(svnFileName); inputLine = EntriesFile.ReadLine(); while (inputLine != null) { // using the dir svn revision at the top of entries file strcmp = String.Compare(inputLine, "dir"); if (strcmp == 0) { buildVersion = EntriesFile.ReadLine(); break; } else { inputLine = EntriesFile.ReadLine(); } } EntriesFile.Close(); } m_version += string.IsNullOrEmpty(buildVersion) ? " " : ("." + buildVersion + " ").Substring(0, 6); } } public string GetVersionText() { return String.Format("Version: {0} (SIMULATION/{1} - SIMULATION/{2})", m_version, VersionInfo.SimulationServiceVersionSupportedMin, VersionInfo.SimulationServiceVersionSupportedMax); } /// <summary> /// Get a report about the registered threads in this server. /// </summary> protected string GetThreadsReport() { // This should be a constant field. string reportFormat = "{0,6} {1,35} {2,16} {3,13} {4,10} {5,30}"; StringBuilder sb = new StringBuilder(); Watchdog.ThreadWatchdogInfo[] threads = Watchdog.GetThreadsInfo(); sb.Append(threads.Length + " threads are being tracked:" + Environment.NewLine); int timeNow = Environment.TickCount & Int32.MaxValue; sb.AppendFormat(reportFormat, "ID", "NAME", "LAST UPDATE (MS)", "LIFETIME (MS)", "PRIORITY", "STATE"); sb.Append(Environment.NewLine); foreach (Watchdog.ThreadWatchdogInfo twi in threads) { Thread t = twi.Thread; sb.AppendFormat( reportFormat, t.ManagedThreadId, t.Name, timeNow - twi.LastTick, timeNow - twi.FirstTick, t.Priority, t.ThreadState); sb.Append("\n"); } sb.Append("\n"); // For some reason mono 2.6.7 returns an empty threads set! Not going to confuse people by reporting // zero active threads. int totalThreads = Process.GetCurrentProcess().Threads.Count; if (totalThreads > 0) sb.AppendFormat("Total threads active: {0}\n\n", totalThreads); sb.Append("Main threadpool (excluding script engine pools)\n"); sb.Append(GetThreadPoolReport()); return sb.ToString(); } /// <summary> /// Get a thread pool report. /// </summary> /// <returns></returns> public static string GetThreadPoolReport() { string threadPoolUsed = null; int maxThreads = 0; int minThreads = 0; int allocatedThreads = 0; int inUseThreads = 0; int waitingCallbacks = 0; int completionPortThreads = 0; StringBuilder sb = new StringBuilder(); if (Util.FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool) { STPInfo stpi = Util.GetSmartThreadPoolInfo(); // ROBUST currently leaves this the FireAndForgetMethod but never actually initializes the threadpool. if (stpi != null) { threadPoolUsed = "SmartThreadPool"; maxThreads = stpi.MaxThreads; minThreads = stpi.MinThreads; inUseThreads = stpi.InUseThreads; allocatedThreads = stpi.ActiveThreads; waitingCallbacks = stpi.WaitingCallbacks; } } else if ( Util.FireAndForgetMethod == FireAndForgetMethod.QueueUserWorkItem || Util.FireAndForgetMethod == FireAndForgetMethod.UnsafeQueueUserWorkItem) { threadPoolUsed = "BuiltInThreadPool"; ThreadPool.GetMaxThreads(out maxThreads, out completionPortThreads); ThreadPool.GetMinThreads(out minThreads, out completionPortThreads); int availableThreads; ThreadPool.GetAvailableThreads(out availableThreads, out completionPortThreads); inUseThreads = maxThreads - availableThreads; allocatedThreads = -1; waitingCallbacks = -1; } if (threadPoolUsed != null) { sb.AppendFormat("Thread pool used : {0}\n", threadPoolUsed); sb.AppendFormat("Max threads : {0}\n", maxThreads); sb.AppendFormat("Min threads : {0}\n", minThreads); sb.AppendFormat("Allocated threads : {0}\n", allocatedThreads < 0 ? "not applicable" : allocatedThreads.ToString()); sb.AppendFormat("In use threads : {0}\n", inUseThreads); sb.AppendFormat("Work items waiting : {0}\n", waitingCallbacks < 0 ? "not available" : waitingCallbacks.ToString()); } else { sb.AppendFormat("Thread pool not used\n"); } return sb.ToString(); } public virtual void HandleThreadsAbort(string module, string[] cmd) { if (cmd.Length != 3) { MainConsole.Instance.Output("Usage: threads abort <thread-id>"); return; } int threadId; if (!int.TryParse(cmd[2], out threadId)) { MainConsole.Instance.Output("ERROR: Thread id must be an integer"); return; } if (Watchdog.AbortThread(threadId)) MainConsole.Instance.OutputFormat("Aborted thread with id {0}", threadId); else MainConsole.Instance.OutputFormat("ERROR - Thread with id {0} not found in managed threads", threadId); } /// <summary> /// Console output is only possible if a console has been established. /// That is something that cannot be determined within this class. So /// all attempts to use the console MUST be verified. /// </summary> /// <param name="msg"></param> protected void Notice(string msg) { if (m_console != null) { m_console.Output(msg); } } /// <summary> /// Console output is only possible if a console has been established. /// That is something that cannot be determined within this class. So /// all attempts to use the console MUST be verified. /// </summary> /// <param name="format"></param> /// <param name="components"></param> protected void Notice(string format, params object[] components) { if (m_console != null) m_console.OutputFormat(format, components); } public virtual void Shutdown() { m_serverStatsCollector.Close(); ShutdownSpecific(); } /// <summary> /// Should be overriden and referenced by descendents if they need to perform extra shutdown processing /// </summary> protected virtual void ShutdownSpecific() {} } }
/* // $Id: RagdollFactoryGenerated.cs $ // // IMPORTANT: GENERATED CODE ==> DO NOT EDIT! // Generated at 11/28/2011 16:30:02. Selected bone for generation was Hips // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. */ using UnityEngine; using System.Collections.Generic; /// <summary> /// Handles dynamic creation of ragdoll components for one specific model. As this is no dynamic ragdoll calculation but /// rather a snapshot of the armature at one given point in time.Because this code was generated automatically by Unity /// editor class RagdollCodeGenerator it should not be edited directly. All changes will be lost on regeneration! Instead /// regenerate the code or edit the generator's code itself if you need significant changes in structure. /// </summary> public class RagdollFactoryGenerated { internal PhysicMaterial physicMaterial = (PhysicMaterial)Resources.LoadAssetAtPath ("RuntimeMaterials/Physic/PlayerPhysicMaterial", typeof(PhysicMaterial)); public List<Collider> allColliders = new List<Collider> (); public List<Rigidbody> allRigidbodies = new List<Rigidbody> (); public List<CharacterJoint> allCharacterJoints = new List<CharacterJoint> (); /// <summary> /// Main entry point of this class to be called for generating all ragdoll components on the fly. The supplied game /// object should be the armature's parent. Although all methods check for existing objects, it is not recommended to /// call this method multiple times without doing explicit clean up before. /// </summary> public string rootBoneName = "Armature/Hips"; public Rigidbody hips_Rigidbody; public BoxCollider hips_BoxCollider; public BoxCollider ribs_BoxCollider; public Rigidbody ribs_Rigidbody; public CharacterJoint ribs_CharacterJoint; public SphereCollider head_SphereCollider; public Rigidbody head_Rigidbody; public CharacterJoint head_CharacterJoint; public CapsuleCollider upperArm_L_CapsuleCollider; public Rigidbody upperArm_L_Rigidbody; public CharacterJoint upperArm_L_CharacterJoint; public CapsuleCollider lowerArm_L_CapsuleCollider; public Rigidbody lowerArm_L_Rigidbody; public CharacterJoint lowerArm_L_CharacterJoint; public CapsuleCollider upperArm_R_CapsuleCollider; public Rigidbody upperArm_R_Rigidbody; public CharacterJoint upperArm_R_CharacterJoint; public CapsuleCollider lowerArm_R_CapsuleCollider; public Rigidbody lowerArm_R_Rigidbody; public CharacterJoint lowerArm_R_CharacterJoint; public CapsuleCollider thigh_L_CapsuleCollider; public Rigidbody thigh_L_Rigidbody; public CharacterJoint thigh_L_CharacterJoint; public CapsuleCollider shin_L_CapsuleCollider; public Rigidbody shin_L_Rigidbody; public CharacterJoint shin_L_CharacterJoint; public CapsuleCollider thigh_R_CapsuleCollider; public Rigidbody thigh_R_Rigidbody; public CharacterJoint thigh_R_CharacterJoint; public CapsuleCollider shin_R_CapsuleCollider; public Rigidbody shin_R_Rigidbody; public CharacterJoint shin_R_CharacterJoint; public virtual void CreateRagdollComponents(GameObject gameObject) { CreateRigidbody_Hips(gameObject, "Hips", "Armature/Hips"); CreateCollider_Hips(gameObject, "Hips", "Armature/Hips"); CreateCollider_Ribs(gameObject, "Ribs", "Armature/Hips/Spine/Ribs"); CreateRigidbody_Ribs(gameObject, "Ribs", "Armature/Hips/Spine/Ribs"); CreateCharacterJoint_Ribs(gameObject, "Ribs", "Armature/Hips/Spine/Ribs"); CreateCollider_Head(gameObject, "Head", "Armature/Hips/Spine/Ribs/Neck/Head"); CreateRigidbody_Head(gameObject, "Head", "Armature/Hips/Spine/Ribs/Neck/Head"); CreateCharacterJoint_Head(gameObject, "Head", "Armature/Hips/Spine/Ribs/Neck/Head"); CreateCollider_UpperArm_L(gameObject, "UpperArm_L", "Armature/Hips/Spine/Ribs/Shoulder_L/UpperArm_L"); CreateRigidbody_UpperArm_L(gameObject, "UpperArm_L", "Armature/Hips/Spine/Ribs/Shoulder_L/UpperArm_L"); CreateCharacterJoint_UpperArm_L(gameObject, "UpperArm_L", "Armature/Hips/Spine/Ribs/Shoulder_L/UpperArm_L"); CreateCollider_LowerArm_L(gameObject, "LowerArm_L", "Armature/Hips/Spine/Ribs/Shoulder_L/UpperArm_L/LowerArm_L"); CreateRigidbody_LowerArm_L(gameObject, "LowerArm_L", "Armature/Hips/Spine/Ribs/Shoulder_L/UpperArm_L/LowerArm_L"); CreateCharacterJoint_LowerArm_L(gameObject, "LowerArm_L", "Armature/Hips/Spine/Ribs/Shoulder_L/UpperArm_L/LowerArm_L"); CreateCollider_UpperArm_R(gameObject, "UpperArm_R", "Armature/Hips/Spine/Ribs/Shoulder_R/UpperArm_R"); CreateRigidbody_UpperArm_R(gameObject, "UpperArm_R", "Armature/Hips/Spine/Ribs/Shoulder_R/UpperArm_R"); CreateCharacterJoint_UpperArm_R(gameObject, "UpperArm_R", "Armature/Hips/Spine/Ribs/Shoulder_R/UpperArm_R"); CreateCollider_LowerArm_R(gameObject, "LowerArm_R", "Armature/Hips/Spine/Ribs/Shoulder_R/UpperArm_R/LowerArm_R"); CreateRigidbody_LowerArm_R(gameObject, "LowerArm_R", "Armature/Hips/Spine/Ribs/Shoulder_R/UpperArm_R/LowerArm_R"); CreateCharacterJoint_LowerArm_R(gameObject, "LowerArm_R", "Armature/Hips/Spine/Ribs/Shoulder_R/UpperArm_R/LowerArm_R"); CreateCollider_Thigh_L(gameObject, "Thigh_L", "Armature/Hips/Thigh_L"); CreateRigidbody_Thigh_L(gameObject, "Thigh_L", "Armature/Hips/Thigh_L"); CreateCharacterJoint_Thigh_L(gameObject, "Thigh_L", "Armature/Hips/Thigh_L"); CreateCollider_Shin_L(gameObject, "Shin_L", "Armature/Hips/Thigh_L/Shin_L"); CreateRigidbody_Shin_L(gameObject, "Shin_L", "Armature/Hips/Thigh_L/Shin_L"); CreateCharacterJoint_Shin_L(gameObject, "Shin_L", "Armature/Hips/Thigh_L/Shin_L"); CreateCollider_Thigh_R(gameObject, "Thigh_R", "Armature/Hips/Thigh_R"); CreateRigidbody_Thigh_R(gameObject, "Thigh_R", "Armature/Hips/Thigh_R"); CreateCharacterJoint_Thigh_R(gameObject, "Thigh_R", "Armature/Hips/Thigh_R"); CreateCollider_Shin_R(gameObject, "Shin_R", "Armature/Hips/Thigh_R/Shin_R"); CreateRigidbody_Shin_R(gameObject, "Shin_R", "Armature/Hips/Thigh_R/Shin_R"); CreateCharacterJoint_Shin_R(gameObject, "Shin_R", "Armature/Hips/Thigh_R/Shin_R"); } internal virtual Rigidbody CreateRigidbody_Hips(GameObject gameObject, string name, string path) { Transform childTransform = gameObject.transform.FindChild (path); GameObject childGameObject = childTransform.gameObject; Rigidbody rigidbody = childGameObject.GetComponent <Rigidbody> (); if (rigidbody != null) { Debug.LogWarning ("Existing rigidbody " + rigidbody.name + " found"); return null; } rigidbody = childGameObject.AddComponent <Rigidbody> (); hips_Rigidbody= rigidbody; rigidbody.isKinematic = true; rigidbody.useGravity = true; rigidbody.mass = 3.125f; rigidbody.drag = 0f; rigidbody.angularDrag = 0.05f; rigidbody.interpolation = RigidbodyInterpolation.None; rigidbody.detectCollisions = true; rigidbody.constraints = RigidbodyConstraints.None; allRigidbodies.Add (rigidbody); return rigidbody; } internal virtual Collider CreateCollider_Hips(GameObject gameObject, string name, string path) { Transform childTransform = gameObject.transform.FindChild (path); GameObject childGameObject = childTransform.gameObject; Collider collider = childGameObject.GetComponent <Collider> (); if (collider != null) { Debug.LogWarning ("Existing collider " + collider.name + " found of type " + collider.GetType ()); return null; } hips_BoxCollider = childGameObject.AddComponent<BoxCollider> (); collider = hips_BoxCollider; hips_BoxCollider.size = new Vector3 (0.2708345f, 0.2262724f, 0.197055f); hips_BoxCollider.center = new Vector3 (0.0837656f, -6.705523E-08f, -0.004841924f); collider.isTrigger = false; collider.material = (PhysicMaterial) Resources.Load ("RuntimeMaterials/Physic/PlayerPhysicMaterial", typeof(PhysicMaterial)); allColliders.Add (collider); return collider; } internal virtual Collider CreateCollider_Ribs(GameObject gameObject, string name, string path) { Transform childTransform = gameObject.transform.FindChild (path); GameObject childGameObject = childTransform.gameObject; Collider collider = childGameObject.GetComponent <Collider> (); if (collider != null) { Debug.LogWarning ("Existing collider " + collider.name + " found of type " + collider.GetType ()); return null; } ribs_BoxCollider = childGameObject.AddComponent<BoxCollider> (); collider = ribs_BoxCollider; ribs_BoxCollider.size = new Vector3 (0.12359f, 0.2262724f, 0.196419f); ribs_BoxCollider.center = new Vector3 (-0.06179501f, 2.980232E-08f, 0.035f); collider.isTrigger = false; collider.material = (PhysicMaterial) Resources.Load ("RuntimeMaterials/Physic/PlayerPhysicMaterial", typeof(PhysicMaterial)); allColliders.Add (collider); return collider; } internal virtual Rigidbody CreateRigidbody_Ribs(GameObject gameObject, string name, string path) { Transform childTransform = gameObject.transform.FindChild (path); GameObject childGameObject = childTransform.gameObject; Rigidbody rigidbody = childGameObject.GetComponent <Rigidbody> (); if (rigidbody != null) { Debug.LogWarning ("Existing rigidbody " + rigidbody.name + " found"); return null; } rigidbody = childGameObject.AddComponent <Rigidbody> (); ribs_Rigidbody= rigidbody; rigidbody.isKinematic = true; rigidbody.useGravity = true; rigidbody.mass = 3.125f; rigidbody.drag = 0f; rigidbody.angularDrag = 0.05f; rigidbody.interpolation = RigidbodyInterpolation.None; rigidbody.detectCollisions = true; rigidbody.constraints = RigidbodyConstraints.None; allRigidbodies.Add (rigidbody); return rigidbody; } internal virtual CharacterJoint CreateCharacterJoint_Ribs(GameObject gameObject, string name, string path) { Transform childTransform = gameObject.transform.FindChild (path); GameObject childGameObject = childTransform.gameObject; CharacterJoint joint = childGameObject.GetComponent <CharacterJoint> (); if (joint != null) { Debug.LogWarning ("Existing joint " + joint.name + " found"); return null; } joint = childGameObject.AddComponent <CharacterJoint> (); ribs_CharacterJoint= joint; joint.breakForce = Mathf.Infinity; joint.breakTorque = Mathf.Infinity; joint.anchor = new Vector3 (0f, 0f, 0f); joint.axis = new Vector3 (-1f, 0f, 0f); joint.swingAxis = new Vector3 (0f, 0f, 1f); SoftJointLimit lowTwistLimitNew = joint.lowTwistLimit; lowTwistLimitNew.limit = -20f; lowTwistLimitNew.spring = 0f; lowTwistLimitNew.damper = 0f; lowTwistLimitNew.bounciness = 0f; joint.lowTwistLimit = lowTwistLimitNew; SoftJointLimit highTwistLimitNew = joint.highTwistLimit; highTwistLimitNew.limit = 20f; highTwistLimitNew.spring = 0f; highTwistLimitNew.damper = 0f; highTwistLimitNew.bounciness = 0f; joint.highTwistLimit = highTwistLimitNew; SoftJointLimit swing1LimitNew = joint.swing1Limit; swing1LimitNew.limit = 10f; swing1LimitNew.spring = 0f; swing1LimitNew.damper = 0f; swing1LimitNew.bounciness = 0f; joint.swing1Limit = swing1LimitNew; SoftJointLimit swing2LimitNew = joint.swing2Limit; swing2LimitNew.limit = 0f; swing2LimitNew.spring = 0f; swing2LimitNew.damper = 0f; swing2LimitNew.bounciness = 0f; joint.swing2Limit = swing2LimitNew; Transform parentTransform = gameObject.transform.FindChild ("Armature/Hips"); if (parentTransform == null) { Debug.LogWarning ("parentGameObject for " + childGameObject.name + " not found! Maybe initalisation is not yet done."); joint.connectedBody = null; } else { joint.connectedBody = parentTransform.gameObject.rigidbody; } allCharacterJoints.Add (joint); return joint; } internal virtual Collider CreateCollider_Head(GameObject gameObject, string name, string path) { Transform childTransform = gameObject.transform.FindChild (path); GameObject childGameObject = childTransform.gameObject; Collider collider = childGameObject.GetComponent <Collider> (); if (collider != null) { Debug.LogWarning ("Existing collider " + collider.name + " found of type " + collider.GetType ()); return null; } head_SphereCollider = childGameObject.AddComponent<SphereCollider> (); collider = head_SphereCollider; head_SphereCollider.radius = 0.1165681f; head_SphereCollider.center = new Vector3 (-0.13f, 0f, 0f); collider.isTrigger = false; collider.material = (PhysicMaterial) Resources.Load ("RuntimeMaterials/Physic/PlayerPhysicMaterial", typeof(PhysicMaterial)); allColliders.Add (collider); return collider; } internal virtual Rigidbody CreateRigidbody_Head(GameObject gameObject, string name, string path) { Transform childTransform = gameObject.transform.FindChild (path); GameObject childGameObject = childTransform.gameObject; Rigidbody rigidbody = childGameObject.GetComponent <Rigidbody> (); if (rigidbody != null) { Debug.LogWarning ("Existing rigidbody " + rigidbody.name + " found"); return null; } rigidbody = childGameObject.AddComponent <Rigidbody> (); head_Rigidbody= rigidbody; rigidbody.isKinematic = true; rigidbody.useGravity = true; rigidbody.mass = 1.25f; rigidbody.drag = 0f; rigidbody.angularDrag = 0.05f; rigidbody.interpolation = RigidbodyInterpolation.None; rigidbody.detectCollisions = true; rigidbody.constraints = RigidbodyConstraints.None; allRigidbodies.Add (rigidbody); return rigidbody; } internal virtual CharacterJoint CreateCharacterJoint_Head(GameObject gameObject, string name, string path) { Transform childTransform = gameObject.transform.FindChild (path); GameObject childGameObject = childTransform.gameObject; CharacterJoint joint = childGameObject.GetComponent <CharacterJoint> (); if (joint != null) { Debug.LogWarning ("Existing joint " + joint.name + " found"); return null; } joint = childGameObject.AddComponent <CharacterJoint> (); head_CharacterJoint= joint; joint.breakForce = Mathf.Infinity; joint.breakTorque = Mathf.Infinity; joint.anchor = new Vector3 (0f, 0f, 0f); joint.axis = new Vector3 (-1f, 0f, 0f); joint.swingAxis = new Vector3 (0f, 0f, 1f); SoftJointLimit lowTwistLimitNew = joint.lowTwistLimit; lowTwistLimitNew.limit = -40f; lowTwistLimitNew.spring = 0f; lowTwistLimitNew.damper = 0f; lowTwistLimitNew.bounciness = 0f; joint.lowTwistLimit = lowTwistLimitNew; SoftJointLimit highTwistLimitNew = joint.highTwistLimit; highTwistLimitNew.limit = 25f; highTwistLimitNew.spring = 0f; highTwistLimitNew.damper = 0f; highTwistLimitNew.bounciness = 0f; joint.highTwistLimit = highTwistLimitNew; SoftJointLimit swing1LimitNew = joint.swing1Limit; swing1LimitNew.limit = 25f; swing1LimitNew.spring = 0f; swing1LimitNew.damper = 0f; swing1LimitNew.bounciness = 0f; joint.swing1Limit = swing1LimitNew; SoftJointLimit swing2LimitNew = joint.swing2Limit; swing2LimitNew.limit = 0f; swing2LimitNew.spring = 0f; swing2LimitNew.damper = 0f; swing2LimitNew.bounciness = 0f; joint.swing2Limit = swing2LimitNew; Transform parentTransform = gameObject.transform.FindChild ("Armature/Hips/Spine/Ribs"); if (parentTransform == null) { Debug.LogWarning ("parentGameObject for " + childGameObject.name + " not found! Maybe initalisation is not yet done."); joint.connectedBody = null; } else { joint.connectedBody = parentTransform.gameObject.rigidbody; } allCharacterJoints.Add (joint); return joint; } internal virtual Collider CreateCollider_UpperArm_L(GameObject gameObject, string name, string path) { Transform childTransform = gameObject.transform.FindChild (path); GameObject childGameObject = childTransform.gameObject; Collider collider = childGameObject.GetComponent <Collider> (); if (collider != null) { Debug.LogWarning ("Existing collider " + collider.name + " found of type " + collider.GetType ()); return null; } upperArm_L_CapsuleCollider = childGameObject.AddComponent<CapsuleCollider> (); collider = upperArm_L_CapsuleCollider; upperArm_L_CapsuleCollider.height = 0.2798699f; upperArm_L_CapsuleCollider.center = new Vector3 (-0.1399349f, 0f, 0f); upperArm_L_CapsuleCollider.radius = 0.06996747f; upperArm_L_CapsuleCollider.direction = 0; collider.isTrigger = false; collider.material = (PhysicMaterial) Resources.Load ("RuntimeMaterials/Physic/PlayerPhysicMaterial", typeof(PhysicMaterial)); allColliders.Add (collider); return collider; } internal virtual Rigidbody CreateRigidbody_UpperArm_L(GameObject gameObject, string name, string path) { Transform childTransform = gameObject.transform.FindChild (path); GameObject childGameObject = childTransform.gameObject; Rigidbody rigidbody = childGameObject.GetComponent <Rigidbody> (); if (rigidbody != null) { Debug.LogWarning ("Existing rigidbody " + rigidbody.name + " found"); return null; } rigidbody = childGameObject.AddComponent <Rigidbody> (); upperArm_L_Rigidbody= rigidbody; rigidbody.isKinematic = true; rigidbody.useGravity = true; rigidbody.mass = 1.25f; rigidbody.drag = 0f; rigidbody.angularDrag = 0.05f; rigidbody.interpolation = RigidbodyInterpolation.None; rigidbody.detectCollisions = true; rigidbody.constraints = RigidbodyConstraints.None; allRigidbodies.Add (rigidbody); return rigidbody; } internal virtual CharacterJoint CreateCharacterJoint_UpperArm_L(GameObject gameObject, string name, string path) { Transform childTransform = gameObject.transform.FindChild (path); GameObject childGameObject = childTransform.gameObject; CharacterJoint joint = childGameObject.GetComponent <CharacterJoint> (); if (joint != null) { Debug.LogWarning ("Existing joint " + joint.name + " found"); return null; } joint = childGameObject.AddComponent <CharacterJoint> (); upperArm_L_CharacterJoint= joint; joint.breakForce = Mathf.Infinity; joint.breakTorque = Mathf.Infinity; joint.anchor = new Vector3 (0f, 0f, 0f); joint.axis = new Vector3 (0f, -1f, 0f); joint.swingAxis = new Vector3 (0f, 0f, -1f); SoftJointLimit lowTwistLimitNew = joint.lowTwistLimit; lowTwistLimitNew.limit = -70f; lowTwistLimitNew.spring = 0f; lowTwistLimitNew.damper = 0f; lowTwistLimitNew.bounciness = 0f; joint.lowTwistLimit = lowTwistLimitNew; SoftJointLimit highTwistLimitNew = joint.highTwistLimit; highTwistLimitNew.limit = 10f; highTwistLimitNew.spring = 0f; highTwistLimitNew.damper = 0f; highTwistLimitNew.bounciness = 0f; joint.highTwistLimit = highTwistLimitNew; SoftJointLimit swing1LimitNew = joint.swing1Limit; swing1LimitNew.limit = 50f; swing1LimitNew.spring = 0f; swing1LimitNew.damper = 0f; swing1LimitNew.bounciness = 0f; joint.swing1Limit = swing1LimitNew; SoftJointLimit swing2LimitNew = joint.swing2Limit; swing2LimitNew.limit = 0f; swing2LimitNew.spring = 0f; swing2LimitNew.damper = 0f; swing2LimitNew.bounciness = 0f; joint.swing2Limit = swing2LimitNew; Transform parentTransform = gameObject.transform.FindChild ("Armature/Hips/Spine/Ribs"); if (parentTransform == null) { Debug.LogWarning ("parentGameObject for " + childGameObject.name + " not found! Maybe initalisation is not yet done."); joint.connectedBody = null; } else { joint.connectedBody = parentTransform.gameObject.rigidbody; } allCharacterJoints.Add (joint); return joint; } internal virtual Collider CreateCollider_LowerArm_L(GameObject gameObject, string name, string path) { Transform childTransform = gameObject.transform.FindChild (path); GameObject childGameObject = childTransform.gameObject; Collider collider = childGameObject.GetComponent <Collider> (); if (collider != null) { Debug.LogWarning ("Existing collider " + collider.name + " found of type " + collider.GetType ()); return null; } lowerArm_L_CapsuleCollider = childGameObject.AddComponent<CapsuleCollider> (); collider = lowerArm_L_CapsuleCollider; lowerArm_L_CapsuleCollider.height = 0.1698555f; lowerArm_L_CapsuleCollider.center = new Vector3 (-0.08492777f, 0f, 0f); lowerArm_L_CapsuleCollider.radius = 0.03397111f; lowerArm_L_CapsuleCollider.direction = 0; collider.isTrigger = false; collider.material = (PhysicMaterial) Resources.Load ("RuntimeMaterials/Physic/PlayerPhysicMaterial", typeof(PhysicMaterial)); allColliders.Add (collider); return collider; } internal virtual Rigidbody CreateRigidbody_LowerArm_L(GameObject gameObject, string name, string path) { Transform childTransform = gameObject.transform.FindChild (path); GameObject childGameObject = childTransform.gameObject; Rigidbody rigidbody = childGameObject.GetComponent <Rigidbody> (); if (rigidbody != null) { Debug.LogWarning ("Existing rigidbody " + rigidbody.name + " found"); return null; } rigidbody = childGameObject.AddComponent <Rigidbody> (); lowerArm_L_Rigidbody= rigidbody; rigidbody.isKinematic = true; rigidbody.useGravity = true; rigidbody.mass = 1.25f; rigidbody.drag = 0f; rigidbody.angularDrag = 0.05f; rigidbody.interpolation = RigidbodyInterpolation.None; rigidbody.detectCollisions = true; rigidbody.constraints = RigidbodyConstraints.None; allRigidbodies.Add (rigidbody); return rigidbody; } internal virtual CharacterJoint CreateCharacterJoint_LowerArm_L(GameObject gameObject, string name, string path) { Transform childTransform = gameObject.transform.FindChild (path); GameObject childGameObject = childTransform.gameObject; CharacterJoint joint = childGameObject.GetComponent <CharacterJoint> (); if (joint != null) { Debug.LogWarning ("Existing joint " + joint.name + " found"); return null; } joint = childGameObject.AddComponent <CharacterJoint> (); lowerArm_L_CharacterJoint= joint; joint.breakForce = Mathf.Infinity; joint.breakTorque = Mathf.Infinity; joint.anchor = new Vector3 (0f, 0f, 0f); joint.axis = new Vector3 (0f, 0f, -1f); joint.swingAxis = new Vector3 (0f, -1f, 0f); SoftJointLimit lowTwistLimitNew = joint.lowTwistLimit; lowTwistLimitNew.limit = -90f; lowTwistLimitNew.spring = 0f; lowTwistLimitNew.damper = 0f; lowTwistLimitNew.bounciness = 0f; joint.lowTwistLimit = lowTwistLimitNew; SoftJointLimit highTwistLimitNew = joint.highTwistLimit; highTwistLimitNew.limit = 0f; highTwistLimitNew.spring = 0f; highTwistLimitNew.damper = 0f; highTwistLimitNew.bounciness = 0f; joint.highTwistLimit = highTwistLimitNew; SoftJointLimit swing1LimitNew = joint.swing1Limit; swing1LimitNew.limit = 0f; swing1LimitNew.spring = 0f; swing1LimitNew.damper = 0f; swing1LimitNew.bounciness = 0f; joint.swing1Limit = swing1LimitNew; SoftJointLimit swing2LimitNew = joint.swing2Limit; swing2LimitNew.limit = 0f; swing2LimitNew.spring = 0f; swing2LimitNew.damper = 0f; swing2LimitNew.bounciness = 0f; joint.swing2Limit = swing2LimitNew; Transform parentTransform = gameObject.transform.FindChild ("Armature/Hips/Spine/Ribs/Shoulder_L/UpperArm_L"); if (parentTransform == null) { Debug.LogWarning ("parentGameObject for " + childGameObject.name + " not found! Maybe initalisation is not yet done."); joint.connectedBody = null; } else { joint.connectedBody = parentTransform.gameObject.rigidbody; } allCharacterJoints.Add (joint); return joint; } internal virtual Collider CreateCollider_UpperArm_R(GameObject gameObject, string name, string path) { Transform childTransform = gameObject.transform.FindChild (path); GameObject childGameObject = childTransform.gameObject; Collider collider = childGameObject.GetComponent <Collider> (); if (collider != null) { Debug.LogWarning ("Existing collider " + collider.name + " found of type " + collider.GetType ()); return null; } upperArm_R_CapsuleCollider = childGameObject.AddComponent<CapsuleCollider> (); collider = upperArm_R_CapsuleCollider; upperArm_R_CapsuleCollider.height = 0.2798699f; upperArm_R_CapsuleCollider.center = new Vector3 (-0.1399349f, 0f, 0f); upperArm_R_CapsuleCollider.radius = 0.06996746f; upperArm_R_CapsuleCollider.direction = 0; collider.isTrigger = false; collider.material = (PhysicMaterial) Resources.Load ("RuntimeMaterials/Physic/PlayerPhysicMaterial", typeof(PhysicMaterial)); allColliders.Add (collider); return collider; } internal virtual Rigidbody CreateRigidbody_UpperArm_R(GameObject gameObject, string name, string path) { Transform childTransform = gameObject.transform.FindChild (path); GameObject childGameObject = childTransform.gameObject; Rigidbody rigidbody = childGameObject.GetComponent <Rigidbody> (); if (rigidbody != null) { Debug.LogWarning ("Existing rigidbody " + rigidbody.name + " found"); return null; } rigidbody = childGameObject.AddComponent <Rigidbody> (); upperArm_R_Rigidbody= rigidbody; rigidbody.isKinematic = true; rigidbody.useGravity = true; rigidbody.mass = 1.25f; rigidbody.drag = 0f; rigidbody.angularDrag = 0.05f; rigidbody.interpolation = RigidbodyInterpolation.None; rigidbody.detectCollisions = true; rigidbody.constraints = RigidbodyConstraints.None; allRigidbodies.Add (rigidbody); return rigidbody; } internal virtual CharacterJoint CreateCharacterJoint_UpperArm_R(GameObject gameObject, string name, string path) { Transform childTransform = gameObject.transform.FindChild (path); GameObject childGameObject = childTransform.gameObject; CharacterJoint joint = childGameObject.GetComponent <CharacterJoint> (); if (joint != null) { Debug.LogWarning ("Existing joint " + joint.name + " found"); return null; } joint = childGameObject.AddComponent <CharacterJoint> (); upperArm_R_CharacterJoint= joint; joint.breakForce = Mathf.Infinity; joint.breakTorque = Mathf.Infinity; joint.anchor = new Vector3 (0f, 0f, 0f); joint.axis = new Vector3 (0f, -1f, 0f); joint.swingAxis = new Vector3 (0f, 0f, -1f); SoftJointLimit lowTwistLimitNew = joint.lowTwistLimit; lowTwistLimitNew.limit = -70f; lowTwistLimitNew.spring = 0f; lowTwistLimitNew.damper = 0f; lowTwistLimitNew.bounciness = 0f; joint.lowTwistLimit = lowTwistLimitNew; SoftJointLimit highTwistLimitNew = joint.highTwistLimit; highTwistLimitNew.limit = 10f; highTwistLimitNew.spring = 0f; highTwistLimitNew.damper = 0f; highTwistLimitNew.bounciness = 0f; joint.highTwistLimit = highTwistLimitNew; SoftJointLimit swing1LimitNew = joint.swing1Limit; swing1LimitNew.limit = 50f; swing1LimitNew.spring = 0f; swing1LimitNew.damper = 0f; swing1LimitNew.bounciness = 0f; joint.swing1Limit = swing1LimitNew; SoftJointLimit swing2LimitNew = joint.swing2Limit; swing2LimitNew.limit = 0f; swing2LimitNew.spring = 0f; swing2LimitNew.damper = 0f; swing2LimitNew.bounciness = 0f; joint.swing2Limit = swing2LimitNew; Transform parentTransform = gameObject.transform.FindChild ("Armature/Hips/Spine/Ribs"); if (parentTransform == null) { Debug.LogWarning ("parentGameObject for " + childGameObject.name + " not found! Maybe initalisation is not yet done."); joint.connectedBody = null; } else { joint.connectedBody = parentTransform.gameObject.rigidbody; } allCharacterJoints.Add (joint); return joint; } internal virtual Collider CreateCollider_LowerArm_R(GameObject gameObject, string name, string path) { Transform childTransform = gameObject.transform.FindChild (path); GameObject childGameObject = childTransform.gameObject; Collider collider = childGameObject.GetComponent <Collider> (); if (collider != null) { Debug.LogWarning ("Existing collider " + collider.name + " found of type " + collider.GetType ()); return null; } lowerArm_R_CapsuleCollider = childGameObject.AddComponent<CapsuleCollider> (); collider = lowerArm_R_CapsuleCollider; lowerArm_R_CapsuleCollider.height = 0.1698554f; lowerArm_R_CapsuleCollider.center = new Vector3 (-0.0849277f, 0f, 0f); lowerArm_R_CapsuleCollider.radius = 0.03397108f; lowerArm_R_CapsuleCollider.direction = 0; collider.isTrigger = false; collider.material = (PhysicMaterial) Resources.Load ("RuntimeMaterials/Physic/PlayerPhysicMaterial", typeof(PhysicMaterial)); allColliders.Add (collider); return collider; } internal virtual Rigidbody CreateRigidbody_LowerArm_R(GameObject gameObject, string name, string path) { Transform childTransform = gameObject.transform.FindChild (path); GameObject childGameObject = childTransform.gameObject; Rigidbody rigidbody = childGameObject.GetComponent <Rigidbody> (); if (rigidbody != null) { Debug.LogWarning ("Existing rigidbody " + rigidbody.name + " found"); return null; } rigidbody = childGameObject.AddComponent <Rigidbody> (); lowerArm_R_Rigidbody= rigidbody; rigidbody.isKinematic = true; rigidbody.useGravity = true; rigidbody.mass = 1.25f; rigidbody.drag = 0f; rigidbody.angularDrag = 0.05f; rigidbody.interpolation = RigidbodyInterpolation.None; rigidbody.detectCollisions = true; rigidbody.constraints = RigidbodyConstraints.None; allRigidbodies.Add (rigidbody); return rigidbody; } internal virtual CharacterJoint CreateCharacterJoint_LowerArm_R(GameObject gameObject, string name, string path) { Transform childTransform = gameObject.transform.FindChild (path); GameObject childGameObject = childTransform.gameObject; CharacterJoint joint = childGameObject.GetComponent <CharacterJoint> (); if (joint != null) { Debug.LogWarning ("Existing joint " + joint.name + " found"); return null; } joint = childGameObject.AddComponent <CharacterJoint> (); lowerArm_R_CharacterJoint= joint; joint.breakForce = Mathf.Infinity; joint.breakTorque = Mathf.Infinity; joint.anchor = new Vector3 (0f, 0f, 0f); joint.axis = new Vector3 (0f, 0f, -1f); joint.swingAxis = new Vector3 (0f, -1f, 0f); SoftJointLimit lowTwistLimitNew = joint.lowTwistLimit; lowTwistLimitNew.limit = -90f; lowTwistLimitNew.spring = 0f; lowTwistLimitNew.damper = 0f; lowTwistLimitNew.bounciness = 0f; joint.lowTwistLimit = lowTwistLimitNew; SoftJointLimit highTwistLimitNew = joint.highTwistLimit; highTwistLimitNew.limit = 0f; highTwistLimitNew.spring = 0f; highTwistLimitNew.damper = 0f; highTwistLimitNew.bounciness = 0f; joint.highTwistLimit = highTwistLimitNew; SoftJointLimit swing1LimitNew = joint.swing1Limit; swing1LimitNew.limit = 0f; swing1LimitNew.spring = 0f; swing1LimitNew.damper = 0f; swing1LimitNew.bounciness = 0f; joint.swing1Limit = swing1LimitNew; SoftJointLimit swing2LimitNew = joint.swing2Limit; swing2LimitNew.limit = 0f; swing2LimitNew.spring = 0f; swing2LimitNew.damper = 0f; swing2LimitNew.bounciness = 0f; joint.swing2Limit = swing2LimitNew; Transform parentTransform = gameObject.transform.FindChild ("Armature/Hips/Spine/Ribs/Shoulder_R/UpperArm_R"); if (parentTransform == null) { Debug.LogWarning ("parentGameObject for " + childGameObject.name + " not found! Maybe initalisation is not yet done."); joint.connectedBody = null; } else { joint.connectedBody = parentTransform.gameObject.rigidbody; } allCharacterJoints.Add (joint); return joint; } internal virtual Collider CreateCollider_Thigh_L(GameObject gameObject, string name, string path) { Transform childTransform = gameObject.transform.FindChild (path); GameObject childGameObject = childTransform.gameObject; Collider collider = childGameObject.GetComponent <Collider> (); if (collider != null) { Debug.LogWarning ("Existing collider " + collider.name + " found of type " + collider.GetType ()); return null; } thigh_L_CapsuleCollider = childGameObject.AddComponent<CapsuleCollider> (); collider = thigh_L_CapsuleCollider; thigh_L_CapsuleCollider.height = 0.3249351f; thigh_L_CapsuleCollider.center = new Vector3 (-0.1624676f, 0f, 0f); thigh_L_CapsuleCollider.radius = 0.09748054f; thigh_L_CapsuleCollider.direction = 0; collider.isTrigger = false; collider.material = (PhysicMaterial) Resources.Load ("RuntimeMaterials/Physic/PlayerPhysicMaterial", typeof(PhysicMaterial)); allColliders.Add (collider); return collider; } internal virtual Rigidbody CreateRigidbody_Thigh_L(GameObject gameObject, string name, string path) { Transform childTransform = gameObject.transform.FindChild (path); GameObject childGameObject = childTransform.gameObject; Rigidbody rigidbody = childGameObject.GetComponent <Rigidbody> (); if (rigidbody != null) { Debug.LogWarning ("Existing rigidbody " + rigidbody.name + " found"); return null; } rigidbody = childGameObject.AddComponent <Rigidbody> (); thigh_L_Rigidbody= rigidbody; rigidbody.isKinematic = true; rigidbody.useGravity = true; rigidbody.mass = 1.875f; rigidbody.drag = 0f; rigidbody.angularDrag = 0.05f; rigidbody.interpolation = RigidbodyInterpolation.None; rigidbody.detectCollisions = true; rigidbody.constraints = RigidbodyConstraints.None; allRigidbodies.Add (rigidbody); return rigidbody; } internal virtual CharacterJoint CreateCharacterJoint_Thigh_L(GameObject gameObject, string name, string path) { Transform childTransform = gameObject.transform.FindChild (path); GameObject childGameObject = childTransform.gameObject; CharacterJoint joint = childGameObject.GetComponent <CharacterJoint> (); if (joint != null) { Debug.LogWarning ("Existing joint " + joint.name + " found"); return null; } joint = childGameObject.AddComponent <CharacterJoint> (); thigh_L_CharacterJoint= joint; joint.breakForce = Mathf.Infinity; joint.breakTorque = Mathf.Infinity; joint.anchor = new Vector3 (0f, 0f, 0f); joint.axis = new Vector3 (1f, 0f, 0f); joint.swingAxis = new Vector3 (0f, 0f, -1f); SoftJointLimit lowTwistLimitNew = joint.lowTwistLimit; lowTwistLimitNew.limit = -20f; lowTwistLimitNew.spring = 0f; lowTwistLimitNew.damper = 0f; lowTwistLimitNew.bounciness = 0f; joint.lowTwistLimit = lowTwistLimitNew; SoftJointLimit highTwistLimitNew = joint.highTwistLimit; highTwistLimitNew.limit = 70f; highTwistLimitNew.spring = 0f; highTwistLimitNew.damper = 0f; highTwistLimitNew.bounciness = 0f; joint.highTwistLimit = highTwistLimitNew; SoftJointLimit swing1LimitNew = joint.swing1Limit; swing1LimitNew.limit = 30f; swing1LimitNew.spring = 0f; swing1LimitNew.damper = 0f; swing1LimitNew.bounciness = 0f; joint.swing1Limit = swing1LimitNew; SoftJointLimit swing2LimitNew = joint.swing2Limit; swing2LimitNew.limit = 0f; swing2LimitNew.spring = 0f; swing2LimitNew.damper = 0f; swing2LimitNew.bounciness = 0f; joint.swing2Limit = swing2LimitNew; Transform parentTransform = gameObject.transform.FindChild ("Armature/Hips"); if (parentTransform == null) { Debug.LogWarning ("parentGameObject for " + childGameObject.name + " not found! Maybe initalisation is not yet done."); joint.connectedBody = null; } else { joint.connectedBody = parentTransform.gameObject.rigidbody; } allCharacterJoints.Add (joint); return joint; } internal virtual Collider CreateCollider_Shin_L(GameObject gameObject, string name, string path) { Transform childTransform = gameObject.transform.FindChild (path); GameObject childGameObject = childTransform.gameObject; Collider collider = childGameObject.GetComponent <Collider> (); if (collider != null) { Debug.LogWarning ("Existing collider " + collider.name + " found of type " + collider.GetType ()); return null; } shin_L_CapsuleCollider = childGameObject.AddComponent<CapsuleCollider> (); collider = shin_L_CapsuleCollider; shin_L_CapsuleCollider.height = 0.3590847f; shin_L_CapsuleCollider.center = new Vector3 (-0.1795424f, 0f, 0f); shin_L_CapsuleCollider.radius = 0.08977118f; shin_L_CapsuleCollider.direction = 0; collider.isTrigger = false; collider.material = (PhysicMaterial) Resources.Load ("RuntimeMaterials/Physic/PlayerPhysicMaterial", typeof(PhysicMaterial)); allColliders.Add (collider); return collider; } internal virtual Rigidbody CreateRigidbody_Shin_L(GameObject gameObject, string name, string path) { Transform childTransform = gameObject.transform.FindChild (path); GameObject childGameObject = childTransform.gameObject; Rigidbody rigidbody = childGameObject.GetComponent <Rigidbody> (); if (rigidbody != null) { Debug.LogWarning ("Existing rigidbody " + rigidbody.name + " found"); return null; } rigidbody = childGameObject.AddComponent <Rigidbody> (); shin_L_Rigidbody= rigidbody; rigidbody.isKinematic = true; rigidbody.useGravity = true; rigidbody.mass = 1.875f; rigidbody.drag = 0f; rigidbody.angularDrag = 0.05f; rigidbody.interpolation = RigidbodyInterpolation.None; rigidbody.detectCollisions = true; rigidbody.constraints = RigidbodyConstraints.None; allRigidbodies.Add (rigidbody); return rigidbody; } internal virtual CharacterJoint CreateCharacterJoint_Shin_L(GameObject gameObject, string name, string path) { Transform childTransform = gameObject.transform.FindChild (path); GameObject childGameObject = childTransform.gameObject; CharacterJoint joint = childGameObject.GetComponent <CharacterJoint> (); if (joint != null) { Debug.LogWarning ("Existing joint " + joint.name + " found"); return null; } joint = childGameObject.AddComponent <CharacterJoint> (); shin_L_CharacterJoint= joint; joint.breakForce = Mathf.Infinity; joint.breakTorque = Mathf.Infinity; joint.anchor = new Vector3 (0f, 0f, 0f); joint.axis = new Vector3 (1f, 0f, 0f); joint.swingAxis = new Vector3 (0f, 0f, -1f); SoftJointLimit lowTwistLimitNew = joint.lowTwistLimit; lowTwistLimitNew.limit = -80f; lowTwistLimitNew.spring = 0f; lowTwistLimitNew.damper = 0f; lowTwistLimitNew.bounciness = 0f; joint.lowTwistLimit = lowTwistLimitNew; SoftJointLimit highTwistLimitNew = joint.highTwistLimit; highTwistLimitNew.limit = 0f; highTwistLimitNew.spring = 0f; highTwistLimitNew.damper = 0f; highTwistLimitNew.bounciness = 0f; joint.highTwistLimit = highTwistLimitNew; SoftJointLimit swing1LimitNew = joint.swing1Limit; swing1LimitNew.limit = 0f; swing1LimitNew.spring = 0f; swing1LimitNew.damper = 0f; swing1LimitNew.bounciness = 0f; joint.swing1Limit = swing1LimitNew; SoftJointLimit swing2LimitNew = joint.swing2Limit; swing2LimitNew.limit = 0f; swing2LimitNew.spring = 0f; swing2LimitNew.damper = 0f; swing2LimitNew.bounciness = 0f; joint.swing2Limit = swing2LimitNew; Transform parentTransform = gameObject.transform.FindChild ("Armature/Hips/Thigh_L"); if (parentTransform == null) { Debug.LogWarning ("parentGameObject for " + childGameObject.name + " not found! Maybe initalisation is not yet done."); joint.connectedBody = null; } else { joint.connectedBody = parentTransform.gameObject.rigidbody; } allCharacterJoints.Add (joint); return joint; } internal virtual Collider CreateCollider_Thigh_R(GameObject gameObject, string name, string path) { Transform childTransform = gameObject.transform.FindChild (path); GameObject childGameObject = childTransform.gameObject; Collider collider = childGameObject.GetComponent <Collider> (); if (collider != null) { Debug.LogWarning ("Existing collider " + collider.name + " found of type " + collider.GetType ()); return null; } thigh_R_CapsuleCollider = childGameObject.AddComponent<CapsuleCollider> (); collider = thigh_R_CapsuleCollider; thigh_R_CapsuleCollider.height = 0.3249351f; thigh_R_CapsuleCollider.center = new Vector3 (-0.1624675f, 0f, 0f); thigh_R_CapsuleCollider.radius = 0.09748053f; thigh_R_CapsuleCollider.direction = 0; collider.isTrigger = false; collider.material = (PhysicMaterial) Resources.Load ("RuntimeMaterials/Physic/PlayerPhysicMaterial", typeof(PhysicMaterial)); allColliders.Add (collider); return collider; } internal virtual Rigidbody CreateRigidbody_Thigh_R(GameObject gameObject, string name, string path) { Transform childTransform = gameObject.transform.FindChild (path); GameObject childGameObject = childTransform.gameObject; Rigidbody rigidbody = childGameObject.GetComponent <Rigidbody> (); if (rigidbody != null) { Debug.LogWarning ("Existing rigidbody " + rigidbody.name + " found"); return null; } rigidbody = childGameObject.AddComponent <Rigidbody> (); thigh_R_Rigidbody= rigidbody; rigidbody.isKinematic = true; rigidbody.useGravity = true; rigidbody.mass = 1.875f; rigidbody.drag = 0f; rigidbody.angularDrag = 0.05f; rigidbody.interpolation = RigidbodyInterpolation.None; rigidbody.detectCollisions = true; rigidbody.constraints = RigidbodyConstraints.None; allRigidbodies.Add (rigidbody); return rigidbody; } internal virtual CharacterJoint CreateCharacterJoint_Thigh_R(GameObject gameObject, string name, string path) { Transform childTransform = gameObject.transform.FindChild (path); GameObject childGameObject = childTransform.gameObject; CharacterJoint joint = childGameObject.GetComponent <CharacterJoint> (); if (joint != null) { Debug.LogWarning ("Existing joint " + joint.name + " found"); return null; } joint = childGameObject.AddComponent <CharacterJoint> (); thigh_R_CharacterJoint= joint; joint.breakForce = Mathf.Infinity; joint.breakTorque = Mathf.Infinity; joint.anchor = new Vector3 (0f, 0f, 0f); joint.axis = new Vector3 (1f, 0f, 0f); joint.swingAxis = new Vector3 (0f, 0f, -1f); SoftJointLimit lowTwistLimitNew = joint.lowTwistLimit; lowTwistLimitNew.limit = -20f; lowTwistLimitNew.spring = 0f; lowTwistLimitNew.damper = 0f; lowTwistLimitNew.bounciness = 0f; joint.lowTwistLimit = lowTwistLimitNew; SoftJointLimit highTwistLimitNew = joint.highTwistLimit; highTwistLimitNew.limit = 70f; highTwistLimitNew.spring = 0f; highTwistLimitNew.damper = 0f; highTwistLimitNew.bounciness = 0f; joint.highTwistLimit = highTwistLimitNew; SoftJointLimit swing1LimitNew = joint.swing1Limit; swing1LimitNew.limit = 30f; swing1LimitNew.spring = 0f; swing1LimitNew.damper = 0f; swing1LimitNew.bounciness = 0f; joint.swing1Limit = swing1LimitNew; SoftJointLimit swing2LimitNew = joint.swing2Limit; swing2LimitNew.limit = 0f; swing2LimitNew.spring = 0f; swing2LimitNew.damper = 0f; swing2LimitNew.bounciness = 0f; joint.swing2Limit = swing2LimitNew; Transform parentTransform = gameObject.transform.FindChild ("Armature/Hips"); if (parentTransform == null) { Debug.LogWarning ("parentGameObject for " + childGameObject.name + " not found! Maybe initalisation is not yet done."); joint.connectedBody = null; } else { joint.connectedBody = parentTransform.gameObject.rigidbody; } allCharacterJoints.Add (joint); return joint; } internal virtual Collider CreateCollider_Shin_R(GameObject gameObject, string name, string path) { Transform childTransform = gameObject.transform.FindChild (path); GameObject childGameObject = childTransform.gameObject; Collider collider = childGameObject.GetComponent <Collider> (); if (collider != null) { Debug.LogWarning ("Existing collider " + collider.name + " found of type " + collider.GetType ()); return null; } shin_R_CapsuleCollider = childGameObject.AddComponent<CapsuleCollider> (); collider = shin_R_CapsuleCollider; shin_R_CapsuleCollider.height = 0.3590847f; shin_R_CapsuleCollider.center = new Vector3 (-0.1795424f, 0f, 0f); shin_R_CapsuleCollider.radius = 0.08977118f; shin_R_CapsuleCollider.direction = 0; collider.isTrigger = false; collider.material = (PhysicMaterial) Resources.Load ("RuntimeMaterials/Physic/PlayerPhysicMaterial", typeof(PhysicMaterial)); allColliders.Add (collider); return collider; } internal virtual Rigidbody CreateRigidbody_Shin_R(GameObject gameObject, string name, string path) { Transform childTransform = gameObject.transform.FindChild (path); GameObject childGameObject = childTransform.gameObject; Rigidbody rigidbody = childGameObject.GetComponent <Rigidbody> (); if (rigidbody != null) { Debug.LogWarning ("Existing rigidbody " + rigidbody.name + " found"); return null; } rigidbody = childGameObject.AddComponent <Rigidbody> (); shin_R_Rigidbody= rigidbody; rigidbody.isKinematic = true; rigidbody.useGravity = true; rigidbody.mass = 1.875f; rigidbody.drag = 0f; rigidbody.angularDrag = 0.05f; rigidbody.interpolation = RigidbodyInterpolation.None; rigidbody.detectCollisions = true; rigidbody.constraints = RigidbodyConstraints.None; allRigidbodies.Add (rigidbody); return rigidbody; } internal virtual CharacterJoint CreateCharacterJoint_Shin_R(GameObject gameObject, string name, string path) { Transform childTransform = gameObject.transform.FindChild (path); GameObject childGameObject = childTransform.gameObject; CharacterJoint joint = childGameObject.GetComponent <CharacterJoint> (); if (joint != null) { Debug.LogWarning ("Existing joint " + joint.name + " found"); return null; } joint = childGameObject.AddComponent <CharacterJoint> (); shin_R_CharacterJoint= joint; joint.breakForce = Mathf.Infinity; joint.breakTorque = Mathf.Infinity; joint.anchor = new Vector3 (0f, 0f, 0f); joint.axis = new Vector3 (1f, 0f, 0f); joint.swingAxis = new Vector3 (0f, 0f, -1f); SoftJointLimit lowTwistLimitNew = joint.lowTwistLimit; lowTwistLimitNew.limit = -80f; lowTwistLimitNew.spring = 0f; lowTwistLimitNew.damper = 0f; lowTwistLimitNew.bounciness = 0f; joint.lowTwistLimit = lowTwistLimitNew; SoftJointLimit highTwistLimitNew = joint.highTwistLimit; highTwistLimitNew.limit = 0f; highTwistLimitNew.spring = 0f; highTwistLimitNew.damper = 0f; highTwistLimitNew.bounciness = 0f; joint.highTwistLimit = highTwistLimitNew; SoftJointLimit swing1LimitNew = joint.swing1Limit; swing1LimitNew.limit = 0f; swing1LimitNew.spring = 0f; swing1LimitNew.damper = 0f; swing1LimitNew.bounciness = 0f; joint.swing1Limit = swing1LimitNew; SoftJointLimit swing2LimitNew = joint.swing2Limit; swing2LimitNew.limit = 0f; swing2LimitNew.spring = 0f; swing2LimitNew.damper = 0f; swing2LimitNew.bounciness = 0f; joint.swing2Limit = swing2LimitNew; Transform parentTransform = gameObject.transform.FindChild ("Armature/Hips/Thigh_R"); if (parentTransform == null) { Debug.LogWarning ("parentGameObject for " + childGameObject.name + " not found! Maybe initalisation is not yet done."); joint.connectedBody = null; } else { joint.connectedBody = parentTransform.gameObject.rigidbody; } allCharacterJoints.Add (joint); return joint; } }
/* * Copyright (c) 2010-2015 Pivotal Software, 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. See accompanying * LICENSE file. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Diagnostics; using AdoNetTest.BIN.Configuration; namespace AdoNetTest.BIN { class GFXDServer { /// <summary> /// Configurable class member properties /// </summary> private static int numServers; private static string installPath; private static string scriptFile; private static string defaultServerDir; private static string defaultClientBindAddress; private static int defaultClientPort; private static int mcastPort; private static string drdaDebug; private static string logLevel; private static string logDir; private static string serverScript; private static int serverCount = 0; private static Logger.Logger logger; private static object locker = new object(); /// <summary> /// Instance member properties /// </summary> private string serverDir; private string clientBindAddress; private int clientPort; private GFXDLocator locator; public string ServerName { get; set; } public GFXDState ServerState { get; set; } public GFXDServer() { LoadConfig(); if (logger != null) logger.Close(); logger = new Logger.Logger(logDir, String.Format("{0}.log", typeof(GFXDServer).FullName)); if (numServers == 1) mcastPort = 0; clientBindAddress = defaultClientBindAddress; clientPort = defaultClientPort + (serverCount++); ServerName = string.Format("{0}{1}", defaultServerDir, serverCount); serverDir = string.Format(@"{0}\{1}", installPath, ServerName); this.ServerState = GFXDState.STOPPED; } public GFXDServer(GFXDLocator locator) : this() { this.locator = locator; } public static void LoadConfig() { numServers = int.Parse(GFXDConfigManager.GetServerSetting("numServers")); //installPath = GFXDConfigManager.GetServerSetting("installPath"); installPath = Environment.GetEnvironmentVariable("GEMFIREXD"); scriptFile = GFXDConfigManager.GetServerSetting("scriptFile"); defaultServerDir = GFXDConfigManager.GetServerSetting("defaultServerDir"); defaultClientBindAddress = GFXDConfigManager.GetServerSetting("defaultClientBindAddress"); defaultClientPort = int.Parse(GFXDConfigManager.GetServerSetting("defaultClientPort")); mcastPort = int.Parse(GFXDConfigManager.GetServerSetting("mcastPort")); drdaDebug = GFXDConfigManager.GetServerSetting("drdaDebug"); logLevel = GFXDConfigManager.GetServerSetting("logLevel"); //logDir = GFXDConfigManager.GetClientSetting("logDir"); logDir = Environment.GetEnvironmentVariable("GFXDADOOUTDIR"); serverScript = String.Format(@"{0}\{1}", installPath, scriptFile); } public void Start() { Log(String.Format("Starting server {0}, serverState: {1}", ServerName, ServerState)); Log(String.Format("serverScript: {0}, startCommand: {1}", serverScript, GetStartCmd())); if (this.ServerState == GFXDState.STARTED) return; ProcessStartInfo psinfo = new ProcessStartInfo(serverScript, GetStartCmd()); psinfo.UseShellExecute = true; psinfo.WindowStyle = ProcessWindowStyle.Hidden; Process proc = new Process(); proc.StartInfo = psinfo; if (!proc.Start()) { String msg = "Failed to start eslasticsql process."; Log(msg); throw new Exception(String.Format("Exception: {0}", msg)); } bool started = proc.WaitForExit(60000); if (!started) { proc.Kill(); String msg = "Timeout waiting for elasticsql process to start."; Log(msg); throw new Exception(String.Format("Exception: {0}", msg)); } this.ServerState = GFXDState.STARTED; Log(String.Format("Server {0} started, serverState: {1}", ServerName, ServerState)); } public void Stop(bool removeDir) { Log(String.Format("Stopping server {0}, serverState: {1}", ServerName, ServerState)); Log(String.Format("serverScript: {0}, stopCommand: {1}", serverScript, GetStopCmd())); if (this.ServerState == GFXDState.STOPPED) return; ProcessStartInfo psinfo = new ProcessStartInfo(serverScript, GetStopCmd()); psinfo.UseShellExecute = true; psinfo.WindowStyle = ProcessWindowStyle.Hidden; Process proc = new Process(); proc.StartInfo = psinfo; if (!proc.Start()) { String msg = "Failed to stop elasticsql process."; Log(msg); throw new Exception(String.Format("Exception: {0}", msg)); } bool started = proc.WaitForExit(60000); if (!started) { proc.Kill(); String msg = "Timeout waiting for elasticsql process to stop."; Log(msg); throw new Exception(String.Format("Exception: {0}", msg)); } this.ServerState = GFXDState.STOPPED; if (removeDir) RemoveServerDir(); Log(String.Format("Server {0} stopped, serverState: {1}", ServerName, ServerState)); serverCount--; } private string GetStartCmd() { CreateServerDir(); String cmd = string.Empty; if(locator != null) cmd = String.Format( @"server start -dir={0} -J-Dgemfirexd.drda.debug={1} -log-level={2} " + "-locators={3}[{4}] -client-bind-address={5} -client-port={6} -run-netserver=true ", serverDir, drdaDebug, logLevel, locator.PeerDiscoveryAddress,locator.PeerDiscoveryPort, clientBindAddress, clientPort); else cmd = String.Format( @"server start -dir={0} -J-Dgemfirexd.drda.debug={1} " + "-log-level={2} -client-bind-address={3} -client-port={4} -mcast-port={5}", serverDir, drdaDebug, logLevel, clientBindAddress, clientPort, mcastPort); return cmd; } private string GetStopCmd() { return String.Format(@"server stop -dir={0}", serverDir); } private void CreateServerDir() { try { if (!Directory.Exists(serverDir)) Directory.CreateDirectory(serverDir); } catch (Exception e) { Log(e.Message); Log("Server Dir.: " + serverDir); } } private void RemoveServerDir() { try { if (Directory.Exists(serverDir)) Directory.Delete(serverDir, true); } catch (Exception e) { Log(e.Message); } } private void Log(String msg) { lock (locker) { logger.Write(msg); } } } }
/* * Magix - A Web Application Framework for Humans * Copyright 2010 - 2014 - [email protected] * Magix is licensed as MITx11, see enclosed License.txt File for Details. */ using System; using System.IO; using System.Linq; using System.Collections.Generic; using MimeKit; using MimeKit.Cryptography; using MailKit; using MailKit.Net.Pop3; using HtmlAgilityPack; using Magix.Core; namespace Magix.email { /* * email pop3 helper */ internal class Pop3Helper { /* * returns message count from pop3 server */ internal static int GetMessageCount(Core.Node ip, Core.Node dp) { string host = Expressions.GetExpressionValue<string>(ip.GetValue("host", ""), dp, ip, false); int port = Expressions.GetExpressionValue<int>(ip.GetValue("port", "-1"), dp, ip, false); bool implicitSsl = Expressions.GetExpressionValue<bool>(ip.GetValue("ssl", "false"), dp, ip, false); string username = Expressions.GetExpressionValue<string>(ip.GetValue("username", ""), dp, ip, false); string password = Expressions.GetExpressionValue<string>(ip.GetValue("password", ""), dp, ip, false); using (Pop3Client client = new Pop3Client()) { client.Connect(host, port, implicitSsl); client.AuthenticationMechanisms.Remove("XOAUTH2"); if (!string.IsNullOrEmpty(username)) client.Authenticate(username, password); int retVal = client.GetMessageCount(); client.Disconnect(true); return retVal; } } /* * returns messages from pop3 server */ internal static void GetMessages( Node pars, Node ip, Node dp, string basePath, string attachmentDirectory, string linkedAttachmentDirectory) { string host = Expressions.GetExpressionValue<string>(ip.GetValue("host", ""), dp, ip, false); int port = Expressions.GetExpressionValue<int>(ip.GetValue("port", "-1"), dp, ip, false); bool implicitSsl = Expressions.GetExpressionValue<bool>(ip.GetValue("ssl", "false"), dp, ip, false); string username = Expressions.GetExpressionValue<string>(ip.GetValue("username", ""), dp, ip, false); string password = Expressions.GetExpressionValue<string>(ip.GetValue("password", ""), dp, ip, false); Node exeNode = null; if (ip.Contains("code")) exeNode = ip["code"]; using (Pop3Client client = new Pop3Client()) { client.Connect(host, port, implicitSsl); client.AuthenticationMechanisms.Remove("XOAUTH2"); if (!string.IsNullOrEmpty(username)) client.Authenticate(username, password); try { RetrieveMessagesFromServer( pars, dp, ip, basePath, attachmentDirectory, linkedAttachmentDirectory, exeNode, client); } finally { if (client.IsConnected) client.Disconnect(true); } } } /* * retrieves messages from pop3 server */ private static void RetrieveMessagesFromServer( Node pars, Node dp, Node ip, string basePath, string attachmentDirectory, string linkedAttachmentDirectory, Node exeNode, Pop3Client client) { int serverCount = client.GetMessageCount(); int count = Expressions.GetExpressionValue<int>(ip.GetValue("count", serverCount.ToString()), dp, ip, false); count = Math.Min(serverCount, count); bool delete = Expressions.GetExpressionValue<bool>(ip.GetValue("delete", "false"), dp, ip, false); for (int idxMsg = 0; idxMsg < count; idxMsg++) { // short circuting in case message is already downloaded string uuid = null; if (client.SupportsUids) { uuid = client.GetMessageUid(idxMsg); if (MessageAlreadyDownloaded(uuid)) continue; } MimeMessage msg = client.GetMessage(idxMsg); HandleMessage( pars, ip, basePath, attachmentDirectory, linkedAttachmentDirectory, exeNode, idxMsg, msg, uuid); if (delete) client.DeleteMessage(idxMsg); } } /* * checks to see if message is already download, and if it is, returns true */ private static bool MessageAlreadyDownloaded(string uuid) { Node checkDataLayer = new Node(); checkDataLayer["or"]["uuid"].Value = uuid; checkDataLayer["or"]["type"].Value = "magix.email.message"; ActiveEvents.Instance.RaiseActiveEvent( typeof(Pop3Helper), "magix.data.count", checkDataLayer); return checkDataLayer["count"].Get<int>() > 0; } /* * handles one message from server */ private static void HandleMessage( Node pars, Node ip, string basePath, string attachmentDirectory, string linkedAttachmentDirectory, Node exeNode, int idxMsg, MimeMessage msg, string uuid) { if (exeNode == null) { // returning messages back to caller as a list of emails BuildMessage(msg, ip["values"]["msg_" + idxMsg], basePath, attachmentDirectory, linkedAttachmentDirectory, uuid); } else { HandleMessageInCallback( pars, basePath, attachmentDirectory, linkedAttachmentDirectory, exeNode, msg, uuid); } } /* * handles message by callback */ private static void HandleMessageInCallback( Node pars, string basePath, string attachmentDirectory, string linkedAttachmentDirectory, Node exeNode, MimeMessage msg, string uuid) { // we have a code callback Node callbackNode = exeNode.Clone(); BuildMessage(msg, exeNode["_message"], basePath, attachmentDirectory, linkedAttachmentDirectory, uuid); pars["_ip"].Value = exeNode; ActiveEvents.Instance.RaiseActiveEvent( typeof(Pop3Helper), "magix.execute", pars); exeNode.Clear(); exeNode.AddRange(callbackNode); } /* * puts a message into a node for returning back to client */ private static void BuildMessage( MimeMessage msg, Node node, string basePath, string attachmentDirectory, string linkedAttachmentDirectory, string uuid) { ExtractHeaders(msg, node, uuid); ExtractBody(new MimeEntity[] { msg.Body }, node, false, msg, basePath, attachmentDirectory, linkedAttachmentDirectory); } /* * extract headers from email and put into node */ private static void ExtractHeaders(MimeMessage msg, Node node, string uuid) { GetAddress(msg.Sender, "sender", node); GetAddress(msg.From[0], "from", node); if (msg.ReplyTo.Count > 0) GetAddress(msg.ReplyTo[0], "reply-to", node); foreach (InternetAddress idxAdr in msg.To) GetAddress(idxAdr, "", node["to"]); foreach (InternetAddress idxAdr in msg.Cc) GetAddress(idxAdr, "", node["cc"]); node["date"].Value = msg.Date.DateTime; if (!string.IsNullOrEmpty(msg.InReplyTo)) node["in-reply-to"].Value = msg.InReplyTo; if (!string.IsNullOrEmpty(uuid)) node["uuid"].Value = uuid; node["message-id"].Value = msg.MessageId; node["subject"].Value = msg.Subject ?? ""; node["download-date"].Value = DateTime.Now; } /* * extracts body parts from message and put into node */ private static void ExtractBody( IEnumerable<MimeEntity> entities, Node node, bool skipSignature, MimeMessage msg, string basePath, string attachmentDirectory, string linkedAttachmentDirectory) { foreach (MimeEntity idxBody in entities) { if (idxBody is TextPart) { TextPart tp = idxBody as TextPart; if (idxBody.ContentType.MediaType == "text") { if (idxBody.ContentType.MediaSubtype == "plain") { node["body"]["plain"].Value = tp.Text; } else if (idxBody.ContentType.MediaSubtype == "html") { node["body"]["html"].Value = CleanHtml(tp.Text); } } } else if (idxBody is ApplicationPkcs7Mime) { ApplicationPkcs7Mime pkcs7 = idxBody as ApplicationPkcs7Mime; if (pkcs7.SecureMimeType == SecureMimeType.EnvelopedData) { try { MimeEntity entity = pkcs7.Decrypt(); ExtractBody(new MimeEntity[] { entity }, node, false, msg, basePath, attachmentDirectory, linkedAttachmentDirectory); node["encrypted"].Value = true; } catch (Exception err) { // couldn't decrypt node["body"]["plain"].Value = "couldn't decrypt message, exceptions was; '" + err.Message + "'"; node["encrypted"].Value = true; } } } else if (!skipSignature && idxBody is MultipartSigned) { MultipartSigned signed = idxBody as MultipartSigned; bool valid = false; foreach (IDigitalSignature signature in signed.Verify()) { valid = signature.Verify(); if (!valid) break; } node["signed"].Value = valid; ExtractBody(new MimeEntity[] { signed }, node, true, msg, basePath, attachmentDirectory, linkedAttachmentDirectory); } else if (idxBody is Multipart) { Multipart mp = idxBody as Multipart; ExtractBody(mp, node, false, msg, basePath, attachmentDirectory, linkedAttachmentDirectory); } else if (idxBody is MimePart) { // this is an attachment ExtractAttachments(idxBody as MimePart, msg, node, basePath, attachmentDirectory, linkedAttachmentDirectory); } } } /* * cleans up html from email */ private static string CleanHtml(string html) { HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(html); // removing all script and style tags, in addition to all comments doc.DocumentNode.Descendants() .Where(n => n.Name == "script" || n.Name == "style" || n.Name == "#comment") .ToList() .ForEach(n => n.Remove()); // making sure all links opens up in _blank targets HtmlNodeCollection links = doc.DocumentNode.SelectNodes("//a"); if (links != null) { foreach (HtmlNode link in links) { if (link.Attributes["target"] != null) link.Attributes["target"].Value = "_blank"; else link.Attributes.Add("target", "_blank"); } } // returning only contents of body element HtmlNode el = doc.DocumentNode.SelectSingleNode("//body"); if (el != null) return el.InnerHtml; else return doc.DocumentNode.InnerHtml; } /* * extracts attachments from message */ private static void ExtractAttachments( MimePart entity, MimeMessage msg, Node node, string basePath, string attachmentDirectory, string linkedAttachmentDirectory) { if (entity is ApplicationPkcs7Mime) return; // don't bother about p7m attachments string fileName; if (entity.Headers.Contains("Content-Location")) { // this is a linked resource, replacing references inside html with local filename fileName = linkedAttachmentDirectory + msg.MessageId + "_" + entity.FileName; if (node.Contains("body") && node["body"].ContainsValue("html")) node["body"]["html"].Value = node["body"]["html"].Get<string>().Replace(entity.Headers["Content-Location"], fileName); } else if (entity.Headers.Contains("Content-ID")) { fileName = linkedAttachmentDirectory + msg.MessageId + "_" + entity.FileName; string contentId = entity.Headers["Content-ID"].Trim('<').Trim('>'); if (node.Contains("body") && node["body"].ContainsValue("html")) node["body"]["html"].Value = node["body"]["html"].Get<string>().Replace("cid:" + contentId, fileName); } else { fileName = attachmentDirectory + msg.MessageId + "_" + entity.FileName; Node attNode = new Node("", entity.FileName ?? ""); attNode["local-file-name"].Value = fileName; node["attachments"].Add(attNode); } using (Stream stream = File.Create(basePath + fileName)) { entity.ContentObject.DecodeTo(stream); } } /* * puts in an email address into the given node */ private static void GetAddress(InternetAddress adr, string field, Node node) { if (adr == null || !(adr is MailboxAddress)) return; MailboxAddress mailboxAdr = adr as MailboxAddress; Node nNode = new Node(field, mailboxAdr.Address); if (!string.IsNullOrEmpty(mailboxAdr.Name)) nNode.Add("display-name", mailboxAdr.Name); node.Add(nNode); } } }
/* * [File purpose] * Author: Phillip Piper * Date: 10/21/2008 11:01 PM * * CHANGE LOG: * when who what * 10/21/2008 JPP Initial Version */ using System; using System.Text; using System.Windows.Forms; using System.Collections.Generic; using System.Reflection; using System.ComponentModel; using System.Text.RegularExpressions; namespace BrightIdeasSoftware.Tests { /// <summary> /// Class with program entry point. /// </summary> internal sealed class Program { /// <summary> /// Program entry point. /// </summary> //[STAThread] //private static void Main(string[] args) { // Application.EnableVisualStyles(); // Application.SetCompatibleTextRenderingDefault(false); // Application.Run(new MainForm()); // MyGlobals g = new MyGlobals(); // g.RunBeforeAnyTests(); // TestMunger t = new TestMunger(); // t.Init(); // t.Test_PutValue_NonVirtualProperty_CalledOnBaseClass(); // g.RunAfterAnyTests(); //} //[STAThread] //private static void Main(string[] args) { // int start = Environment.TickCount; // int iterations = 10000; // Person person1 = new Person("name", "occupation", 100, DateTime.Now, 1.0, true, " photo ", "comments"); // Person2 person2 = new Person2("name", "occupation", 100, DateTime.Now, 1.0, true, " photo ", "comments"); // OLVColumn column1 = new OLVColumn("ignored", "CulinaryRating"); // OLVColumn column2 = new OLVColumn("ignored", "BirthDate.Year.ToString.Length"); // OLVColumn column3 = new OLVColumn("ignored", "Photo.ToString.Trim"); // for (int i = 0; i < iterations; i++) { // column1.GetValue(person1); // column1.GetValue(person2); // column2.GetValue(person1); // column2.GetValue(person2); // column3.GetValue(person1); // column3.GetValue(person2); // } // Console.WriteLine("Elapsed time: {0}ms", Environment.TickCount - start); //} // Base line: Elapsed time: 2040ms // Base line: Elapsed time: 1547ms 2010-08-04 // Base line: Elapsed time: 442ms 2010-08-10 New SimpleMunger implementation [STAThread] private static void Main(string[] args) { GenerateDocs(); } static void GenerateDocs() { StringBuilder sb = new StringBuilder(); sb.AppendLine(""); sb.AppendLine("Controls"); sb.AppendLine("--------"); GenerateDocs(typeof(ObjectListView), sb); GenerateDocs(typeof(DataListView), sb); GenerateDocs(typeof(VirtualObjectListView), sb); GenerateDocs(typeof(FastObjectListView), sb); GenerateDocs(typeof(TreeListView), sb); sb.AppendLine(""); sb.AppendLine("Renderers"); sb.AppendLine("---------"); GenerateDocs(typeof(IRenderer), sb); GenerateDocs(typeof(AbstractRenderer), sb); GenerateDocs(typeof(BaseRenderer), sb); GenerateDocs(typeof(ImageRenderer), sb); GenerateDocs(typeof(MultiImageRenderer), sb); GenerateDocs(typeof(BarRenderer), sb); sb.AppendLine(""); sb.AppendLine("Decorations"); sb.AppendLine("-----------"); GenerateDocs(typeof(IDecoration), sb); GenerateDocs(typeof(AbstractDecoration), sb); GenerateDocs(typeof(ImageDecoration), sb); GenerateDocs(typeof(TextDecoration), sb); GenerateDocs(typeof(RowBorderDecoration), sb); GenerateDocs(typeof(CellBorderDecoration), sb); GenerateDocs(typeof(LightBoxDecoration), sb); GenerateDocs(typeof(TintedColumnDecoration), sb); sb.AppendLine(""); sb.AppendLine("Drag and Drop"); sb.AppendLine("-------------"); GenerateDocs(typeof(IDropSink), sb); GenerateDocs(typeof(AbstractDropSink), sb); GenerateDocs(typeof(SimpleDropSink), sb); GenerateDocs(typeof(RearrangingDropSink), sb); GenerateDocs(typeof(IDragSource), sb); GenerateDocs(typeof(AbstractDragSource), sb); GenerateDocs(typeof(SimpleDragSource), sb); GenerateDocs(typeof(OLVDataObject), sb); Clipboard.Clear(); Clipboard.SetText(sb.ToString()); } static bool IsStatic(PropertyInfo prop) { if (prop.GetGetMethod() == null) return false; return prop.GetGetMethod().IsStatic; } static void GenerateDocs(Type type, StringBuilder sb) { sb.AppendLine(""); sb.AppendLine(type.Name); sb.AppendLine(new String('~', type.Name.Length)); GeneratePropertiesDocs(type, sb); GenerateEventsDocs(type, sb); GenerateMethodsDocs(type, sb); } static void GeneratePropertiesDocs(Type type, StringBuilder sb) { List<PropertyInfo> properties = new List<PropertyInfo>(type.GetProperties( BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly )); if (properties.Count == 0) return; properties.Sort(delegate(PropertyInfo x, PropertyInfo y) { if (IsStatic(x) == IsStatic(y)) { return x.Name.CompareTo(y.Name); } else { return IsStatic(x) ? -1 : 1; } }); sb.AppendLine(""); sb.AppendLine("Properties"); sb.AppendLine("^^^^^^^^^^"); List<string[]> values = new List<string[]>(); values.Add(new string[] { "*Name*", "*Info*", "*Description*" }); foreach (PropertyInfo pinfo in properties) { values.Add(new string[] { }); // marks a new entry DescriptionAttribute descAttr = Attribute.GetCustomAttribute(pinfo, typeof(DescriptionAttribute)) as DescriptionAttribute; //OLVDocAttribute docAttr = Attribute.GetCustomAttribute(pinfo, typeof(OLVDocAttribute)) as OLVDocAttribute; values.Add(new string[] { GetName(pinfo), String.Format("* Type: {0}", GetTypeName(pinfo.PropertyType)), (descAttr == null ? "" : descAttr.Description) }); DefaultValueAttribute defaultValueAttr = Attribute.GetCustomAttribute(pinfo, typeof(DefaultValueAttribute)) as DefaultValueAttribute; if (defaultValueAttr != null) values.Add(new string[] { String.Empty, String.Format("* Default: {0}", Convert.ToString(defaultValueAttr.Value)), String.Empty }); CategoryAttribute categoryAttr = Attribute.GetCustomAttribute(pinfo, typeof(CategoryAttribute)) as CategoryAttribute; values.Add(new string[] { String.Empty, String.Format("* IDE?: {0}", (categoryAttr == null || categoryAttr.Category != "ObjectListView" ? "No" : "Yes")), String.Empty }); values.Add(new string[] { String.Empty, String.Format("* Access: {0}", GetAccessLevel(pinfo)), String.Empty }); values.Add(new string[] { String.Empty, String.Format("* Writeable: {0}", (pinfo.CanWrite ? "Read-Write" : "Read")), String.Empty }); } GenerateTable(sb, values); } static void GenerateEventsDocs(Type type, StringBuilder sb) { List<EventInfo> events = new List<EventInfo>(type.GetEvents( BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly )); if (events.Count == 0) return; events.Sort(delegate(EventInfo x, EventInfo y) { return x.Name.CompareTo(y.Name); }); sb.AppendLine(""); sb.AppendLine("Events"); sb.AppendLine("^^^^^^"); List<string[]> values = new List<string[]>(); values.Add(new string[] { "*Name*", "*Parameters*", "*Description*" }); foreach (EventInfo einfo in events) { values.Add(new string[] { }); // marks a new entry DescriptionAttribute descAttr = Attribute.GetCustomAttribute(einfo, typeof(DescriptionAttribute)) as DescriptionAttribute; values.Add(new string[] { einfo.Name, GetTypeName(einfo.EventHandlerType), (descAttr == null ? "" : descAttr.Description) }); } GenerateTable(sb, values); } static void GenerateMethodsDocs(Type type, StringBuilder sb) { List<MethodInfo> methods = new List<MethodInfo>(type.GetMethods( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly )); // Special name methods are the get_ and set_ of properties and the // add_ and remove_ of event handlers methods = methods.FindAll(delegate(MethodInfo x) { return !x.IsSpecialName && !x.IsPrivate; }); if (methods.Count == 0) return; methods.Sort(delegate(MethodInfo x, MethodInfo y) { return x.Name.CompareTo(y.Name); }); sb.AppendLine(""); sb.AppendLine("Methods"); sb.AppendLine("^^^^^^^"); List<string[]> values = new List<string[]>(); values.Add(new string[] { "*Name*", "*Description*" }); foreach (MethodInfo info in methods) { values.Add(new string[] { }); // marks a new entry DescriptionAttribute descAttr = Attribute.GetCustomAttribute(info, typeof(DescriptionAttribute)) as DescriptionAttribute; values.Add(new string[] { String.Format("``{0} {1} {2}({3})``", GetAccessLevel(info), GetTypeName(info.ReturnType), info.Name, MakeParameterList(info)), (descAttr == null ? "" : descAttr.Description) }); } GenerateTable(sb, values); } private static string GetName(PropertyInfo pinfo) { string name = pinfo.Name; // Some name are so long they make the formatting strange. List<string[]> pairs = new List<string[]>(new string[][] { new string[] { "GroupWithItemCountSingularFormatOrDefault", "GroupWithItemCountSingularFormat OrDefault" }, new string[] { "RenderNonEditableCheckboxesAsDisabled", "RenderNonEditableCheckboxes AsDisabled" }, new string[] { "UpdateSpaceFillingColumnsWhenDraggingColumnDivider", "UpdateSpaceFillingColumnsWhenDragging ColumnDivider" }, new string[] { "UnfocusedHighlightForegroundColorOrDefault", "UnfocusedHighlightForegroundColorOr Default" }, new string[] { "UnfocusedHighlightBackgroundColorOrDefault", "UnfocusedHighlightBackgroundColorOr Default" } }); foreach (string[] pair in pairs) { if (name == pair[0]) { name = pair[1]; break; } } if (IsStatic(pinfo)) name += " (static)"; return name; } private static string GetTypeName(Type type) { //System.EventHandler`1[[BrightIdeasSoftware.CreateGroupsEventArgs, ObjectListView, Version=2.4.1.15087, Culture=neutral, PublicKeyToken=b1c5bf581481bcd4]]" Match eventHandlerMatch = Regex.Match(type.FullName, @"EventHandler.*\[.*?\.(.*?),"); if (eventHandlerMatch.Success) { return eventHandlerMatch.Groups[1].Value; } Match genericTypeMatch = Regex.Match(type.FullName, @"\.([^.]+?)`1\[\[.+?\.(.+?),"); if (genericTypeMatch.Success) { return String.Format("{0}<{1}>", genericTypeMatch.Groups[1].Value, genericTypeMatch.Groups[2].Value); } string[] fullName = type.FullName.Split('.'); string last = fullName[fullName.Length - 1]; return last; } private static string GetDefaultValue(DefaultValueAttribute attr) { if (attr == null || attr.Value == null) return String.Empty; return attr.Value.ToString(); } private static string GetAccessLevel(PropertyInfo pinfo) { return GetAccessLevel(pinfo.GetGetMethod(true) ?? pinfo.GetSetMethod(true)); } private static string GetAccessLevel(MethodInfo minfo) { if (minfo == null) return String.Empty; StringBuilder sb = new StringBuilder(); MethodAttributes attrs = minfo.Attributes; if ((attrs & MethodAttributes.NewSlot) == MethodAttributes.NewSlot) { if (minfo != minfo.GetBaseDefinition()) sb.Append("new "); } if ((attrs & MethodAttributes.Public) == MethodAttributes.Public) sb.Append("public"); else if ((attrs & MethodAttributes.FamANDAssem) == MethodAttributes.FamANDAssem) sb.Append("internal"); else if ((attrs & MethodAttributes.Family) == MethodAttributes.Family) sb.Append("protected"); else if ((attrs & MethodAttributes.Private) == MethodAttributes.Private) sb.Append("private"); if ((attrs & MethodAttributes.Virtual) == MethodAttributes.Virtual) sb.Append(" virtual"); return sb.ToString(); } private static void GenerateTable(StringBuilder sb, List<string[]> values) { int[] valueMaxLength = new int[values[0].Length]; foreach (string[] value in values) { for (int i = 0; i < value.Length; i++) { valueMaxLength[i] = Math.Max(valueMaxLength[i], value[i].Length); } } for (int i = 0; i < valueMaxLength.Length; i++) valueMaxLength[i] = Math.Max(20, valueMaxLength[i]+2); string titleDivider = ""; string rowDivider = ""; for (int i = 0; i < valueMaxLength.Length; i++) { titleDivider += new string('=', valueMaxLength[i]) + " "; rowDivider += new string('-', valueMaxLength[i]) + " "; } sb.AppendLine(""); sb.AppendLine(titleDivider); // Print rows int rowCount = 0; foreach (string[] value in values) { if (value.Length == 0) { if (rowCount <= 1) sb.AppendLine(titleDivider); else sb.AppendLine(rowDivider); } else { for (int i = 0; i < value.Length; i++) { string formatString = String.Format("{0}0,-{1}{2} ", "{", valueMaxLength[i], "}"); sb.AppendFormat(formatString, value[i]); } sb.AppendLine(); } rowCount++; } sb.AppendLine(titleDivider); } private static string MakeParameterList(MethodInfo info) { StringBuilder sb = new StringBuilder(); foreach (ParameterInfo parameter in info.GetParameters()) { sb.Append(GetTypeName(parameter.ParameterType)); sb.Append(" "); sb.Append(parameter.Name); sb.Append(", "); } // remove trailing comma and space if (sb.Length > 2) sb.Length -= 2; return sb.ToString(); } } }
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt using System; using System.Collections; using System.Globalization; using NUnit.Framework.Constraints; namespace NUnit.Framework.Internal { /// <summary> /// TextMessageWriter writes constraint descriptions and messages /// in displayable form as a text stream. It tailors the display /// of individual message components to form the standard message /// format of NUnit assertion failure messages. /// </summary> public class TextMessageWriter : MessageWriter { #region Message Formats and Constants private static readonly int DEFAULT_LINE_LENGTH = 78; // Prefixes used in all failure messages. All must be the same // length, which is held in the PrefixLength field. Should not // contain any tabs or newline characters. /// <summary> /// Prefix used for the expected value line of a message /// </summary> public static readonly string Pfx_Expected = " Expected: "; /// <summary> /// Prefix used for the actual value line of a message /// </summary> public static readonly string Pfx_Actual = " But was: "; /// <summary> /// Prefix used for the actual difference between actual and expected values if compared with a tolerance /// </summary> public static readonly string Pfx_Difference = " Off by: "; /// <summary> /// Length of a message prefix /// </summary> public static readonly int PrefixLength = Pfx_Expected.Length; #endregion #region Instance Fields private int maxLineLength = DEFAULT_LINE_LENGTH; private bool _sameValDiffTypes = false; private string _expectedType, _actualType; #endregion #region Constructors /// <summary> /// Construct a TextMessageWriter /// </summary> public TextMessageWriter() { } /// <summary> /// Construct a TextMessageWriter, specifying a user message /// and optional formatting arguments. /// </summary> /// <param name="userMessage"></param> /// <param name="args"></param> public TextMessageWriter(string userMessage, params object[] args) { if ( userMessage != null && userMessage != string.Empty) this.WriteMessageLine(userMessage, args); } #endregion #region Properties /// <summary> /// Gets or sets the maximum line length for this writer /// </summary> public override int MaxLineLength { get { return maxLineLength; } set { maxLineLength = value; } } #endregion #region Public Methods - High Level /// <summary> /// Method to write single line message with optional args, usually /// written to precede the general failure message, at a given /// indentation level. /// </summary> /// <param name="level">The indentation level of the message</param> /// <param name="message">The message to be written</param> /// <param name="args">Any arguments used in formatting the message</param> public override void WriteMessageLine(int level, string message, params object[] args) { if (message != null) { while (level-- >= 0) Write(" "); if (args != null && args.Length > 0) message = string.Format(message, args); WriteLine(MsgUtils.EscapeNullCharacters(message)); } } /// <summary> /// Display Expected and Actual lines for a constraint. This /// is called by MessageWriter's default implementation of /// WriteMessageTo and provides the generic two-line display. /// </summary> /// <param name="result">The result of the constraint that failed</param> public override void DisplayDifferences(ConstraintResult result) { WriteExpectedLine(result); WriteActualLine(result); WriteAdditionalLine(result); } /// <summary> /// Gets the unique type name between expected and actual. /// </summary> /// <param name="expected">The expected value</param> /// <param name="actual">The actual value causing the failure</param> /// <param name="expectedType">Output of the unique type name for expected</param> /// <param name="actualType">Output of the unique type name for actual</param> private void ResolveTypeNameDifference(object expected, object actual, out string expectedType, out string actualType) { TypeNameDifferenceResolver resolver = new TypeNameDifferenceResolver(); resolver.ResolveTypeNameDifference(expected, actual, out expectedType, out actualType); expectedType = $" ({expectedType})"; actualType = $" ({actualType})"; } /// <summary> /// Display Expected and Actual lines for given values. This /// method may be called by constraints that need more control over /// the display of actual and expected values than is provided /// by the default implementation. /// </summary> /// <param name="expected">The expected value</param> /// <param name="actual">The actual value causing the failure</param> public override void DisplayDifferences(object expected, object actual) { DisplayDifferences(expected, actual,null); } /// <summary> /// Display Expected and Actual lines for given values, including /// a tolerance value on the expected line. /// </summary> /// <param name="expected">The expected value</param> /// <param name="actual">The actual value causing the failure</param> /// <param name="tolerance">The tolerance within which the test was made</param> public override void DisplayDifferences(object expected, object actual, Tolerance tolerance) { if (expected != null && actual != null && expected.GetType() != actual.GetType() && MsgUtils.FormatValue(expected) == MsgUtils.FormatValue(actual)) { _sameValDiffTypes = true; ResolveTypeNameDifference(expected, actual, out _expectedType, out _actualType); } WriteExpectedLine(expected, tolerance); WriteActualLine(actual); if (tolerance != null) { WriteDifferenceLine(expected, actual, tolerance); } } /// <summary> /// Display the expected and actual string values on separate lines. /// If the mismatch parameter is >=0, an additional line is displayed /// line containing a caret that points to the mismatch point. /// </summary> /// <param name="expected">The expected string value</param> /// <param name="actual">The actual string value</param> /// <param name="mismatch">The point at which the strings don't match or -1</param> /// <param name="ignoreCase">If true, case is ignored in string comparisons</param> /// <param name="clipping">If true, clip the strings to fit the max line length</param> public override void DisplayStringDifferences(string expected, string actual, int mismatch, bool ignoreCase, bool clipping) { // Maximum string we can display without truncating int maxDisplayLength = MaxLineLength - PrefixLength // Allow for prefix - 2; // 2 quotation marks if ( clipping ) MsgUtils.ClipExpectedAndActual(ref expected, ref actual, maxDisplayLength, mismatch); expected = MsgUtils.EscapeControlChars(expected); actual = MsgUtils.EscapeControlChars(actual); // The mismatch position may have changed due to clipping or white space conversion mismatch = MsgUtils.FindMismatchPosition(expected, actual, 0, ignoreCase); Write( Pfx_Expected ); Write( MsgUtils.FormatValue(expected) ); if ( ignoreCase ) Write( ", ignoring case" ); WriteLine(); WriteActualLine( actual ); //DisplayDifferences(expected, actual); if (mismatch >= 0) WriteCaretLine(mismatch); } #endregion #region Public Methods - Low Level /// <summary> /// Writes the text for an actual value. /// </summary> /// <param name="actual">The actual value.</param> public override void WriteActualValue(object actual) { WriteValue(actual); } /// <summary> /// Writes the text for a generalized value. /// </summary> /// <param name="val">The value.</param> public override void WriteValue(object val) { Write(MsgUtils.FormatValue(val)); } /// <summary> /// Writes the text for a collection value, /// starting at a particular point, to a max length /// </summary> /// <param name="collection">The collection containing elements to write.</param> /// <param name="start">The starting point of the elements to write</param> /// <param name="max">The maximum number of elements to write</param> public override void WriteCollectionElements(IEnumerable collection, long start, int max) { Write(MsgUtils.FormatCollection(collection, start, max)); } #endregion #region Helper Methods /// <summary> /// Write the generic 'Expected' line for a constraint /// </summary> /// <param name="result">The constraint that failed</param> private void WriteExpectedLine(ConstraintResult result) { Write(Pfx_Expected); WriteLine(result.Description); } /// <summary> /// Write the generic 'Expected' line for a given value /// and tolerance. /// </summary> /// <param name="expected">The expected value</param> /// <param name="tolerance">The tolerance within which the test was made</param> private void WriteExpectedLine(object expected, Tolerance tolerance) { Write(Pfx_Expected); Write(MsgUtils.FormatValue(expected)); if (_sameValDiffTypes) { Write(_expectedType); } if (tolerance != null && !tolerance.IsUnsetOrDefault) { Write(" +/- "); Write(MsgUtils.FormatValue(tolerance.Amount)); if (tolerance.Mode != ToleranceMode.Linear) Write(" {0}", tolerance.Mode); } WriteLine(); } /// <summary> /// Write the generic 'Actual' line for a constraint /// </summary> /// <param name="result">The ConstraintResult for which the actual value is to be written</param> private void WriteActualLine(ConstraintResult result) { Write(Pfx_Actual); result.WriteActualValueTo(this); WriteLine(); //WriteLine(MsgUtils.FormatValue(result.ActualValue)); } private void WriteAdditionalLine(ConstraintResult result) { result.WriteAdditionalLinesTo(this); } /// <summary> /// Write the generic 'Actual' line for a given value /// </summary> /// <param name="actual">The actual value causing a failure</param> private void WriteActualLine(object actual) { Write(Pfx_Actual); WriteActualValue(actual); if (_sameValDiffTypes) { Write(_actualType); } WriteLine(); } private void WriteDifferenceLine(object expected, object actual, Tolerance tolerance) { // It only makes sense to display absolute/percent difference if (tolerance.Mode != ToleranceMode.Linear && tolerance.Mode != ToleranceMode.Percent) return; string differenceString = tolerance.Amount is TimeSpan ? MsgUtils.FormatValue(DateTimes.Difference(expected, actual)) // TimeSpan tolerance applied in linear mode only : MsgUtils.FormatValue(Numerics.Difference(expected, actual, tolerance.Mode)); if (differenceString != double.NaN.ToString()) { Write(Pfx_Difference); Write(differenceString); if (tolerance.Mode != ToleranceMode.Linear) Write(" {0}", tolerance.Mode); WriteLine(); } } private void WriteCaretLine(int mismatch) { // We subtract 2 for the initial 2 blanks and add back 1 for the initial quote WriteLine(" {0}^", new string('-', PrefixLength + mismatch - 2 + 1)); } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace Microsoft.Test.ModuleCore { //////////////////////////////////////////////////////////////// // SecurityFlags // //////////////////////////////////////////////////////////////// public enum SecurityFlags { None = 0, FullTrust = 1, ThreatModel = 2, } //////////////////////////////////////////////////////////////// // TestAttribute (attribute) // //////////////////////////////////////////////////////////////// public abstract class TestAttribute : Attribute { //Data protected string pname; protected string pdesc; protected object[] pparams; protected int pid; protected string pguid; protected bool pinheritance = true; protected TestAttribute pparent = null; protected string pfilter; protected string pversion; //Allows Inhertiance (ie: object to determine if ever been set) protected int? ppriority; //Allows Inhertiance protected string ppurpose; //Allows Inhertiance protected bool? pimplemented; //Allows Inhertiance protected string[] powners; //Allows Inhertiance protected string[] pareas; //Allows Inhertiance protected bool? pskipped; //Allows Inhertiance protected bool? perror; //Allows Inhertiance protected bool? pmanual; //Allows Inhertiance protected SecurityFlags? psecurity; //Allows Inhertiance protected string pfiltercriteria;//Allows Inhertiance protected string[] planguages; //Allows Inhertiance protected string pxml; //Allows Inhertiance protected int? ptimeout; //Allows Inhertiance protected int? pthreads; //Allows Inhertiance protected int? prepeat; //Allows Inhertiance protected bool? pstress; //Allows Inhertiance //Constructors public TestAttribute() { } public TestAttribute(string desc) { Desc = desc; } public TestAttribute(string desc, params Object[] parameters) { Desc = desc; Params = parameters; } //Accessors public virtual string Name { get { return pname; } set { pname = value; } } public virtual string Desc { get { return pdesc; } set { pdesc = value; } } public virtual int Id { get { return pid; } set { pid = value; } } public virtual string Guid { get { return pguid; } set { pguid = value; } } public virtual int Priority { get { if (ppriority == null) { //Inheritance if (Inheritance && pparent != null) return pparent.Priority; //Default return 2; } return (int)ppriority; } set { ppriority = value; } } public virtual string Owner { get { if (powners != null) return powners[0]; return null; } set { if (powners == null) powners = new string[1]; powners[0] = value; } } public virtual string[] Owners { get { return powners; } set { powners = value; } } public virtual string Area { get { if (pareas != null) return pareas[0]; return null; } set { if (pareas == null) pareas = new string[1]; pareas[0] = value; } } public virtual string[] Areas { get { return pareas; } set { pareas = value; } } public virtual string Version { get { return pversion; } set { pversion = value; } } public virtual object Param { get { if (pparams != null) return pparams[0]; return null; } set { if (pparams == null) pparams = new object[1]; pparams[0] = value; } } public virtual object[] Params { get { return pparams; } set { pparams = value; } } public virtual bool Inheritance { get { return pinheritance; } set { pinheritance = value; } } public virtual TestAttribute Parent { get { return pparent; } set { pparent = value; } } public virtual string Filter { get { return pfilter; } set { pfilter = value; } } public virtual string Purpose { get { if (ppurpose == null) { //Inheritance if (Inheritance && pparent != null) return pparent.Purpose; //Default return null; } return (string)ppurpose; } set { ppurpose = value; } } public virtual bool Implemented { get { if (pimplemented == null) { //Inheritance if (Inheritance && pparent != null) return pparent.Implemented; //Default return true; } return (bool)pimplemented; } set { pimplemented = value; } } public virtual bool Skipped { get { if (pskipped == null) { //Inheritance if (Inheritance && pparent != null) return pparent.Skipped; //Default return false; } return (bool)pskipped; } set { pskipped = value; } } public virtual bool Error { get { if (perror == null) { //Inheritance if (Inheritance && pparent != null) return pparent.Error; //Default return false; } return (bool)perror; } set { perror = value; } } public virtual bool Manual { get { if (pmanual == null) { //Inheritance if (Inheritance && pparent != null) return pparent.Manual; //Default return false; } return (bool)pmanual; } set { pmanual = value; } } public virtual SecurityFlags Security { get { if (psecurity == null) { //Inheritance if (Inheritance && pparent != null) return pparent.Security; //Default return SecurityFlags.None; } return (SecurityFlags)psecurity; } set { psecurity = value; } } public virtual string FilterCriteria { get { if (pfiltercriteria == null) { //Inheritance if (Inheritance && pparent != null) return pparent.FilterCriteria; //Default return null; } return (string)pfiltercriteria; } set { pfiltercriteria = value; } } public virtual string Language { get { if (Languages != null) return Languages[0]; return null; } set { if (Languages == null) Languages = new string[1]; Languages[0] = value; } } public virtual string[] Languages { get { if (planguages == null) { //Inheritance if (Inheritance && pparent != null) return pparent.Languages; //Default return null; } return (string[])planguages; } set { planguages = value; } } public virtual string Xml { get { if (pxml == null) { //Inheritance if (Inheritance && pparent != null) return pparent.Xml; //Default return null; } return (string)pxml; } set { pxml = value; } } public virtual bool Stress { get { if (pstress == null) { //Inheritance if (Inheritance && pparent != null) return pparent.Stress; //Default return false; } return (bool)pstress; } set { pstress = value; } } public virtual int Timeout { get { if (ptimeout == null) { //Inheritance if (Inheritance && pparent != null) return pparent.Timeout; //Default (infinite) return 0; } return (int)ptimeout; } set { ptimeout = value; } } public virtual int Threads { get { if (pthreads == null) { //Inheritance if (Inheritance && pparent != null) return pparent.Threads; //Default (one thread) return 1; } return (int)pthreads; } set { pthreads = value; } } public virtual int Repeat { get { if (prepeat == null) { //Inheritance if (Inheritance && pparent != null) return pparent.Repeat; //Default (no repeat) return 0; } return (int)prepeat; } set { prepeat = value; } } } //////////////////////////////////////////////////////////////// // TestModule (attribute) // //////////////////////////////////////////////////////////////// public class TestModuleAttribute : TestAttribute { //Data protected string pcreated; protected string pmodified; //Constructors public TestModuleAttribute() : base() { } public TestModuleAttribute(string desc) : base(desc) { } public TestModuleAttribute(string desc, params Object[] parameters) : base(desc, parameters) { } [TestProperty(Visible = true)] public virtual string Created { get { return pcreated; } set { pcreated = value; } } [TestProperty(Visible = true)] public virtual string Modified { get { return pmodified; } set { pmodified = value; } } } //////////////////////////////////////////////////////////////// // TestCase (attribute) // //////////////////////////////////////////////////////////////// public class TestCaseAttribute : TestAttribute { //Constructors public TestCaseAttribute() : base() { } public TestCaseAttribute(string desc) : base(desc) { } public TestCaseAttribute(string desc, params Object[] parameters) : base(desc, parameters) { } } //////////////////////////////////////////////////////////////// // Variation (attribute) // //////////////////////////////////////////////////////////////// public class VariationAttribute : TestAttribute { //Data //Constructors public VariationAttribute() : base() { } public VariationAttribute(string desc) : base(desc) { } public VariationAttribute(string desc, params Object[] parameters) : base(desc, parameters) { } } //////////////////////////////////////////////////////////////// // TestPropertyAttribute (attribute) // //////////////////////////////////////////////////////////////// public class TestPropertyAttribute : Attribute { //Data protected string pname; protected string pdesc; protected Guid pguid; protected int pid; protected object pdefaultvalue; protected TestPropertyFlags pflags = TestPropertyFlags.Read; //Constructors public TestPropertyAttribute() { } public virtual string Name { get { return pname; } set { pname = value; } } public virtual string Desc { get { return pdesc; } set { pdesc = value; } } public virtual Guid Guid { get { return pguid; } set { pguid = value; } } public virtual int Id { get { return pid; } set { pid = value; } } public virtual object DefaultValue { get { return pdefaultvalue; } set { pdefaultvalue = value; } } public virtual bool Settable { get { return this.IsFlag(TestPropertyFlags.Write); } set { this.SetFlag(TestPropertyFlags.Write, value); } } public virtual bool Required { get { return this.IsFlag(TestPropertyFlags.Required); } set { this.SetFlag(TestPropertyFlags.Required, value); } } public virtual bool Inherit { get { return this.IsFlag(TestPropertyFlags.Inheritance); } set { this.SetFlag(TestPropertyFlags.Inheritance, value); } } public virtual bool Visible { get { return this.IsFlag(TestPropertyFlags.Visible); } set { this.SetFlag(TestPropertyFlags.Visible, value); } } public virtual bool MultipleValues { get { return this.IsFlag(TestPropertyFlags.MultipleValues); } set { this.SetFlag(TestPropertyFlags.MultipleValues, value); } } public virtual TestPropertyFlags Flags { get { return pflags; } set { pflags = value; } } //Helpers protected bool IsFlag(TestPropertyFlags flags) { return (pflags & flags) == flags; } protected void SetFlag(TestPropertyFlags flags, bool value) { if (value) pflags |= flags; else pflags &= ~flags; } } //////////////////////////////////////////////////////////////// // TestInclude (attribute) // //////////////////////////////////////////////////////////////// public class TestIncludeAttribute : Attribute { //Data protected string pname; protected string pfile; protected string pfiles; protected string pfilter; //Constructors public TestIncludeAttribute() { } public virtual string Name { //Prefix for testcase names get { return pname; } set { pname = value; } } public virtual string File { get { return pfile; } set { pfile = value; } } public virtual string Files { //Search Pattern (ie: *.*) get { return pfiles; } set { pfiles = value; } } public virtual string Filter { get { return pfilter; } set { pfilter = value; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using Azure; using Management; using Rest; using Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for ApplicationGatewaysOperations. /// </summary> public static partial class ApplicationGatewaysOperationsExtensions { /// <summary> /// Deletes the specified application gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> public static void Delete(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName) { operations.DeleteAsync(resourceGroupName, applicationGatewayName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified application gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, applicationGatewayName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified application gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> public static ApplicationGateway Get(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName) { return operations.GetAsync(resourceGroupName, applicationGatewayName).GetAwaiter().GetResult(); } /// <summary> /// Gets the specified application gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ApplicationGateway> GetAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, applicationGatewayName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates the specified application gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update application gateway operation. /// </param> public static ApplicationGateway CreateOrUpdate(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, ApplicationGateway parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, applicationGatewayName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates the specified application gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update application gateway operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ApplicationGateway> CreateOrUpdateAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, ApplicationGateway parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, applicationGatewayName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all application gateways in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> public static IPage<ApplicationGateway> List(this IApplicationGatewaysOperations operations, string resourceGroupName) { return operations.ListAsync(resourceGroupName).GetAwaiter().GetResult(); } /// <summary> /// Lists all application gateways in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ApplicationGateway>> ListAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the application gateways in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<ApplicationGateway> ListAll(this IApplicationGatewaysOperations operations) { return operations.ListAllAsync().GetAwaiter().GetResult(); } /// <summary> /// Gets all the application gateways in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ApplicationGateway>> ListAllAsync(this IApplicationGatewaysOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Starts the specified application gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> public static void Start(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName) { operations.StartAsync(resourceGroupName, applicationGatewayName).GetAwaiter().GetResult(); } /// <summary> /// Starts the specified application gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task StartAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.StartWithHttpMessagesAsync(resourceGroupName, applicationGatewayName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Stops the specified application gateway in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> public static void Stop(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName) { operations.StopAsync(resourceGroupName, applicationGatewayName).GetAwaiter().GetResult(); } /// <summary> /// Stops the specified application gateway in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task StopAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.StopWithHttpMessagesAsync(resourceGroupName, applicationGatewayName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the backend health of the specified application gateway in a resource /// group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='expand'> /// Expands BackendAddressPool and BackendHttpSettings referenced in backend /// health. /// </param> public static ApplicationGatewayBackendHealth BackendHealth(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, string expand = default(string)) { return operations.BackendHealthAsync(resourceGroupName, applicationGatewayName, expand).GetAwaiter().GetResult(); } /// <summary> /// Gets the backend health of the specified application gateway in a resource /// group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='expand'> /// Expands BackendAddressPool and BackendHttpSettings referenced in backend /// health. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ApplicationGatewayBackendHealth> BackendHealthAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BackendHealthWithHttpMessagesAsync(resourceGroupName, applicationGatewayName, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the specified application gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> public static void BeginDelete(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName) { operations.BeginDeleteAsync(resourceGroupName, applicationGatewayName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified application gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, applicationGatewayName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Creates or updates the specified application gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update application gateway operation. /// </param> public static ApplicationGateway BeginCreateOrUpdate(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, ApplicationGateway parameters) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, applicationGatewayName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates the specified application gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update application gateway operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ApplicationGateway> BeginCreateOrUpdateAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, ApplicationGateway parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, applicationGatewayName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Starts the specified application gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> public static void BeginStart(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName) { operations.BeginStartAsync(resourceGroupName, applicationGatewayName).GetAwaiter().GetResult(); } /// <summary> /// Starts the specified application gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginStartAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.BeginStartWithHttpMessagesAsync(resourceGroupName, applicationGatewayName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Stops the specified application gateway in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> public static void BeginStop(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName) { operations.BeginStopAsync(resourceGroupName, applicationGatewayName).GetAwaiter().GetResult(); } /// <summary> /// Stops the specified application gateway in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginStopAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.BeginStopWithHttpMessagesAsync(resourceGroupName, applicationGatewayName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the backend health of the specified application gateway in a resource /// group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='expand'> /// Expands BackendAddressPool and BackendHttpSettings referenced in backend /// health. /// </param> public static ApplicationGatewayBackendHealth BeginBackendHealth(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, string expand = default(string)) { return operations.BeginBackendHealthAsync(resourceGroupName, applicationGatewayName, expand).GetAwaiter().GetResult(); } /// <summary> /// Gets the backend health of the specified application gateway in a resource /// group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='expand'> /// Expands BackendAddressPool and BackendHttpSettings referenced in backend /// health. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ApplicationGatewayBackendHealth> BeginBackendHealthAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginBackendHealthWithHttpMessagesAsync(resourceGroupName, applicationGatewayName, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all application gateways in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<ApplicationGateway> ListNext(this IApplicationGatewaysOperations operations, string nextPageLink) { return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Lists all application gateways in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ApplicationGateway>> ListNextAsync(this IApplicationGatewaysOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the application gateways in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<ApplicationGateway> ListAllNext(this IApplicationGatewaysOperations operations, string nextPageLink) { return operations.ListAllNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all the application gateways in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ApplicationGateway>> ListAllNextAsync(this IApplicationGatewaysOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// // Vorbis.cs: // // Author: // Brian Nickel ([email protected]) // // Copyright (C) 2007 Brian Nickel // // 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; namespace TagLib.Ogg.Codecs { /// <summary> /// This class extends <see cref="Codec" /> and implements <see /// cref="IAudioCodec" /> to provide support for processing Ogg /// Vorbis bitstreams. /// </summary> public class Vorbis : Codec, IAudioCodec { #region Private Static Fields /// <summary> /// Contains the file identifier. /// </summary> private static ByteVector id = "vorbis"; #endregion #region Private Fields /// <summary> /// Contains the header packet. /// </summary> private HeaderPacket header; /// <summary> /// Contains the comment data. /// </summary> private ByteVector comment_data; #endregion #region Constructors /// <summary> /// Constructs and initializes a new instance of <see /// cref="Vorbis" />. /// </summary> private Vorbis () { } #endregion #region Public Methods /// <summary> /// Reads a Ogg packet that has been encountered in the /// stream. /// </summary> /// <param name="packet"> /// A <see cref="ByteVector" /> object containing a packet to /// be read by the current instance. /// </param> /// <param name="index"> /// A <see cref="int" /> value containing the index of the /// packet in the stream. /// </param> /// <returns> /// <see langword="true" /> if the codec has read all the /// necessary packets for the stream and does not need to be /// called again, typically once the Xiph comment has been /// found. Otherwise <see langword="false" />. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="packet" /> is <see langword="null" />. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="index" /> is less than zero. /// </exception> /// <exception cref="CorruptFileException"> /// The data does not conform to the specificiation for the /// codec represented by the current instance. /// </exception> public override bool ReadPacket (ByteVector packet, int index) { if (packet == null) throw new ArgumentNullException ("packet"); if (index < 0) throw new ArgumentOutOfRangeException ("index", "index must be at least zero."); int type = PacketType (packet); if (type != 1 && index == 0) System.Console.WriteLine( "Stream does not begin with vorbis header."); if (comment_data == null) { if (type == 1) header = new HeaderPacket (packet); else if (type == 3) comment_data = packet.Mid (7); else return true; } return comment_data != null; } /// <summary> /// Computes the duration of the stream using the first and /// last granular positions of the stream. /// </summary> /// <param name="firstGranularPosition"> /// A <see cref="long" /> value containing the first granular /// position of the stream. /// </param> /// <param name="lastGranularPosition"> /// A <see cref="long" /> value containing the last granular /// position of the stream. /// </param> /// <returns> /// A <see cref="TimeSpan" /> value containing the duration /// of the stream. /// </returns> public override TimeSpan GetDuration (long firstGranularPosition, long lastGranularPosition) { return header.sample_rate == 0 ? TimeSpan.Zero : TimeSpan.FromSeconds ((double) (lastGranularPosition - firstGranularPosition) / (double) header.sample_rate); } /// <summary> /// Replaces the comment packet in a collection of packets /// with the rendered version of a Xiph comment or inserts a /// comment packet if the stream lacks one. /// </summary> /// <param name="packets"> /// A <see cref="ByteVectorCollection" /> object containing /// a collection of packets. /// </param> /// <param name="comment"> /// A <see cref="XiphComment" /> object to store the rendered /// version of in <paramref name="packets" />. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="packets" /> or <paramref name="comment" /// /> is <see langword="null" />. /// </exception> //public override void SetCommentPacket (ByteVectorCollection packets, // XiphComment comment) //{ // if (packets == null) // throw new ArgumentNullException ("packets"); // if (comment == null) // throw new ArgumentNullException ("comment"); // ByteVector data = new ByteVector ((byte) 0x03); // data.Add (id); // data.Add (comment.Render (true)); // if (packets.Count > 1 && PacketType (packets [1]) == 0x03) // packets [1] = data; // else // packets.Insert (1, data); //} #endregion #region Public Properties /// <summary> /// Gets the bitrate of the audio represented by the current /// instance. /// </summary> /// <value> /// A <see cref="int" /> value containing a bitrate of the /// audio represented by the current instance. /// </value> public int AudioBitrate { get { return (int) ((float)header.bitrate_nominal / 1000f + 0.5); } } /// <summary> /// Gets the sample rate of the audio represented by the /// current instance. /// </summary> /// <value> /// A <see cref="int" /> value containing the sample rate of /// the audio represented by the current instance. /// </value> public int AudioSampleRate { get {return (int) header.sample_rate;} } /// <summary> /// Gets the number of channels in the audio represented by /// the current instance. /// </summary> /// <value> /// A <see cref="int" /> value containing the number of /// channels in the audio represented by the current /// instance. /// </value> public int AudioChannels { get {return (int) header.channels;} } /// <summary> /// Gets the types of media represented by the current /// instance. /// </summary> /// <value> /// Always <see cref="MediaTypes.Audio" />. /// </value> public override MediaTypes MediaTypes { get {return MediaTypes.Audio;} } /// <summary> /// Gets the raw Xiph comment data contained in the codec. /// </summary> /// <value> /// A <see cref="ByteVector" /> object containing a raw Xiph /// comment or <see langword="null"/> if none was found. /// </value> public override ByteVector CommentData { get {return comment_data;} } /// <summary> /// Gets a text description of the media represented by the /// current instance. /// </summary> /// <value> /// A <see cref="string" /> object containing a description /// of the media represented by the current instance. /// </value> public override string Description { get { return string.Format ( "Vorbis Version {0} Audio", header.vorbis_version); } } #endregion #region Public Static Methods /// <summary> /// Implements the <see cref="CodecProvider" /> delegate to /// provide support for recognizing a Vorbis stream from the /// header packet. /// </summary> /// <param name="packet"> /// A <see cref="ByteVector" /> object containing the stream /// header packet. /// </param> /// <returns> /// A <see cref="Codec"/> object containing a codec capable /// of parsing the stream of <see langref="null" /> if the /// stream is not a Vorbis stream. /// </returns> public static Codec FromPacket (ByteVector packet) { return (PacketType (packet) == 1) ? new Vorbis () : null; } #endregion #region Private Static Methods /// <summary> /// Gets the packet type for a specified Vorbis packet. /// </summary> /// <param name="packet"> /// A <see cref="ByteVector" /> object containing a Vorbis /// packet. /// </param> /// <returns> /// A <see cref="int" /> value containing the packet type or /// -1 if the packet is invalid. /// </returns> private static int PacketType (ByteVector packet) { if (packet.Count <= id.Count) return -1; for (int i = 0; i < id.Count; i ++) if (packet [i + 1] != id [i]) return -1; return packet [0]; } #endregion /// <summary> /// This structure represents a Vorbis header packet. /// </summary> private struct HeaderPacket { public uint sample_rate; public uint channels; public uint vorbis_version; public uint bitrate_maximum; public uint bitrate_nominal; public uint bitrate_minimum; public HeaderPacket (ByteVector data) { vorbis_version = data.Mid(7, 4).ToUInt (false); channels = data [11]; sample_rate = data.Mid(12, 4).ToUInt (false); bitrate_maximum = data.Mid(16, 4).ToUInt (false); bitrate_nominal = data.Mid(20, 4).ToUInt (false); bitrate_minimum = data.Mid(24, 4).ToUInt (false); } } } }
/***************************************************************************** * Skeleton Utility created by Mitch Thompson * Full irrevocable rights and permissions granted to Esoteric Software *****************************************************************************/ using System; using System.IO; using System.Collections.Generic; using UnityEngine; using Spine; /// <summary>Sets a GameObject's transform to match a bone on a Spine skeleton.</summary> [ExecuteInEditMode] [AddComponentMenu("Spine/SkeletonUtilityBone")] public class SkeletonUtilityBone : MonoBehaviour { public enum Mode { Follow, Override } [System.NonSerialized] public bool valid; [System.NonSerialized] public SkeletonUtility skeletonUtility; [System.NonSerialized] public Bone bone; public Mode mode; public bool zPosition = true; public bool position; public bool rotation; public bool scale; public bool flip; public bool flipX; [Range(0f,1f)] public float overrideAlpha = 1; /// <summary>If a bone isn't set, boneName is used to find the bone.</summary> public String boneName; public Transform parentReference; [HideInInspector] public bool transformLerpComplete; protected Transform cachedTransform; protected Transform skeletonTransform; public bool NonUniformScaleWarning { get { return nonUniformScaleWarning; } } private bool nonUniformScaleWarning; public void Reset () { bone = null; cachedTransform = transform; valid = skeletonUtility != null && skeletonUtility.skeletonRenderer != null && skeletonUtility.skeletonRenderer.valid; if (!valid) return; skeletonTransform = skeletonUtility.transform; skeletonUtility.OnReset -= HandleOnReset; skeletonUtility.OnReset += HandleOnReset; DoUpdate(); } void OnEnable () { skeletonUtility = SkeletonUtility.GetInParent<SkeletonUtility>(transform); if (skeletonUtility == null) return; skeletonUtility.RegisterBone(this); skeletonUtility.OnReset += HandleOnReset; } void HandleOnReset () { Reset(); } void OnDisable () { if (skeletonUtility != null) { skeletonUtility.OnReset -= HandleOnReset; skeletonUtility.UnregisterBone(this); } } public void DoUpdate () { if (!valid) { Reset(); return; } Spine.Skeleton skeleton = skeletonUtility.skeletonRenderer.skeleton; if (bone == null) { if (boneName == null || boneName.Length == 0) return; bone = skeleton.FindBone(boneName); if (bone == null) { Debug.LogError("Bone not found: " + boneName, this); return; } } float skeletonFlipRotation = (skeleton.flipX ^ skeleton.flipY) ? -1f : 1f; float flipCompensation = 0; if (flip && (flipX || (flipX != bone.flipX)) && bone.parent != null) { flipCompensation = bone.parent.WorldRotation * -2; } if (mode == Mode.Follow) { if (flip) { flipX = bone.flipX; } if (position) { cachedTransform.localPosition = new Vector3(bone.x, bone.y, 0); } if (rotation) { if (bone.Data.InheritRotation) { if (bone.FlipX) { cachedTransform.localRotation = Quaternion.Euler(0, 180, bone.rotationIK - flipCompensation); } else { cachedTransform.localRotation = Quaternion.Euler(0, 0, bone.rotationIK); } } else { Vector3 euler = skeletonTransform.rotation.eulerAngles; cachedTransform.rotation = Quaternion.Euler(euler.x, euler.y, skeletonTransform.rotation.eulerAngles.z + (bone.worldRotation * skeletonFlipRotation)); } } if (scale) { cachedTransform.localScale = new Vector3(bone.scaleX, bone.scaleY, bone.worldFlipX ? -1 : 1); nonUniformScaleWarning = (bone.scaleX != bone.scaleY); } } else if (mode == Mode.Override) { if (transformLerpComplete) return; if (parentReference == null) { if (position) { bone.x = Mathf.Lerp(bone.x, cachedTransform.localPosition.x, overrideAlpha); bone.y = Mathf.Lerp(bone.y, cachedTransform.localPosition.y, overrideAlpha); } if (rotation) { float angle = Mathf.LerpAngle(bone.Rotation, cachedTransform.localRotation.eulerAngles.z, overrideAlpha) + flipCompensation; if (flip) { if ((!flipX && bone.flipX)) { angle -= flipCompensation; } //TODO fix this... if (angle >= 360) angle -= 360; else if (angle <= -360) angle += 360; } bone.Rotation = angle; bone.RotationIK = angle; } if (scale) { bone.scaleX = Mathf.Lerp(bone.scaleX, cachedTransform.localScale.x, overrideAlpha); bone.scaleY = Mathf.Lerp(bone.scaleY, cachedTransform.localScale.y, overrideAlpha); nonUniformScaleWarning = (bone.scaleX != bone.scaleY); } if (flip) { bone.flipX = flipX; } } else { if (transformLerpComplete) return; if (position) { Vector3 pos = parentReference.InverseTransformPoint(cachedTransform.position); bone.x = Mathf.Lerp(bone.x, pos.x, overrideAlpha); bone.y = Mathf.Lerp(bone.y, pos.y, overrideAlpha); } if (rotation) { float angle = Mathf.LerpAngle(bone.Rotation, Quaternion.LookRotation(flipX ? Vector3.forward * -1 : Vector3.forward, parentReference.InverseTransformDirection(cachedTransform.up)).eulerAngles.z, overrideAlpha) + flipCompensation; if (flip) { if ((!flipX && bone.flipX)) { angle -= flipCompensation; } //TODO fix this... if (angle >= 360) angle -= 360; else if (angle <= -360) angle += 360; } bone.Rotation = angle; bone.RotationIK = angle; } //TODO: Something about this if (scale) { bone.scaleX = Mathf.Lerp(bone.scaleX, cachedTransform.localScale.x, overrideAlpha); bone.scaleY = Mathf.Lerp(bone.scaleY, cachedTransform.localScale.y, overrideAlpha); nonUniformScaleWarning = (bone.scaleX != bone.scaleY); } if (flip) { bone.flipX = flipX; } } transformLerpComplete = true; } } public void FlipX (bool state) { if (state != flipX) { flipX = state; if (flipX && Mathf.Abs(transform.localRotation.eulerAngles.y) > 90) { skeletonUtility.skeletonAnimation.LateUpdate(); return; } else if (!flipX && Mathf.Abs(transform.localRotation.eulerAngles.y) < 90) { skeletonUtility.skeletonAnimation.LateUpdate(); return; } } bone.FlipX = state; transform.RotateAround(transform.position, skeletonUtility.transform.up, 180); Vector3 euler = transform.localRotation.eulerAngles; euler.x = 0; euler.y = bone.FlipX ? 180 : 0; transform.localRotation = Quaternion.Euler(euler); } public void AddBoundingBox (string skinName, string slotName, string attachmentName) { SkeletonUtility.AddBoundingBox(bone.skeleton, skinName, slotName, attachmentName, transform); } void OnDrawGizmos () { if (NonUniformScaleWarning) { Gizmos.DrawIcon(transform.position + new Vector3(0, 0.128f, 0), "icon-warning"); } } }
using Serenity.Data; using Serenity.Data.Mapping; using System; using System.Collections.Generic; using System.Data; using System.Globalization; using System.Linq; using System.Reflection; namespace Serenity.Services { public class SaveRequestHandler<TRow, TSaveRequest, TSaveResponse> : ISaveRequestHandler where TRow : Row, IIdRow, new() where TSaveResponse : SaveResponse, new() where TSaveRequest : SaveRequest<TRow>, new() { private bool displayOrderFix; private static bool loggingInitialized; protected static CaptureLogHandler<TRow> captureLogHandler; protected static bool hasAuditLogAttribute; protected IEnumerable<SaveRequestBehaviourAttribute> behaviours; public SaveRequestHandler() { this.behaviours = this.GetType().GetCustomAttributes<SaveRequestBehaviourAttribute>(); } protected virtual void AfterSave() { HandleDisplayOrder(afterSave: true); foreach (var behaviour in this.behaviours) behaviour.OnAfterSave(this); } protected virtual void BeforeSave() { foreach (var behaviour in this.behaviours) behaviour.OnBeforeSave(this); } protected virtual void ClearNonTableAssignments() { foreach (var field in Row.GetFields()) { if (Row.IsAssigned(field) && !field.IsTableField()) Row.ClearAssignment(field); } } protected virtual void PerformAuditing() { if (!loggingInitialized) { var logTableAttr = typeof(TRow).GetCustomAttribute<CaptureLogAttribute>(); if (logTableAttr != null) captureLogHandler = new CaptureLogHandler<TRow>(); hasAuditLogAttribute = typeof(TRow).GetCustomAttribute<AuditLogAttribute>(false) != null; loggingInitialized = true; } if (captureLogHandler != null) DoCaptureLog(); else if (hasAuditLogAttribute) DoGenericAudit(); } protected virtual void DoCaptureLog() { if (IsUpdate) { var logRow = Row as ILoggingRow; bool anyChanged = false; foreach (var field in this.Row.GetTableFields()) { if (logRow != null && (ReferenceEquals(logRow.InsertDateField, field) || ReferenceEquals(logRow.UpdateDateField, field) || ReferenceEquals(logRow.InsertUserIdField, field) || ReferenceEquals(logRow.UpdateUserIdField, field))) { continue; } if (field.IndexCompare(Old, Row) != 0) { anyChanged = true; break; } } if (anyChanged) captureLogHandler.Log(this.UnitOfWork, this.Row, Authorization.UserId.TryParseID().Value, isDelete: false); } else if (IsCreate) { captureLogHandler.Log(this.UnitOfWork, this.Row, Authorization.UserId.TryParseID().Value, isDelete: false); } } protected virtual void DoGenericAudit() { var auditFields = new HashSet<Field>(); GetEditableFields(auditFields); var auditRequest = GetAuditRequest(auditFields); if (IsUpdate) { Row audit = null; if (auditRequest != null) audit = AuditLogService.PrepareAuditUpdate(RowRegistry.GetConnectionKey(Row), auditRequest); if (audit != null) Connection.Insert(audit); } else if (IsCreate) { if (auditRequest != null) AuditLogService.AuditInsert(Connection, RowRegistry.GetConnectionKey(Row), auditRequest); } } protected virtual void ExecuteSave() { if (IsUpdate) { if (Row.IsAnyFieldAssigned) { Connection.UpdateById(Row); InvalidateCacheOnCommit(); } } else if (IsCreate) { var idField = Row.IdField as Field; if (!ReferenceEquals(null, idField) && idField.Flags.HasFlag(FieldFlags.AutoIncrement)) { Response.EntityId = Connection.InsertAndGetID(Row); Row.IdField[Row] = Response.EntityId; } else { Connection.Insert(Row); if (!ReferenceEquals(null, idField)) Response.EntityId = Row.IdField[Row]; } InvalidateCacheOnCommit(); } } protected virtual AuditSaveRequest GetAuditRequest(HashSet<Field> auditFields) { Field[] array = new Field[auditFields.Count]; auditFields.CopyTo(array); var auditRequest = new AuditSaveRequest(Row.Table, (IIdRow)Old, (IIdRow)Row, array); var parentIdRow = Row as IParentIdRow; if (parentIdRow != null) { var parentIdField = (Field)parentIdRow.ParentIdField; if (!parentIdField.ForeignTable.IsTrimmedEmpty()) { auditRequest.ParentTypeId = parentIdField.ForeignTable; auditRequest.OldParentId = Old == null ? null : parentIdRow.ParentIdField[Old]; auditRequest.NewParentId = parentIdRow.ParentIdField[Row]; } } return auditRequest; } protected virtual BaseCriteria GetDisplayOrderFilter() { return DisplayOrderFilterHelper.GetDisplayOrderFilterFor(Row); } protected virtual void GetEditableFields(HashSet<Field> editable) { var flag = IsCreate ? FieldFlags.Insertable : FieldFlags.Updatable; foreach (var field in Row.GetFields()) if (field.Flags.HasFlag(flag)) editable.Add(field); } protected virtual void GetRequiredFields(HashSet<Field> required, HashSet<Field> editable) { foreach (var field in Row.GetFields()) { if (editable.Contains(field) && (field.Flags & FieldFlags.NotNull) == FieldFlags.NotNull & (field.Flags & FieldFlags.TrimToEmpty) != FieldFlags.TrimToEmpty) { required.Add(field); } } } protected virtual void HandleDisplayOrder(bool afterSave) { var displayOrderRow = Row as IDisplayOrderRow; if (displayOrderRow == null) return; if (IsCreate && !afterSave) { var value = displayOrderRow.DisplayOrderField.AsObject(Row); if (value == null || Convert.ToInt32(value) <= 0) { var filter = GetDisplayOrderFilter(); displayOrderRow.DisplayOrderField.AsObject(Row, DisplayOrderHelper.GetNextValue(Connection, displayOrderRow, filter)); } else displayOrderFix = true; } else if (afterSave && ((IsCreate && displayOrderFix) || (IsUpdate && displayOrderRow.DisplayOrderField[Old] != displayOrderRow.DisplayOrderField[Row]))) { DisplayOrderHelper.ReorderValues( connection: Connection, row: displayOrderRow, filter: GetDisplayOrderFilter(), recordID: Row.IdField[Row].Value, newDisplayOrder: displayOrderRow.DisplayOrderField[Row].Value, hasUniqueConstraint: false); } } protected virtual void HandleNonEditable(Field field) { if (IsUpdate && field.IndexCompare(Row, Old) == 0) { field.CopyNoAssignment(Old, Row); Row.ClearAssignment(field); return; } bool isNonTableField = ((field.Flags & FieldFlags.Foreign) == FieldFlags.Foreign) || ((field.Flags & FieldFlags.Calculated) == FieldFlags.Calculated) || ((field.Flags & FieldFlags.ClientSide) == FieldFlags.ClientSide); if (IsUpdate) { if ((field.Flags & FieldFlags.Reflective) != FieldFlags.Reflective) { if (!isNonTableField) throw DataValidation.ReadOnlyError(Row, field); field.CopyNoAssignment(Old, Row); Row.ClearAssignment(field); } } else if (IsCreate) { if (!field.IsNull(Row) && (field.Flags & FieldFlags.Reflective) != FieldFlags.Reflective) { if (!isNonTableField) throw DataValidation.ReadOnlyError(Row, field); field.AsObject(Row, null); Row.ClearAssignment(field); } } if (Row.IsAssigned(field)) Row.ClearAssignment(field); } protected virtual void LoadOldEntity() { var idField = (Field)(Row.IdField); var id = Row.IdField[Row].Value; if (!PrepareQuery().GetFirst(Connection)) throw DataValidation.EntityNotFoundError(Row, id); } protected virtual void OnReturn() { foreach (var behaviour in this.behaviours) behaviour.OnReturn(this); } protected virtual SqlQuery PrepareQuery() { var idField = (Field)(Row.IdField); var id = Row.IdField[Row].Value; return new SqlQuery() .From(Old) .SelectTableFields() .WhereEqual(idField, id); } public TSaveResponse Process(IUnitOfWork unitOfWork, TSaveRequest request, SaveRequestType requestType = SaveRequestType.Auto) { if (unitOfWork == null) throw new ArgumentNullException("unitOfWork"); UnitOfWork = unitOfWork; Request = request; Response = new TSaveResponse(); Row = request.Entity; if (Row == null) throw new ArgumentNullException("Entity"); if (requestType == SaveRequestType.Auto) { if (Row.IdField[Row] == null) requestType = SaveRequestType.Create; else requestType = SaveRequestType.Update; } if (requestType == SaveRequestType.Update) { ValidateAndClearIdField(); Old = new TRow(); LoadOldEntity(); } ValidateRequest(); SetInternalFields(); BeforeSave(); ClearNonTableAssignments(); ExecuteSave(); AfterSave(); PerformAuditing(); OnReturn(); return Response; } protected virtual void SetDefaultValue(Field field) { if (field.DefaultValue == null) return; field.AsObject(Row, field.ConvertValue(field.DefaultValue, CultureInfo.InvariantCulture)); } protected virtual void SetDefaultValues() { foreach (var field in Row.GetTableFields()) { if (Row.IsAssigned(field) || !field.IsNull(Row)) continue; SetDefaultValue(field); } var isActiveRow = Row as IIsActiveRow; if (isActiveRow != null && !Row.IsAssigned(isActiveRow.IsActiveField)) isActiveRow.IsActiveField[Row] = 1; } protected virtual void SetInternalFields() { if (IsCreate) { HandleDisplayOrder(afterSave: false); SetTrimToEmptyFields(); SetDefaultValues(); } SetInternalLogFields(); foreach (var behaviour in this.behaviours) behaviour.OnSetInternalFields(this); } protected virtual void SetInternalLogFields() { var updateLogRow = Row as IUpdateLogRow; var insertLogRow = Row as IInsertLogRow; if (updateLogRow != null && (IsUpdate || insertLogRow == null)) { updateLogRow.UpdateDateField[Row] = DateTimeField.ToDateTimeKind(DateTime.Now, updateLogRow.UpdateDateField.DateTimeKind); updateLogRow.UpdateUserIdField[Row] = Authorization.UserId.TryParseID(); } else if (insertLogRow != null && IsCreate) { insertLogRow.InsertDateField[Row] = DateTimeField.ToDateTimeKind(DateTime.Now, insertLogRow.InsertDateField.DateTimeKind); insertLogRow.InsertUserIdField[Row] = Authorization.UserId.TryParseID(); } } protected virtual void SetTrimToEmptyFields() { foreach (var field in Row.GetFields()) if (!Row.IsAssigned(field) && (field is StringField && (field.Flags & FieldFlags.Insertable) == FieldFlags.Insertable & (field.Flags & FieldFlags.NotNull) == FieldFlags.NotNull & (field.Flags & FieldFlags.TrimToEmpty) == FieldFlags.TrimToEmpty)) { ((StringField)field)[Row] = ""; } } protected virtual void ValidateEditableFields(HashSet<Field> editable) { foreach (Field field in Row.GetFields()) { if (IsUpdate && !Row.IsAssigned(field)) { field.CopyNoAssignment(Old, Row); Row.ClearAssignment(field); continue; } var stringField = field as StringField; if (!ReferenceEquals(null, stringField) && Row.IsAssigned(field) && (field.Flags & FieldFlags.Trim) == FieldFlags.Trim) { string value = stringField[Row]; if ((field.Flags & FieldFlags.TrimToEmpty) == FieldFlags.TrimToEmpty) value = value.TrimToEmpty(); else // TrimToNull value = value.TrimToNull(); stringField[Row] = value; } if (!editable.Contains(field)) HandleNonEditable(field); } } protected virtual HashSet<Field> ValidateEditable() { var editableFields = new HashSet<Field>(); GetEditableFields(editableFields); ValidateEditableFields(editableFields); return editableFields; } protected virtual void ValidateRequired(HashSet<Field> editableFields) { var requiredFields = new HashSet<Field>(); GetRequiredFields(required: requiredFields, editable: editableFields); if (IsUpdate) Row.ValidateRequiredIfModified(requiredFields); else Row.ValidateRequired(requiredFields); } protected virtual void ValidateRequest() { ValidatePermissions(); var editableFields = ValidateEditable(); ValidateRequired(editableFields); if (IsUpdate) ValidateIsActive(); ValidateFieldValues(); ValidateUniqueConstraints(); foreach (var behaviour in this.behaviours) behaviour.OnValidateRequest(this); } protected virtual void ValidateFieldValues() { var context = new RowValidationContext(this.Connection, this.Row); foreach (var field in Row.GetFields()) { if (!Row.IsAssigned(field)) continue; if (field.CustomAttributes == null) continue; var validators = field.CustomAttributes.OfType<ICustomValidator>(); foreach (var validator in validators) { context.Value = field.AsObject(this.Row); var error = CustomValidate(context, field, validator); if (error != null) throw new ValidationError("CustomValidationError", field.PropertyName ?? field.Name, error); } } } protected virtual void ValidateUniqueConstraints() { foreach (var field in Row.GetTableFields()) { if (!field.Flags.HasFlag(FieldFlags.Unique)) continue; var attr = field.CustomAttributes.OfType<UniqueAttribute>().FirstOrDefault(); if (attr != null && !attr.CheckBeforeSave) continue; ValidateUniqueConstraint(new Field[] { field }, attr == null ? (string)null : attr.ErrorMessage, Criteria.Empty); } foreach (var attr in typeof(TRow).GetCustomAttributes<UniqueConstraintAttribute>()) { if (!attr.CheckBeforeSave) continue; ValidateUniqueConstraint(attr.Fields.Select(x => { var field = Row.FindFieldByPropertyName(x) ?? Row.FindField(x); if (ReferenceEquals(null, field)) { throw new InvalidOperationException(String.Format( "Can't find field '{0}' of unique constraint in row type '{1}'", x, typeof(TRow).FullName)); } return field; }), attr.ErrorMessage, Criteria.Empty); } } protected virtual void ValidateUniqueConstraint(IEnumerable<Field> fields, string errorMessage = null, BaseCriteria groupCriteria = null) { if (IsUpdate && !fields.Any(x => x.IndexCompare(Old, Row) != 0)) return; var criteria = groupCriteria ?? Criteria.Empty; foreach (var field in fields) if (field.IsNull(Row)) criteria &= field.IsNull(); else criteria &= field == new ValueCriteria(field.AsObject(Row)); if (IsUpdate) criteria &= (Field)Row.IdField != Row.IdField[Old].Value; if (Connection.Exists<TRow>(criteria)) { throw new ValidationError("UniqueViolation", String.Join(", ", fields.Select(x => x.PropertyName ?? x.Name)), String.Format(!string.IsNullOrEmpty(errorMessage) ? (LocalText.TryGet(errorMessage) ?? errorMessage) : LocalText.Get("Validation.UniqueViolation"), String.Join(", ", fields.Select(x => x.Title)))); } } protected virtual string CustomValidate(RowValidationContext context, Field field, ICustomValidator validator) { return validator.Validate(context); } protected virtual void ValidateIsActive() { var isActiveRow = Old as IIsActiveRow; if (isActiveRow != null && isActiveRow.IsActiveField[Old] < 0) throw DataValidation.RecordNotActive(Old); } protected virtual void ValidateAndClearIdField() { var idField = (Field)(Row.IdField); Row.ValidateRequired(idField); Row.ClearAssignment(idField); } protected virtual void ValidatePermissions() { PermissionAttributeBase attr = null; if (IsUpdate) { typeof(TRow).GetCustomAttribute<UpdatePermissionAttribute>(false); } else if (IsCreate) { typeof(TRow).GetCustomAttribute<InsertPermissionAttribute>(false); } attr = attr ?? typeof(TRow).GetCustomAttribute<ModifyPermissionAttribute>(false); if (attr != null) { if (attr.Permission.IsNullOrEmpty()) Authorization.ValidateLoggedIn(); else Authorization.ValidatePermission(attr.Permission); } } protected virtual void InvalidateCacheOnCommit() { var attr = typeof(TRow).GetCustomAttribute<TwoLevelCachedAttribute>(false); if (attr != null) { BatchGenerationUpdater.OnCommit(this.UnitOfWork, Row.GetFields().GenerationKey); foreach (var key in attr.GenerationKeys) BatchGenerationUpdater.OnCommit(this.UnitOfWork, key); } } protected IDbConnection Connection { get { return UnitOfWork.Connection; } } public IUnitOfWork UnitOfWork { get; protected set; } public TRow Old { get; protected set; } public TRow Row { get; protected set; } public bool IsCreate { get { return Old == null; } } public bool IsUpdate { get { return Old != null; } } public TSaveRequest Request { get; protected set; } public TSaveResponse Response { get; protected set; } ISaveRequest ISaveRequestHandler.Request { get { return this.Request; } } SaveResponse ISaveRequestHandler.Response { get { return this.Response; } } Row ISaveRequestHandler.Old { get { return this.Old; } } Row ISaveRequestHandler.Row { get { return this.Row; } } } public class SaveRequestHandler<TRow> : SaveRequestHandler<TRow, SaveRequest<TRow>, SaveResponse> where TRow : Row, IIdRow, new() { } }
using SchemaZen.Library; using SchemaZen.Library.Models; using Test.Integration.Helpers; using Xunit; using Xunit.Abstractions; using ILogger = Microsoft.Extensions.Logging.ILogger; namespace Test.Integration; [Trait("Category", "Integration")] public class DatabaseTester { private readonly TestDbHelper _dbHelper; private readonly ILogger _logger; public DatabaseTester(ITestOutputHelper output, TestDbHelper dbHelper) { _logger = output.BuildLogger(); _dbHelper = dbHelper; } [Fact] public async Task TestDescIndex() { await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecSqlAsync(@"create table MyTable (Id int)"); await testDb.ExecSqlAsync(@"create nonclustered index MyIndex on MyTable (Id desc)"); var db = new Database("test") { Connection = testDb.GetConnString() }; db.Load(); var index = db.FindConstraint("MyIndex"); Assert.NotNull(index); Assert.True(index.Columns[0].Desc); } [Fact] public async Task TestTableIndexesWithFilter() { await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecSqlAsync( @"CREATE TABLE MyTable (Id int, EndDate datetime)"); await testDb.ExecSqlAsync( @"CREATE NONCLUSTERED INDEX MyIndex ON MyTable (Id) WHERE (EndDate) IS NULL"); var db = new Database("TEST") { Connection = testDb.GetConnString() }; db.Load(); var index = db.FindConstraint("MyIndex"); Assert.NotNull(index); Assert.Equal("([EndDate] IS NULL)", index.Filter); } [Fact] public async Task TestViewIndexes() { await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecSqlAsync( @"CREATE TABLE MyTable (Id int, Name nvarchar(250), EndDate datetime)"); await testDb.ExecSqlAsync( @"CREATE VIEW dbo.MyView WITH SCHEMABINDING as SELECT t.Id, t.Name, t.EndDate from dbo.MyTable t"); await testDb.ExecSqlAsync( @"CREATE UNIQUE CLUSTERED INDEX MyIndex ON MyView (Id, Name)"); var db = new Database("TEST") { Connection = testDb.GetConnString() }; db.Load(); var index = db.FindViewIndex("MyIndex"); Assert.NotNull(index); } [Fact] public async Task TestScript() { var db = new Database(_dbHelper.MakeTestDbName()); var t1 = new Table("dbo", "t1"); t1.Columns.Add(new Column("col1", "int", false, null) { Position = 1 }); t1.Columns.Add(new Column("col2", "int", false, null) { Position = 2 }); t1.AddConstraint( new Constraint("pk_t1", "PRIMARY KEY", "col1,col2") { IndexType = "CLUSTERED" }); var t2 = new Table("dbo", "t2"); t2.Columns.Add(new Column("col1", "int", false, null) { Position = 1 }); var col2 = new Column("col2", "int", false, null) { Position = 2 }; col2.Default = new Default(t2, col2, "df_col2", "((0))", false); t2.Columns.Add(col2); t2.Columns.Add(new Column("col3", "int", false, null) { Position = 3 }); t2.AddConstraint( new Constraint("pk_t2", "PRIMARY KEY", "col1") { IndexType = "CLUSTERED" }); t2.AddConstraint( Constraint.CreateCheckedConstraint("ck_col2", true, false, "([col2]>(0))")); t2.AddConstraint( new Constraint("IX_col3", "UNIQUE", "col3") { IndexType = "NONCLUSTERED" }); db.ForeignKeys.Add(new ForeignKey(t2, "fk_t2_t1", "col2,col3", t1, "col1,col2")); db.Tables.Add(t1); db.Tables.Add(t2); await using var testDb = await _dbHelper.CreateTestDb(db); var db2 = new Database(); db2.Connection = testDb.GetConnString(); db2.Load(); foreach (var t in db.Tables) { var copy = db2.FindTable(t.Name, t.Owner); Assert.NotNull(copy); Assert.False(copy.Compare(t).IsDiff); } } [Fact] public async Task TestScriptTableType() { var setupSQL1 = @" CREATE TYPE [dbo].[MyTableType] AS TABLE( [ID] [nvarchar](250) NULL, [Value] [numeric](5, 1) NULL, [LongNVarchar] [nvarchar](max) NULL ) "; await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecSqlAsync(setupSQL1); var db = new Database("test") { Connection = testDb.GetConnString() }; db.Load(); Assert.Single(db.TableTypes); var tt = db.TableTypes.FirstOrDefault(); if (tt == null) throw new Exception("impossible due to Assert.Single"); Assert.Equal(250, tt.Columns.Items[0].Length); Assert.Equal(1, tt.Columns.Items[1].Scale); Assert.Equal(5, tt.Columns.Items[1].Precision); Assert.Equal(-1, tt.Columns.Items[2].Length); Assert.Equal("MyTableType", tt.Name); var result = tt.ScriptCreate(); Assert.Contains( "CREATE TYPE [dbo].[MyTableType] AS TABLE", result); } [Fact] public async Task TestScriptTableTypePrimaryKey() { var sql = @" CREATE TYPE [dbo].[MyTableType] AS TABLE( [ID] [int] NOT NULL, [Value] [varchar](50) NOT NULL, PRIMARY KEY CLUSTERED ( [ID] ) ) "; await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecSqlAsync(sql); var db = new Database("test") { Connection = testDb.GetConnString() }; db.Load(); Assert.Single(db.TableTypes); var tt = db.TableTypes.FirstOrDefault(); if (tt == null) throw new Exception("impossible due to Assert.Single"); Assert.Single(tt.PrimaryKey.Columns); Assert.Equal("ID", tt.PrimaryKey.Columns[0].ColumnName); Assert.Equal(50, tt.Columns.Items[1].Length); Assert.Equal("MyTableType", tt.Name); var result = tt.ScriptCreate(); Assert.Contains("PRIMARY KEY", result); } [Fact] public async Task TestScriptTableTypeComputedColumn() { var sql = @" CREATE TYPE [dbo].[MyTableType] AS TABLE( [Value1] [int] NOT NULL, [Value2] [int] NOT NULL, [ComputedValue] AS ([VALUE1]+[VALUE2]) ) "; await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecSqlAsync(sql); var db = new Database("test") { Connection = testDb.GetConnString() }; db.Load(); Assert.Single(db.TableTypes); var tt = db.TableTypes.FirstOrDefault(); if (tt == null) throw new Exception("impossible due to Assert.Single"); Assert.Equal(3, tt.Columns.Items.Count()); Assert.Equal("ComputedValue", tt.Columns.Items[2].Name); Assert.Equal("([VALUE1]+[VALUE2])", tt.Columns.Items[2].ComputedDefinition); Assert.Equal("MyTableType", tt.Name); } [Fact] public async Task TestScriptTableTypeColumnCheckConstraint() { var sql = @" CREATE TYPE [dbo].[MyTableType] AS TABLE( [ID] [nvarchar](250) NULL, [Value] [numeric](5, 1) NULL CHECK([Value]>(0)), [LongNVarchar] [nvarchar](max) NULL ) "; await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecSqlAsync(sql); var db = new Database("test") { Connection = testDb.GetConnString() }; db.Load(); Assert.Single(db.TableTypes); var tt = db.TableTypes.FirstOrDefault(); if (tt == null) throw new Exception("impossible due to Assert.Single"); Assert.Single(tt.Constraints); var constraint = tt.Constraints.First(); Assert.Equal("([Value]>(0))", constraint.CheckConstraintExpression); Assert.Equal("MyTableType", db.TableTypes[0].Name); } [Fact] public async Task TestScriptTableTypeColumnDefaultConstraint() { var sql = @" CREATE TYPE [dbo].[MyTableType] AS TABLE( [ID] [nvarchar](250) NULL, [Value] [numeric](5, 1) NULL DEFAULT 0, [LongNVarchar] [nvarchar](max) NULL ) "; await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecSqlAsync(sql); var db = new Database("test") { Connection = testDb.GetConnString() }; db.Load(); Assert.Single(db.TableTypes); Assert.NotNull(db.TableTypes[0].Columns.Items[1].Default); Assert.Equal(" DEFAULT ((0))", db.TableTypes[0].Columns.Items[1].Default.ScriptCreate()); Assert.Equal("MyTableType", db.TableTypes[0].Name); } [Fact] public async Task TestScriptFKSameName() { var sql = @" CREATE SCHEMA [s2] AUTHORIZATION [dbo] CREATE TABLE [dbo].[t1a] ( a INT NOT NULL, CONSTRAINT [PK_1a] PRIMARY KEY (a) ) CREATE TABLE [dbo].[t1b] ( a INT NOT NULL, CONSTRAINT [FKName] FOREIGN KEY ([a]) REFERENCES [dbo].[t1a] ([a]) ON UPDATE CASCADE ) CREATE TABLE [s2].[t2a] ( a INT NOT NULL, CONSTRAINT [PK_2a] PRIMARY KEY (a) ) CREATE TABLE [s2].[t2b] ( a INT NOT NULL, CONSTRAINT [FKName] FOREIGN KEY ([a]) REFERENCES [s2].[t2a] ([a]) ON DELETE CASCADE ) "; await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecSqlAsync(sql); var db = new Database("test") { Connection = testDb.GetConnString() }; db.Load(); Assert.Equal(2, db.ForeignKeys.Count()); Assert.Equal(db.ForeignKeys[0].Name, db.ForeignKeys[1].Name); Assert.NotEqual(db.ForeignKeys[0].Table.Owner, db.ForeignKeys[1].Table.Owner); Assert.Equal("CASCADE", db.FindForeignKey("FKName", "dbo").OnUpdate); Assert.Equal("NO ACTION", db.FindForeignKey("FKName", "s2").OnUpdate); Assert.Equal("NO ACTION", db.FindForeignKey("FKName", "dbo").OnDelete); Assert.Equal("CASCADE", db.FindForeignKey("FKName", "s2").OnDelete); } [Fact] public async Task TestScriptViewInsteadOfTrigger() { var setupSQL1 = @" CREATE TABLE [dbo].[t1] ( a INT NOT NULL, CONSTRAINT [PK] PRIMARY KEY (a) ) "; var setupSQL2 = @" CREATE VIEW [dbo].[v1] AS SELECT * FROM t1 "; var setupSQL3 = @" CREATE TRIGGER [dbo].[TR_v1] ON [dbo].[v1] INSTEAD OF DELETE AS DELETE FROM [dbo].[t1] FROM [dbo].[t1] INNER JOIN DELETED ON DELETED.a = [dbo].[t1].a "; await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecSqlAsync(setupSQL1); await testDb.ExecSqlAsync(setupSQL2); await testDb.ExecSqlAsync(setupSQL3); var db = new Database("test") { Connection = testDb.GetConnString() }; db.Load(); var triggers = db.Routines.Where(x => x.RoutineType == Routine.RoutineKind.Trigger) .ToList(); Assert.Single(triggers); Assert.Equal("TR_v1", triggers[0].Name); } [Fact] public async Task TestScriptTriggerWithNoSets() { var setupSQL1 = @" CREATE TABLE [dbo].[t1] ( a INT NOT NULL, CONSTRAINT [PK] PRIMARY KEY (a) ) "; var setupSQL2 = @" CREATE TABLE [dbo].[t2] ( a INT NOT NULL ) "; var setupSQL3 = @" CREATE TRIGGER [dbo].[TR_1] ON [dbo].[t1] FOR UPDATE,INSERT AS INSERT INTO [dbo].[t2](a) SELECT a FROM INSERTED"; await using var testDb = await _dbHelper.CreateTestDbAsync(); await testDb.ExecSqlAsync(setupSQL1); await testDb.ExecSqlAsync(setupSQL2); await testDb.ExecSqlAsync(setupSQL3); var db = new Database("test") { Connection = testDb.GetConnString() }; db.Load(); // Set these properties to the defaults so they are not scripted db.FindProp("QUOTED_IDENTIFIER").Value = "ON"; db.FindProp("ANSI_NULLS").Value = "ON"; var trigger = db.FindRoutine("TR_1", "dbo"); var script = trigger.ScriptCreate(); Assert.DoesNotContain( "INSERTEDENABLE", script); } [Fact] public async Task TestScriptToDir() { var policy = new Table("dbo", "Policy"); policy.Columns.Add(new Column("id", "int", false, null) { Position = 1 }); policy.Columns.Add(new Column("form", "tinyint", false, null) { Position = 2 }); policy.AddConstraint( new Constraint("PK_Policy", "PRIMARY KEY", "id") { IndexType = "CLUSTERED", Unique = true }); policy.Columns.Items[0].Identity = new Identity(1, 1); var loc = new Table("dbo", "Location"); loc.Columns.Add(new Column("id", "int", false, null) { Position = 1 }); loc.Columns.Add(new Column("policyId", "int", false, null) { Position = 2 }); loc.Columns.Add(new Column("storage", "bit", false, null) { Position = 3 }); loc.Columns.Add(new Column("category", "int", false, null) { Position = 4 }); loc.AddConstraint( new Constraint("PK_Location", "PRIMARY KEY", "id") { IndexType = "CLUSTERED", Unique = true }); loc.Columns.Items[0].Identity = new Identity(1, 1); var formType = new Table("dbo", "FormType"); formType.Columns.Add(new Column("code", "tinyint", false, null) { Position = 1 }); formType.Columns.Add(new Column("desc", "varchar", 10, false, null) { Position = 2 }); formType.AddConstraint( new Constraint("PK_FormType", "PRIMARY KEY", "code") { IndexType = "CLUSTERED", Unique = true }); formType.AddConstraint( Constraint.CreateCheckedConstraint("CK_FormType", false, false, "([code]<(5))")); var categoryType = new Table("dbo", "CategoryType"); categoryType.Columns.Add(new Column("id", "int", false, null) { Position = 1 }); categoryType.Columns.Add( new Column("Category", "varchar", 10, false, null) { Position = 2 }); categoryType.AddConstraint( new Constraint("PK_CategoryType", "PRIMARY KEY", "id") { IndexType = "CLUSTERED", Unique = true }); var emptyTable = new Table("dbo", "EmptyTable"); emptyTable.Columns.Add(new Column("code", "tinyint", false, null) { Position = 1 }); emptyTable.AddConstraint( new Constraint("PK_EmptyTable", "PRIMARY KEY", "code") { IndexType = "CLUSTERED", Unique = true }); var fk_policy_formType = new ForeignKey("FK_Policy_FormType"); fk_policy_formType.Table = policy; fk_policy_formType.Columns.Add("form"); fk_policy_formType.RefTable = formType; fk_policy_formType.RefColumns.Add("code"); fk_policy_formType.OnUpdate = "NO ACTION"; fk_policy_formType.OnDelete = "NO ACTION"; var fk_location_policy = new ForeignKey("FK_Location_Policy"); fk_location_policy.Table = loc; fk_location_policy.Columns.Add("policyId"); fk_location_policy.RefTable = policy; fk_location_policy.RefColumns.Add("id"); fk_location_policy.OnUpdate = "NO ACTION"; fk_location_policy.OnDelete = "CASCADE"; var fk_location_category = new ForeignKey("FK_Location_category"); fk_location_category.Table = loc; fk_location_category.Columns.Add("category"); fk_location_category.RefTable = categoryType; fk_location_category.RefColumns.Add("id"); fk_location_category.OnUpdate = "NO ACTION"; fk_location_category.OnDelete = "CASCADE"; var tt_codedesc = new Table("dbo", "CodeDesc"); tt_codedesc.IsType = true; tt_codedesc.Columns.Add(new Column("code", "tinyint", false, null) { Position = 1 }); tt_codedesc.Columns.Add( new Column("desc", "varchar", 10, false, null) { Position = 2 }); tt_codedesc.AddConstraint( new Constraint("PK_CodeDesc", "PRIMARY KEY", "code") { IndexType = "NONCLUSTERED" }); var db = new Database("ScriptToDirTest"); db.Tables.Add(policy); db.Tables.Add(formType); db.Tables.Add(categoryType); db.Tables.Add(emptyTable); db.Tables.Add(loc); db.TableTypes.Add(tt_codedesc); db.ForeignKeys.Add(fk_policy_formType); db.ForeignKeys.Add(fk_location_policy); db.ForeignKeys.Add(fk_location_category); db.FindProp("COMPATIBILITY_LEVEL").Value = "110"; db.FindProp("COLLATE").Value = "SQL_Latin1_General_CP1_CI_AS"; db.FindProp("AUTO_CLOSE").Value = "OFF"; db.FindProp("AUTO_SHRINK").Value = "ON"; db.FindProp("ALLOW_SNAPSHOT_ISOLATION").Value = "ON"; db.FindProp("READ_COMMITTED_SNAPSHOT").Value = "OFF"; db.FindProp("RECOVERY").Value = "SIMPLE"; db.FindProp("PAGE_VERIFY").Value = "CHECKSUM"; db.FindProp("AUTO_CREATE_STATISTICS").Value = "ON"; db.FindProp("AUTO_UPDATE_STATISTICS").Value = "ON"; db.FindProp("AUTO_UPDATE_STATISTICS_ASYNC").Value = "ON"; db.FindProp("ANSI_NULL_DEFAULT").Value = "ON"; db.FindProp("ANSI_NULLS").Value = "ON"; db.FindProp("ANSI_PADDING").Value = "ON"; db.FindProp("ANSI_WARNINGS").Value = "ON"; db.FindProp("ARITHABORT").Value = "ON"; db.FindProp("CONCAT_NULL_YIELDS_NULL").Value = "ON"; db.FindProp("NUMERIC_ROUNDABORT").Value = "ON"; db.FindProp("QUOTED_IDENTIFIER").Value = "ON"; db.FindProp("RECURSIVE_TRIGGERS").Value = "ON"; db.FindProp("CURSOR_CLOSE_ON_COMMIT").Value = "ON"; db.FindProp("CURSOR_DEFAULT").Value = "LOCAL"; db.FindProp("TRUSTWORTHY").Value = "ON"; db.FindProp("DB_CHAINING").Value = "ON"; db.FindProp("PARAMETERIZATION").Value = "FORCED"; db.FindProp("DATE_CORRELATION_OPTIMIZATION").Value = "ON"; await _dbHelper.DropDbAsync(db.Name); await using var testDb = await _dbHelper.CreateTestDb(db); db.Connection = testDb.GetConnString(); DBHelper.ExecSql( db.Connection, " insert into formType ([code], [desc]) values (1, 'DP-1')\n" + "insert into formType ([code], [desc]) values (2, 'DP-2')\n" + "insert into formType ([code], [desc]) values (3, 'DP-3')"); db.DataTables.Add(formType); db.DataTables.Add(emptyTable); db.Dir = db.Name; if (Directory.Exists(db.Dir)) Directory.Delete(db.Dir, true); db.ScriptToDir(); Assert.True(Directory.Exists(db.Name)); Assert.True(Directory.Exists(db.Name + "/data")); Assert.True(Directory.Exists(db.Name + "/tables")); Assert.True(Directory.Exists(db.Name + "/foreign_keys")); foreach (var t in db.DataTables) if (t.Name == "EmptyTable") Assert.False(File.Exists(db.Name + "/data/" + t.Name + ".tsv")); else Assert.True(File.Exists(db.Name + "/data/" + t.Name + ".tsv")); foreach (var t in db.Tables) { var tblFile = db.Name + "/tables/" + t.Name + ".sql"; Assert.True(File.Exists(tblFile)); // Test that the constraints are ordered in the file var script = File.ReadAllText(tblFile); var cindex = -1; foreach (var ckobject in t.Constraints.Where(c => c.Type != "CHECK") .OrderBy(x => x.Name)) { var thisindex = script.IndexOf(ckobject.ScriptCreate()); Assert.True(thisindex > cindex, "Constraints are not ordered."); cindex = thisindex; } } foreach (var t in db.TableTypes) Assert.True(File.Exists(db.Name + "/table_types/TYPE_" + t.Name + ".sql")); foreach (var expected in db.ForeignKeys.Select( fk => db.Name + "/foreign_keys/" + fk.Table.Name + ".sql")) Assert.True(File.Exists(expected), "File does not exist" + expected); // Test that the foreign keys are ordered in the file foreach (var t in db.Tables) { var fksFile = db.Name + "/foreign_keys/" + t.Name + ".sql"; if (File.Exists(fksFile)) { var script = File.ReadAllText(fksFile); var fkindex = -1; foreach (var fkobject in db.ForeignKeys.Where(x => x.Table == t) .OrderBy(x => x.Name)) { var thisindex = script.IndexOf(fkobject.ScriptCreate()); Assert.True(thisindex > fkindex, "Foreign keys are not ordered."); fkindex = thisindex; } } } var copy = new Database("ScriptToDirTestCopy"); await _dbHelper.DropDbAsync("ScriptToDirTestCopy"); await using var testDb2 = await _dbHelper.CreateTestDb(copy); copy.Dir = db.Dir; copy.Connection = testDb2.GetConnString(); copy.CreateFromDir(true); copy.Load(); Assert.False(db.Compare(copy).IsDiff); } [Fact] public async Task TestScriptToDirOnlyCreatesNecessaryFolders() { var db = new Database("TestEmptyDB"); await _dbHelper.DropDbAsync(db.Name); await using var testDb = await _dbHelper.CreateTestDb(db); db.Load(); if (Directory.Exists(db.Dir)) Directory.Delete(db.Dir, true); db.ScriptToDir(); Assert.Empty(db.Assemblies); Assert.Empty(db.DataTables); Assert.Empty(db.ForeignKeys); Assert.Empty(db.Routines); Assert.Empty(db.Schemas); Assert.Empty(db.Synonyms); Assert.Empty(db.Tables); Assert.Empty(db.TableTypes); Assert.Empty(db.Users); Assert.Empty(db.ViewIndexes); Assert.True(Directory.Exists(db.Name)); Assert.True(File.Exists(db.Name + "/props.sql")); //Assert.IsFalse(File.Exists(db.Name + "/schemas.sql")); Assert.False(Directory.Exists(db.Name + "/assemblies")); Assert.False(Directory.Exists(db.Name + "/data")); Assert.False(Directory.Exists(db.Name + "/foreign_keys")); foreach (var routineType in Enum.GetNames(typeof(Routine.RoutineKind))) { var dir = routineType.ToLower() + "s"; Assert.False(Directory.Exists(db.Name + "/" + dir)); } Assert.False(Directory.Exists(db.Name + "/synonyms")); Assert.False(Directory.Exists(db.Name + "/tables")); Assert.False(Directory.Exists(db.Name + "/table_types")); Assert.False(Directory.Exists(db.Name + "/users")); } }
using System; using System.IO; using System.IO.Compression; 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.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NetCoreForce.Client.Serializer; using NetCoreForce.Client.Models; namespace NetCoreForce.Client { public class JsonClient : IDisposable { private const string JsonMimeType = "application/json"; // private const string GZipEncoding = "gzip"; // private const string DeflateEncoding = "deflate"; //best practice is to reuse HttpClient //https://github.com/mspnp/performance-optimization/blob/master/ImproperInstantiation/docs/ImproperInstantiation.md //By default, and the ideal case, is using the static readonly HttpClient. //Alternatively, for testing and special cases, a class instance instnace of an HttpClient can be used instead. private static readonly HttpClient _SharedHttpClient; private HttpClient _httpClient; private HttpClient SharedHttpClient { get { //use the instance client when extant, otherwise use the default shared instance. return _httpClient ?? _SharedHttpClient; } } AuthenticationHeaderValue _authHeaderValue; /// <summary> /// JSON Client static constructor, initializes the default shared HttpClient instance. /// </summary> static JsonClient() { _SharedHttpClient = HttpClientFactory.CreateHttpClient(); } /// <summary> /// Intialize the JSON client. /// <para>By default, uses a shared static HttpClient instance for best performance.</para> /// </summary> /// <param name="accessToken">API Access token</param> /// <param name="httpClient">Optional custom HttpClient. Ideally this should be a shared static instance for best performance.</param> public JsonClient(string accessToken, HttpClient httpClient = null) { _authHeaderValue = new AuthenticationHeaderValue("Bearer", accessToken); if (httpClient != null) { _httpClient = httpClient; } } public async Task<T> HttpGetAsync<T>(Uri uri, Dictionary<string, string> customHeaders = null, bool deserializeResponse = true) { //TODO: can this handle T = string? return await HttpAsync<T>(uri, HttpMethod.Get, null, customHeaders, deserializeResponse); } public async Task<T> HttpPostAsync<T>(object inputObject, Uri uri, Dictionary<string, string> customHeaders = null, bool deserializeResponse = true) { var json = JsonSerializer.SerializeForCreate(inputObject); var content = new StringContent(json, Encoding.UTF8, JsonMimeType); HttpRequestMessage request = new HttpRequestMessage(); request.Headers.Authorization = _authHeaderValue; request.RequestUri = uri; request.Method = HttpMethod.Post; request.Content = content; return await GetResponse<T>(request, customHeaders, deserializeResponse); } /// <summary> /// Submits a PATCH request /// </summary> /// <param name="inputObject"></param> /// <param name="uri"></param> /// <param name="customHeaders"></param> /// <param name="deserializeResponse"></param> /// <param name="serializeComplete">Serializes ALL object properties to include in the request, even those not appropriate for some update/patch calls.</param> /// <param name="includeSObjectId">includes the SObject ID when serializing the request content</param> /// <typeparam name="T"></typeparam> /// <returns></returns> public async Task<T> HttpPatchAsync<T>(object inputObject, Uri uri, Dictionary<string, string> customHeaders = null, bool deserializeResponse = true, bool serializeComplete = false, bool includeSObjectId = false) { string json; if (serializeComplete) { json = JsonSerializer.SerializeComplete(inputObject, false); } else if (includeSObjectId) { json = JsonSerializer.SerializeForUpdateWithObjectId(inputObject); } else { json = JsonSerializer.SerializeForUpdate(inputObject); } var content = new StringContent(json, Encoding.UTF8, JsonMimeType); return await HttpAsync<T>(uri, new HttpMethod("PATCH"), content, customHeaders, deserializeResponse); } public async Task<T> HttpDeleteAsync<T>(Uri uri, Dictionary<string, string> customHeaders = null, bool deserializeResponse = true) { HttpRequestMessage request = new HttpRequestMessage(); request.Headers.Authorization = _authHeaderValue; request.RequestUri = uri; request.Method = HttpMethod.Delete; return await GetResponse<T>(request, customHeaders, deserializeResponse); } private async Task<T> HttpAsync<T>(Uri uri, HttpMethod httpMethod, HttpContent content = null, Dictionary<string, string> customHeaders = null, bool deserializeResponse = true) { HttpRequestMessage request = new HttpRequestMessage(); request.Headers.Authorization = _authHeaderValue; request.RequestUri = uri; request.Method = httpMethod; if (content != null) { request.Content = content; } return await GetResponse<T>(request, customHeaders, deserializeResponse); } /// <summary> /// Get a http client reponse /// </summary> /// <param name="request">HttpRequestMessage containing the request details</param> /// <param name="customHeaders">Custom headers, if any</param> /// <param name="deserializeResponse">Should the response be deserialized for successful (HTTP 2xx) requests. Default is true/yes. /// If false/no, this effectively ignores the content of any 2xx type response. /// Errors will still be deserialized.</param> /// <typeparam name="T">Type used to deserialize the reponse content</typeparam> /// <returns></returns> private async Task<T> GetResponse<T>(HttpRequestMessage request, Dictionary<string, string> customHeaders = null, bool deserializeResponse = true) { if (customHeaders != null && customHeaders.Count > 0) { foreach (KeyValuePair<string, string> header in customHeaders) { request.Headers.Add(header.Key, header.Value); } } HttpResponseMessage responseMessage = null; try { responseMessage = await SharedHttpClient.SendAsync(request).ConfigureAwait(false); } catch (Exception ex) { string errMsg = "Error sending HTTP request:" + ex.Message; if (ex.InnerException != null && !string.IsNullOrEmpty(ex.InnerException.Message)) { errMsg += " " + ex.InnerException.Message; } Debug.WriteLine(errMsg); throw new ForceApiException(errMsg); } #if DEBUG //API usage response header //e.g. "Sforce-Limit-Info: api-usage=90/15000" const string SforceLimitInfoHeaderName = "Sforce-Limit-Info"; IEnumerable<string> limitValues = GetHeaderValues(responseMessage.Headers, SforceLimitInfoHeaderName); if (limitValues != null) { Debug.WriteLine(string.Format("{0}: {1}", SforceLimitInfoHeaderName, limitValues.FirstOrDefault() ?? "none")); } #endif if (responseMessage.StatusCode == HttpStatusCode.NoContent) { return JsonConvert.DeserializeObject<T>(string.Empty); } //sucessful response, skip deserialization of response content if (responseMessage.IsSuccessStatusCode && !deserializeResponse) { return JsonConvert.DeserializeObject<T>(string.Empty); } if (responseMessage.Content != null) { try { string responseContent = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); if (responseMessage.IsSuccessStatusCode) { if (string.IsNullOrEmpty(responseContent)) { throw new ForceApiException("Response content was empty"); } return JsonConvert.DeserializeObject<T>(responseContent); } if (responseMessage.StatusCode == HttpStatusCode.MultipleChoices) { // Returned when an external ID exists in more than one record // https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_upsert.htm // If the external ID value isn't unique, an HTTP status code 300 is returned, plus a list of the records that matched the query. if (string.IsNullOrEmpty(responseContent)) { throw new ForceApiException("Response content was empty"); } var results = JsonConvert.DeserializeObject<List<string>>(responseContent); var fex = new ForceApiException("Multiple matches for External ID value, see ObjectUrls"); fex.ObjectUrls = results; throw fex; } else { string msg = string.Format("Unable to complete request, Salesforce API returned {0}.", responseMessage.StatusCode.ToString()); List<ErrorResponse> errors = null; try { errors = JsonConvert.DeserializeObject<List<ErrorResponse>>(responseContent); // There will often only be one error code - append this to the message if (errors != null && errors.Count > 0) { msg += string.Format(" ErrorCode {0}: {1}.", errors[0].ErrorCode, errors[0].Message); } // inform if there are multiple errors that need to be checked if (errors != null && errors.Count > 1) { msg += " Additional errors returned, see Errors for complete list."; } } catch (Exception ex) { msg += string.Format(" Unable to parse error details: {0}" + ex.Message); } throw new ForceApiException(msg, errors, responseMessage.StatusCode); } } catch (ForceApiException) { throw; } catch (Exception ex) { throw new ForceApiException(string.Format("Error parsing response content: {0}", ex.Message)); } } throw new ForceApiException(string.Format("Error processing response: returned {0} for {1}", responseMessage.ReasonPhrase, request.RequestUri.ToString())); } /// <summary> /// Get values for a particular reponse header /// </summary> /// <param name="headers">HttpHeaders from the HttpResponseMessage</param> /// <param name="headerName">Header Name</param> /// <returns>IEnumerable{string} of header values, if any, Null if none found.</returns> private IEnumerable<string> GetHeaderValues(HttpHeaders headers, string headerName) { if (headers != null) { IEnumerable<string> values; if (headers.TryGetValues(headerName, out values)) { return values; } } Debug.WriteLine(string.Format("{0} header not found in response", headerName)); return null; } /// <summary> /// Dispose client - only disposes instance HttpClient, if any. Shared static HttpClient is left as-is. /// </summary> public void Dispose() { //only dispose instance member, if any if (_httpClient != null) { _httpClient.Dispose(); } } } }
// // ServiceTests.cs // // Author: // Scott Peterson <[email protected]> // // Copyright (c) 2009 Scott Peterson // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using NUnit.Framework; using Mono.Upnp.Control; namespace Mono.Upnp.Tests { [TestFixture] public class ServiceTests { class ActionTestClass { [UpnpAction] public void Foo () { } } [Test] public void ActionTest () { var service = new DummyService<ActionTestClass> (); var controller = new ServiceController (new[] { new DummyServiceAction ("Foo") }, null); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } class ActionNameTestClass { [UpnpAction ("foo")] public void Foo () { } } [Test] public void ActionNameTest () { var service = new DummyService<ActionNameTestClass> (); var controller = new ServiceController (new[] { new DummyServiceAction ("foo") }, null); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } class ArgumentTestClass { [UpnpAction] public void Foo (string bar) { } } [Test] public void ArgumentTest () { var service = new DummyService<ArgumentTestClass> (); var controller = new ServiceController ( new[] { new DummyServiceAction ("Foo", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) }) }, new[] { new StateVariable ("A_ARG_bar", "string") } ); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } class OutArgumentTestClass { [UpnpAction] public void Foo (out string bar) { bar = string.Empty; } } [Test] public void OutArgumentTest () { var service = new DummyService<OutArgumentTestClass> (); var controller = new ServiceController ( new[] { new DummyServiceAction ("Foo", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.Out) }) }, new[] { new StateVariable ("A_ARG_bar", "string") } ); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } class RefArgumentTestClass { [UpnpAction] public void Foo (ref string bar) { } } [Test] public void RefArgumentTest () { var service = new DummyService<RefArgumentTestClass> (); var controller = new ServiceController ( new[] { new DummyServiceAction ("Foo", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.Out) }) }, new[] { new StateVariable ("A_ARG_bar", "string") } ); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } class ReturnArgumentTestClass { [UpnpAction] public string Foo () { return string.Empty; } } [Test] public void ReturnArgumentTest () { var service = new DummyService<ReturnArgumentTestClass> (); var controller = new ServiceController ( new[] { new DummyServiceAction ("Foo", new[] { new Argument ("result", "A_ARG_result", ArgumentDirection.Out, true) }) }, new[] { new StateVariable ("A_ARG_result", "string") } ); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } class ArgumentNameTestClass { [UpnpAction] public void Foo ([UpnpArgument ("Bar")]string bar) { } } [Test] public void ArgumentNameTest () { var service = new DummyService<ArgumentNameTestClass> (); var controller = new ServiceController ( new[] { new DummyServiceAction ("Foo", new[] { new Argument ("Bar", "A_ARG_Bar", ArgumentDirection.In) }) }, new[] { new StateVariable ("A_ARG_Bar", "string") } ); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } class ReturnArgumentNameTestClass { [UpnpAction] [return: UpnpArgument ("foo")] public string Foo () { return null; } } [Test] public void ReturnArgumentNameTest () { var service = new DummyService<ReturnArgumentNameTestClass> (); var controller = new ServiceController ( new[] { new DummyServiceAction ("Foo", new[] { new Argument ("foo", "A_ARG_foo", ArgumentDirection.Out, true) }) }, new[] { new StateVariable ("A_ARG_foo", "string") } ); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } class ReturnArgumentDirectionTestClass { [UpnpAction] public string Foo() { return null; } } [Test] public void ReturnArgumentDirectionTest () { var service = new DummyService<ReturnArgumentDirectionTestClass> (); var controller = new ServiceController ( new[] { new DummyServiceAction ("Foo", new[] { new Argument ("result", "A_ARG_result", ArgumentDirection.Out, true) }) }, new[] { new StateVariable ("A_ARG_result", "string") } ); ServiceDescriptionTests.AssertEquality (controller, service.GetController()); } class RelatedStateVariableNameTestClass { [UpnpAction] public void Foo ([UpnpRelatedStateVariable ("X_ARG_bar")]string bar) { } } [Test] public void RelatedStateVariableNameTest () { var service = new DummyService<RelatedStateVariableNameTestClass> (); var controller = new ServiceController ( new[] { new DummyServiceAction ("Foo", new[] { new Argument ("bar", "X_ARG_bar", ArgumentDirection.In) }) }, new[] { new StateVariable ("X_ARG_bar", "string") } ); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } class ReturnArgumentRelatedStateVariableNameTestClass { [UpnpAction] [return: UpnpRelatedStateVariable ("X_ARG_foo")] public string Foo () { return null; } } [Test] public void ReturnArgumentRelatedStateVariableNameTest () { var service = new DummyService<ReturnArgumentRelatedStateVariableNameTestClass> (); var controller = new ServiceController ( new[] { new DummyServiceAction ("Foo", new[] { new Argument ("result", "X_ARG_foo", ArgumentDirection.Out, true) }) }, new[] { new StateVariable ("X_ARG_foo", "string") } ); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } class RelatedStateVariableDataTypeTestClass { [UpnpAction] public void Foo ([UpnpRelatedStateVariable (DataType = "string.foo")]string bar) { } } [Test] public void RelatedStateVariableDataTypeTest () { var service = new DummyService<RelatedStateVariableDataTypeTestClass> (); var controller = new ServiceController ( new[] { new DummyServiceAction ("Foo", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) }) }, new[] { new StateVariable ("A_ARG_bar", "string.foo") } ); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } class RelatedStateVariableDefaultValueTestClass { [UpnpAction] public void Foo ([UpnpRelatedStateVariable (DefaultValue = "hey")]string bar) { } } [Test] public void RelatedStateVariableDefaultValueTest () { var service = new DummyService<RelatedStateVariableDefaultValueTestClass> (); var controller = new ServiceController ( new[] { new DummyServiceAction ("Foo", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) }) }, new[] { new StateVariable ("A_ARG_bar", "string", new StateVariableOptions { DefaultValue = "hey" }) } ); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } class RelatedStateVariableAllowedValueRangeTestClass { [UpnpAction] public void Foo ([UpnpRelatedStateVariable ("0", "100", StepValue = "2")]int bar) { } } [Test] public void RelatedStateVariableAllowedValueRangeTest () { var service = new DummyService<RelatedStateVariableAllowedValueRangeTestClass> (); var controller = new ServiceController ( new[] { new DummyServiceAction ("Foo", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) }) }, new[] { new StateVariable ("A_ARG_bar", "i4", new AllowedValueRange ("0", "100", "2")) } ); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } enum EnumArgumentTestEnum { Foo, Bar } class EnumArgumentTestClass { [UpnpAction] public void Foo (EnumArgumentTestEnum bar) { } } [Test] public void EnumArgumentTest () { var service = new DummyService<EnumArgumentTestClass> (); var controller = new ServiceController ( new[] { new DummyServiceAction ("Foo", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) }) }, new[] { new StateVariable ("A_ARG_bar", new[] { "Foo", "Bar" }) } ); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } enum EnumArgumentNameTestEnum { [UpnpEnum ("foo")] Foo, [UpnpEnum ("bar")] Bar } class EnumArgumentNameTestClass { [UpnpAction] public void Foo (EnumArgumentNameTestEnum bar) { } } [Test] public void EnumArgumentNameTest () { var service = new DummyService<EnumArgumentNameTestClass> (); var controller = new ServiceController ( new[] { new DummyServiceAction ("Foo", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) }) }, new[] { new StateVariable ("A_ARG_bar", new[] { "foo", "bar" }) } ); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } class ArgumentNameAgreementTestClass { [UpnpAction] public void Foo (string bar) { } [UpnpAction] public void Bar (string bar) { } } [Test] public void ArgumentNameAgreementTest () { var service = new DummyService<ArgumentNameAgreementTestClass> (); var controller = new ServiceController ( new[] { new DummyServiceAction ("Foo", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) }), new DummyServiceAction ("Bar", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) }) }, new[] { new StateVariable ("A_ARG_bar", "string") } ); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } class ArgumentTypeConflictTestClass { [UpnpAction] public void Foo (string bar) { } [UpnpAction] public void Bar (int bar) { } } [Test] public void ArgumentTypeConflictTest () { var service = new DummyService<ArgumentTypeConflictTestClass> (); var controller = new ServiceController ( new[] { new DummyServiceAction ("Foo", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) }), new DummyServiceAction ("Bar", new[] { new Argument ("bar", "A_ARG_Bar_bar", ArgumentDirection.In) }) }, new[] { new StateVariable ("A_ARG_bar", "string"), new StateVariable ("A_ARG_Bar_bar", "i4") } ); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } class RelatedStateVariableAllowedValueRangeConflictTest1Class { [UpnpAction] public void Foo (int bar) { } [UpnpAction] public void Bar ([UpnpRelatedStateVariable("0", "100")] int bar) { } } [Test] public void RelatedStateVariableAllowedValueRangeConflictTest1 () { var service = new DummyService<RelatedStateVariableAllowedValueRangeConflictTest1Class> (); var controller = new ServiceController ( new[] { new DummyServiceAction ("Foo", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) }), new DummyServiceAction ("Bar", new[] { new Argument ("bar", "A_ARG_Bar_bar", ArgumentDirection.In) }) }, new[] { new StateVariable ("A_ARG_bar", "i4"), new StateVariable ("A_ARG_Bar_bar", "i4", new AllowedValueRange ("0", "100")) } ); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } class RelatedStateVariableAllowedValueRangeConflictTest2Class { [UpnpAction] public void Foo ([UpnpRelatedStateVariable("0", "100")] int bar) { } [UpnpAction] public void Bar (int bar) { } } [Test] public void RelatedStateVariableAllowedValueRangeConflictTest2 () { var service = new DummyService<RelatedStateVariableAllowedValueRangeConflictTest2Class> (); var controller = new ServiceController ( new[] { new DummyServiceAction ("Foo", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) }), new DummyServiceAction ("Bar", new[] { new Argument ("bar", "A_ARG_Bar_bar", ArgumentDirection.In) }) }, new[] { new StateVariable ("A_ARG_bar", "i4", new AllowedValueRange ("0", "100")), new StateVariable ("A_ARG_Bar_bar", "i4") } ); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } class RelatedStateVariableAllowedValueRangeConflictTest3Class { [UpnpAction] public void Foo ([UpnpRelatedStateVariable("0", "100")] int bar) { } [UpnpAction] public void Bar ([UpnpRelatedStateVariable("0", "101")] int bar) { } } [Test] public void RelatedStateVariableAllowedValueRangeConflictTest3 () { var service = new DummyService<RelatedStateVariableAllowedValueRangeConflictTest3Class> (); var controller = new ServiceController ( new[] { new DummyServiceAction ("Foo", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) }), new DummyServiceAction ("Bar", new[] { new Argument ("bar", "A_ARG_Bar_bar", ArgumentDirection.In) }) }, new[] { new StateVariable ("A_ARG_bar", "i4", new AllowedValueRange ("0", "100")), new StateVariable ("A_ARG_Bar_bar", "i4", new AllowedValueRange ("0", "101")) } ); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } class RelatedStateVariableAllowedValuesConflictTest1Class { [UpnpAction] public void Foo (string bar) { } [UpnpAction] public void Bar (EnumArgumentTestEnum bar) { } } [Test] public void RelatedStateVariableAllowedValuesConflictTest1 () { var service = new DummyService<RelatedStateVariableAllowedValuesConflictTest1Class> (); var controller = new ServiceController ( new[] { new DummyServiceAction ("Foo", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) }), new DummyServiceAction ("Bar", new[] { new Argument ("bar", "A_ARG_Bar_bar", ArgumentDirection.In) }) }, new[] { new StateVariable ("A_ARG_bar", "string"), new StateVariable ("A_ARG_Bar_bar", new[] { "Foo", "Bar" }) } ); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } class RelatedStateVariableAllowedValuesConflictTest2Class { [UpnpAction] public void Foo (EnumArgumentTestEnum bar) { } [UpnpAction] public void Bar (string bar) { } } [Test] public void RelatedStateVariableAllowedValuesConflictTest2 () { var service = new DummyService<RelatedStateVariableAllowedValuesConflictTest2Class> (); var controller = new ServiceController ( new[] { new DummyServiceAction ("Foo", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) }), new DummyServiceAction ("Bar", new[] { new Argument ("bar", "A_ARG_Bar_bar", ArgumentDirection.In) }) }, new[] { new StateVariable ("A_ARG_bar", new[] { "Foo", "Bar" }), new StateVariable ("A_ARG_Bar_bar", "string") } ); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } class RelatedStateVariableAllowedValuesConflictTest3Class { [UpnpAction] public void Foo (EnumArgumentTestEnum bar) { } [UpnpAction] public void Bar (EnumArgumentNameTestEnum bar) { } } [Test] public void RelatedStateVariableAllowedValuesConflictTest3 () { var service = new DummyService<RelatedStateVariableAllowedValuesConflictTest3Class> (); var controller = new ServiceController ( new[] { new DummyServiceAction ("Foo", new[] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) }), new DummyServiceAction ("Bar", new[] { new Argument ("bar", "A_ARG_Bar_bar", ArgumentDirection.In) }) }, new[] { new StateVariable ("A_ARG_bar", new[] { "Foo", "Bar" }), new StateVariable ("A_ARG_Bar_bar", new[] { "foo", "bar" }) } ); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } class ArgumentsTestClass { [UpnpAction] public void Foo (string stringArg, int intArg, byte byteArg, ushort ushortArg, uint uintArg, sbyte sbyteArg, short shortArg, long longArg, float floatArg, double doubleArg, char charArg, DateTime dateTimeArg, bool boolArg, byte[] byteArrayArg, Uri uriArg) { } } [Test] public void ArgumentsTest () { var service = new DummyService<ArgumentsTestClass> (); var controller = new ServiceController ( new[] { new DummyServiceAction ("Foo", new[] { new Argument ("stringArg", "A_ARG_stringArg", ArgumentDirection.In), new Argument ("intArg", "A_ARG_intArg", ArgumentDirection.In), new Argument ("byteArg", "A_ARG_byteArg", ArgumentDirection.In), new Argument ("ushortArg", "A_ARG_ushortArg", ArgumentDirection.In), new Argument ("uintArg", "A_ARG_uintArg", ArgumentDirection.In), new Argument ("sbyteArg", "A_ARG_sbyteArg", ArgumentDirection.In), new Argument ("shortArg", "A_ARG_shortArg", ArgumentDirection.In), new Argument ("longArg", "A_ARG_longArg", ArgumentDirection.In), new Argument ("floatArg", "A_ARG_floatArg", ArgumentDirection.In), new Argument ("doubleArg", "A_ARG_doubleArg", ArgumentDirection.In), new Argument ("charArg", "A_ARG_charArg", ArgumentDirection.In), new Argument ("dateTimeArg", "A_ARG_dateTimeArg", ArgumentDirection.In), new Argument ("boolArg", "A_ARG_boolArg", ArgumentDirection.In), new Argument ("byteArrayArg", "A_ARG_byteArrayArg", ArgumentDirection.In), new Argument ("uriArg", "A_ARG_uriArg", ArgumentDirection.In) }) }, new[] { new StateVariable ("A_ARG_stringArg", "string"), new StateVariable ("A_ARG_intArg", "i4"), new StateVariable ("A_ARG_byteArg", "ui1"), new StateVariable ("A_ARG_ushortArg", "ui2"), new StateVariable ("A_ARG_uintArg", "ui4"), new StateVariable ("A_ARG_sbyteArg", "i1"), new StateVariable ("A_ARG_shortArg", "i2"), new StateVariable ("A_ARG_longArg", "int"), new StateVariable ("A_ARG_floatArg", "r4"), new StateVariable ("A_ARG_doubleArg", "r8"), new StateVariable ("A_ARG_charArg", "char"), new StateVariable ("A_ARG_dateTimeArg", "date"), new StateVariable ("A_ARG_boolArg", "boolean"), new StateVariable ("A_ARG_byteArrayArg", "bin"), new StateVariable ("A_ARG_uriArg", "uri") } ); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } class StateVariableTestClass { [UpnpStateVariable] public event EventHandler<StateVariableChangedArgs<string>> FooChanged; } [Test] public void StateVariableTest () { var service = new DummyService<StateVariableTestClass> (); var controller = new ServiceController (null, new[] { new DummyStateVariable ("FooChanged", "string") } ); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } class StateVariableNameTestClass { [UpnpStateVariable ("fooChanged")] public event EventHandler<StateVariableChangedArgs<string>> FooChanged; } [Test] public void StateVariableNameTest () { var service = new DummyService<StateVariableNameTestClass> (); var controller = new ServiceController (null, new[] { new DummyStateVariable ("fooChanged", "string") } ); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } class StateVariableDataTypeTestClass { [UpnpStateVariable (DataType = "string.foo")] public event EventHandler<StateVariableChangedArgs<string>> FooChanged; } [Test] public void StateVariableDataTypeTest () { var service = new DummyService<StateVariableDataTypeTestClass> (); var controller = new ServiceController (null, new[] { new DummyStateVariable ("FooChanged", "string.foo") } ); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } class StateVariableIsMulticastTestClass { [UpnpStateVariable (IsMulticast = true)] public event EventHandler<StateVariableChangedArgs<string>> FooChanged; } [Test] public void StateVariableIsMulticastTest () { var service = new DummyService<StateVariableIsMulticastTestClass> (); var controller = new ServiceController (null, new[] { new DummyStateVariable ("FooChanged", "string", true) } ); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } class StateVariablesTestClass { [UpnpStateVariable] public event EventHandler<StateVariableChangedArgs<string>> StringChanged; [UpnpStateVariable] public event EventHandler<StateVariableChangedArgs<int>> IntChanged; [UpnpStateVariable] public event EventHandler<StateVariableChangedArgs<byte>> ByteChanged; [UpnpStateVariable] public event EventHandler<StateVariableChangedArgs<ushort>> UshortChanged; [UpnpStateVariable] public event EventHandler<StateVariableChangedArgs<uint>> UintChanged; [UpnpStateVariable] public event EventHandler<StateVariableChangedArgs<sbyte>> SbyteChanged; [UpnpStateVariable] public event EventHandler<StateVariableChangedArgs<short>> ShortChanged; [UpnpStateVariable] public event EventHandler<StateVariableChangedArgs<long>> LongChanged; [UpnpStateVariable] public event EventHandler<StateVariableChangedArgs<float>> FloatChanged; [UpnpStateVariable] public event EventHandler<StateVariableChangedArgs<double>> DoubleChanged; [UpnpStateVariable] public event EventHandler<StateVariableChangedArgs<char>> CharChanged; [UpnpStateVariable] public event EventHandler<StateVariableChangedArgs<bool>> BoolChanged; [UpnpStateVariable] public event EventHandler<StateVariableChangedArgs<byte[]>> ByteArrayChanged; [UpnpStateVariable] public event EventHandler<StateVariableChangedArgs<Uri>> UriChanged; } [Test] public void StateVariablesTest () { var service = new DummyService<StateVariablesTestClass> (); var controller = new ServiceController (null, new[] { new DummyStateVariable ("StringChanged", "string"), new DummyStateVariable ("IntChanged", "i4"), new DummyStateVariable ("ByteChanged", "ui1"), new DummyStateVariable ("UshortChanged", "ui2"), new DummyStateVariable ("UintChanged", "ui4"), new DummyStateVariable ("SbyteChanged", "i1"), new DummyStateVariable ("ShortChanged", "i2"), new DummyStateVariable ("LongChanged", "int"), new DummyStateVariable ("FloatChanged", "r4"), new DummyStateVariable ("DoubleChanged", "r8"), new DummyStateVariable ("CharChanged", "char"), new DummyStateVariable ("BoolChanged", "boolean"), new DummyStateVariable ("ByteArrayChanged", "bin"), new DummyStateVariable ("UriChanged", "uri") } ); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } class EventedRelatedStateVariableTestClass { [UpnpAction] public void GetFoo ([UpnpRelatedStateVariable ("Foo")] out string foo) { foo = null; } [UpnpStateVariable ("Foo")] public event EventHandler<StateVariableChangedArgs<string>> FooChanged; } [Test] public void EventedRelatedStateVariableTest () { var service = new DummyService<EventedRelatedStateVariableTestClass> (); var controller = new ServiceController ( new[] { new DummyServiceAction ("GetFoo", new[] { new Argument ("foo", "Foo", ArgumentDirection.Out) }) }, new[] { new DummyStateVariable ("Foo", "string") } ); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } class OptionalActionClass { [UpnpAction (OmitUnless = "CanFoo")] public void Foo (string foo) { } [UpnpAction] public void Bar (string bar) { } public bool CanFoo { get; set; } } [Test] public void UnimplementedOptionalAction () { var service = new DummyService<OptionalActionClass> (); var controller = new ServiceController ( new[] { new DummyServiceAction ("Bar", new [] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) }) }, new[] { new StateVariable ("A_ARG_bar", "string") }); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } [Test] public void ImplementedOptionalAction () { var service = new DummyService<OptionalActionClass> (new OptionalActionClass { CanFoo = true }); var controller = new ServiceController ( new[] { new DummyServiceAction ("Foo", new [] { new Argument ("foo", "A_ARG_foo", ArgumentDirection.In) }), new DummyServiceAction ("Bar", new [] { new Argument ("bar", "A_ARG_bar", ArgumentDirection.In) }) }, new[] { new StateVariable ("A_ARG_foo", "string"), new StateVariable ("A_ARG_bar", "string") }); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } class ErroneousOptionalActionClass { [UpnpAction (OmitUnless = "CanFoo")] public void Foo () { } } [Test, ExpectedException (typeof (UpnpServiceDefinitionException))] public void ErroneousOptionalAction () { new DummyService<ErroneousOptionalActionClass> (); } class OptionalStateVariablesClass { [UpnpStateVariable (OmitUnless = "HasFoo")] public event EventHandler<StateVariableChangedArgs<string>> FooChanged; [UpnpStateVariable] public event EventHandler<StateVariableChangedArgs<string>> BarChanged; public bool HasFoo { get; set; } } [Test] public void UnimplementedOptionalStateVariable () { var service = new DummyService<OptionalStateVariablesClass> (); var controller = new ServiceController (null, new[] { new DummyStateVariable ("BarChanged", "string") }); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } [Test] public void ImplementedOptionalStateVariable () { var service = new DummyService<OptionalStateVariablesClass> (new OptionalStateVariablesClass { HasFoo = true }); var controller = new ServiceController (null, new[] { new DummyStateVariable ("FooChanged", "string"), new DummyStateVariable ("BarChanged", "string") }); ServiceDescriptionTests.AssertEquality (controller, service.GetController ()); } class ErroneousOptionalStateVariablesClass { [UpnpStateVariable (OmitUnless = "HasFoo")] public event EventHandler<StateVariableChangedArgs<string>> FooChanged; } [Test, ExpectedException (typeof (UpnpServiceDefinitionException))] public void ErroneousOptionalStateVariable () { new DummyService<ErroneousOptionalStateVariablesClass> (); } class ErroneousArgumentTypeClass { [UpnpAction] public void Foo (Exception e) { } } [Test, ExpectedException (typeof (UpnpServiceDefinitionException))] public void ErroneousArgumentType () { new DummyService<ErroneousArgumentTypeClass> (); } } }
// 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 Xunit; namespace System.Linq.Expressions.Tests { public class Break : GotoExpressionTests { [Theory] [PerCompilationType(nameof(ConstantValueData))] public void JustBreakValue(object value, bool useInterpreter) { Type type = value.GetType(); LabelTarget target = Expression.Label(type); Expression block = Expression.Block( Expression.Break(target, Expression.Constant(value)), Expression.Label(target, Expression.Default(type)) ); Expression equals = Expression.Equal(Expression.Constant(value), block); Assert.True(Expression.Lambda<Func<bool>>(equals).Compile(useInterpreter)()); } [Theory] [ClassData(typeof(CompilationTypes))] public void BreakToMiddle(bool useInterpreter) { // The behaviour is that return jumps to a label, but does not necessarily leave a block. LabelTarget target = Expression.Label(typeof(int)); Expression block = Expression.Block( Expression.Break(target, Expression.Constant(1)), Expression.Label(target, Expression.Constant(2)), Expression.Constant(3) ); Assert.Equal(3, Expression.Lambda<Func<int>>(block).Compile(useInterpreter)()); } [Theory] [PerCompilationType(nameof(ConstantValueData))] public void BreakJumps(object value, bool useInterpreter) { Type type = value.GetType(); LabelTarget target = Expression.Label(type); Expression block = Expression.Block( Expression.Break(target, Expression.Constant(value)), Expression.Throw(Expression.Constant(new InvalidOperationException())), Expression.Label(target, Expression.Default(type)) ); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(value), block)).Compile(useInterpreter)()); } [Theory] [MemberData(nameof(TypesData))] public void NonVoidTargetBreakHasNoValue(Type type) { LabelTarget target = Expression.Label(type); AssertExtensions.Throws<ArgumentException>("target", () => Expression.Break(target)); } [Theory] [MemberData(nameof(TypesData))] public void NonVoidTargetBreakHasNoValueTypeExplicit(Type type) { LabelTarget target = Expression.Label(type); AssertExtensions.Throws<ArgumentException>("target", () => Expression.Break(target, type)); } [Theory] [ClassData(typeof(CompilationTypes))] public void BreakVoidNoValue(bool useInterpreter) { LabelTarget target = Expression.Label(); Expression block = Expression.Block( Expression.Break(target), Expression.Throw(Expression.Constant(new InvalidOperationException())), Expression.Label(target) ); Expression.Lambda<Action>(block).Compile(useInterpreter)(); } [Theory] [ClassData(typeof(CompilationTypes))] public void BreakExplicitVoidNoValue(bool useInterpreter) { LabelTarget target = Expression.Label(); Expression block = Expression.Block( Expression.Break(target, typeof(void)), Expression.Throw(Expression.Constant(new InvalidOperationException())), Expression.Label(target) ); Expression.Lambda<Action>(block).Compile(useInterpreter)(); } [Theory] [MemberData(nameof(TypesData))] public void NullValueOnNonVoidBreak(Type type) { AssertExtensions.Throws<ArgumentException>("target", () => Expression.Break(Expression.Label(type))); AssertExtensions.Throws<ArgumentException>("target", () => Expression.Break(Expression.Label(type), default(Expression))); AssertExtensions.Throws<ArgumentException>("target", () => Expression.Break(Expression.Label(type), null, type)); } [Theory] [MemberData(nameof(ConstantValueData))] public void ExplicitNullTypeWithValue(object value) { AssertExtensions.Throws<ArgumentException>("target", () => Expression.Break(Expression.Label(value.GetType()), default(Type))); } [Fact] public void UnreadableLabel() { Expression value = Expression.Property(null, typeof(Unreadable<string>), "WriteOnly"); LabelTarget target = Expression.Label(typeof(string)); AssertExtensions.Throws<ArgumentException>("value", () => Expression.Break(target, value)); AssertExtensions.Throws<ArgumentException>("value", () => Expression.Break(target, value, typeof(string))); } [Theory] [PerCompilationType(nameof(ConstantValueData))] public void CanAssignAnythingToVoid(object value, bool useInterpreter) { LabelTarget target = Expression.Label(); BlockExpression block = Expression.Block( Expression.Break(target, Expression.Constant(value)), Expression.Label(target) ); Assert.Equal(typeof(void), block.Type); Expression.Lambda<Action>(block).Compile(useInterpreter)(); } [Theory] [MemberData(nameof(NonObjectAssignableConstantValueData))] public void CannotAssignValueTypesToObject(object value) { AssertExtensions.Throws<ArgumentException>(null, () => Expression.Break(Expression.Label(typeof(object)), Expression.Constant(value))); } [Theory] [PerCompilationType(nameof(ObjectAssignableConstantValueData))] public void ExplicitTypeAssigned(object value, bool useInterpreter) { LabelTarget target = Expression.Label(typeof(object)); BlockExpression block = Expression.Block( Expression.Break(target, Expression.Constant(value), typeof(object)), Expression.Label(target, Expression.Default(typeof(object))) ); Assert.Equal(typeof(object), block.Type); Assert.Equal(value, Expression.Lambda<Func<object>>(block).Compile(useInterpreter)()); } [Fact] public void BreakQuotesIfNecessary() { LabelTarget target = Expression.Label(typeof(Expression<Func<int>>)); BlockExpression block = Expression.Block( Expression.Break(target, Expression.Lambda<Func<int>>(Expression.Constant(0))), Expression.Label(target, Expression.Default(typeof(Expression<Func<int>>))) ); Assert.Equal(typeof(Expression<Func<int>>), block.Type); } [Fact] public void UpdateSameIsSame() { LabelTarget target = Expression.Label(typeof(int)); Expression value = Expression.Constant(0); GotoExpression ret = Expression.Break(target, value); Assert.Same(ret, ret.Update(target, value)); Assert.Same(ret, NoOpVisitor.Instance.Visit(ret)); } [Fact] public void UpdateDiferentValueIsDifferent() { LabelTarget target = Expression.Label(typeof(int)); GotoExpression ret = Expression.Break(target, Expression.Constant(0)); Assert.NotSame(ret, ret.Update(target, Expression.Constant(0))); } [Fact] public void UpdateDifferentTargetIsDifferent() { Expression value = Expression.Constant(0); GotoExpression ret = Expression.Break(Expression.Label(typeof(int)), value); Assert.NotSame(ret, ret.Update(Expression.Label(typeof(int)), value)); } [Fact] public void OpenGenericType() { AssertExtensions.Throws<ArgumentException>("type", () => Expression.Break(Expression.Label(typeof(void)), typeof(List<>))); } [Fact] public static void TypeContainsGenericParameters() { AssertExtensions.Throws<ArgumentException>("type", () => Expression.Break(Expression.Label(typeof(void)), typeof(List<>.Enumerator))); AssertExtensions.Throws<ArgumentException>("type", () => Expression.Break(Expression.Label(typeof(void)), typeof(List<>).MakeGenericType(typeof(List<>)))); } [Fact] public void PointerType() { AssertExtensions.Throws<ArgumentException>("type", () => Expression.Break(Expression.Label(typeof(void)), typeof(int).MakePointerType())); } [Fact] public void ByRefType() { AssertExtensions.Throws<ArgumentException>("type", () => Expression.Break(Expression.Label(typeof(void)), typeof(int).MakeByRefType())); } [Theory, ClassData(typeof(CompilationTypes))] public void UndefinedLabel(bool useInterpreter) { Expression<Action> breakNowhere = Expression.Lambda<Action>(Expression.Break(Expression.Label())); Assert.Throws<InvalidOperationException>(() => breakNowhere.Compile(useInterpreter)); } [Theory, ClassData(typeof(CompilationTypes))] public void AmbiguousJump(bool useInterpreter) { LabelTarget target = Expression.Label(); Expression<Action> exp = Expression.Lambda<Action>( Expression.Block( Expression.Break(target), Expression.Block(Expression.Label(target)), Expression.Block(Expression.Label(target)) ) ); Assert.Throws<InvalidOperationException>(() => exp.Compile(useInterpreter)); } [Theory, ClassData(typeof(CompilationTypes))] public void MultipleDefinitionsInSeparateBlocks(bool useInterpreter) { LabelTarget target = Expression.Label(typeof(int)); Func<int> add = Expression.Lambda<Func<int>>( Expression.Add( Expression.Add( Expression.Block( Expression.Break(target, Expression.Constant(6)), Expression.Throw(Expression.Constant(new Exception())), Expression.Label(target, Expression.Constant(0)) ), Expression.Block( Expression.Break(target, Expression.Constant(4)), Expression.Throw(Expression.Constant(new Exception())), Expression.Label(target, Expression.Constant(0)) ) ), Expression.Block( Expression.Break(target, Expression.Constant(5)), Expression.Throw(Expression.Constant(new Exception())), Expression.Label(target, Expression.Constant(0)) ) ) ).Compile(useInterpreter); Assert.Equal(15, add()); } [Theory, ClassData(typeof(CompilationTypes))] public void JumpIntoExpression(bool useInterpreter) { LabelTarget target = Expression.Label(); Expression<Func<bool>> isInt = Expression.Lambda<Func<bool>>( Expression.Block( Expression.Break(target), Expression.TypeIs(Expression.Label(target), typeof(int)) ) ); Assert.Throws<InvalidOperationException>(() => isInt.Compile(useInterpreter)); } [Theory, ClassData(typeof(CompilationTypes))] public void JumpInWithValue(bool useInterpreter) { LabelTarget target = Expression.Label(typeof(int)); Expression<Func<int>> exp = Expression.Lambda<Func<int>>( Expression.Block( Expression.Break(target, Expression.Constant(2)), Expression.Block( Expression.Label(target, Expression.Constant(3))) ) ); Assert.Throws<InvalidOperationException>(() => exp.Compile(useInterpreter)); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/longrunning/operations.proto // Original file comments: // Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using grpc = global::Grpc.Core; namespace Google.LongRunning { /// <summary> /// Manages long-running operations with an API service. /// /// When an API method normally takes long time to complete, it can be designed /// to return [Operation][google.longrunning.Operation] to the client, and the client can use this /// interface to receive the real response asynchronously by polling the /// operation resource, or pass the operation resource to another API (such as /// Google Cloud Pub/Sub API) to receive the response. Any API service that /// returns long-running operations should implement the `Operations` interface /// so developers can have a consistent client experience. /// </summary> public static partial class Operations { static readonly string __ServiceName = "google.longrunning.Operations"; static readonly grpc::Marshaller<global::Google.LongRunning.ListOperationsRequest> __Marshaller_ListOperationsRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.LongRunning.ListOperationsRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.LongRunning.ListOperationsResponse> __Marshaller_ListOperationsResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.LongRunning.ListOperationsResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.LongRunning.GetOperationRequest> __Marshaller_GetOperationRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.LongRunning.GetOperationRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.LongRunning.Operation> __Marshaller_Operation = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.LongRunning.Operation.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.LongRunning.DeleteOperationRequest> __Marshaller_DeleteOperationRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.LongRunning.DeleteOperationRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.LongRunning.CancelOperationRequest> __Marshaller_CancelOperationRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.LongRunning.CancelOperationRequest.Parser.ParseFrom); static readonly grpc::Method<global::Google.LongRunning.ListOperationsRequest, global::Google.LongRunning.ListOperationsResponse> __Method_ListOperations = new grpc::Method<global::Google.LongRunning.ListOperationsRequest, global::Google.LongRunning.ListOperationsResponse>( grpc::MethodType.Unary, __ServiceName, "ListOperations", __Marshaller_ListOperationsRequest, __Marshaller_ListOperationsResponse); static readonly grpc::Method<global::Google.LongRunning.GetOperationRequest, global::Google.LongRunning.Operation> __Method_GetOperation = new grpc::Method<global::Google.LongRunning.GetOperationRequest, global::Google.LongRunning.Operation>( grpc::MethodType.Unary, __ServiceName, "GetOperation", __Marshaller_GetOperationRequest, __Marshaller_Operation); static readonly grpc::Method<global::Google.LongRunning.DeleteOperationRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_DeleteOperation = new grpc::Method<global::Google.LongRunning.DeleteOperationRequest, global::Google.Protobuf.WellKnownTypes.Empty>( grpc::MethodType.Unary, __ServiceName, "DeleteOperation", __Marshaller_DeleteOperationRequest, __Marshaller_Empty); static readonly grpc::Method<global::Google.LongRunning.CancelOperationRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_CancelOperation = new grpc::Method<global::Google.LongRunning.CancelOperationRequest, global::Google.Protobuf.WellKnownTypes.Empty>( grpc::MethodType.Unary, __ServiceName, "CancelOperation", __Marshaller_CancelOperationRequest, __Marshaller_Empty); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Google.LongRunning.OperationsReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of Operations</summary> public abstract partial class OperationsBase { /// <summary> /// Lists operations that match the specified filter in the request. If the /// server doesn't support this method, it returns `UNIMPLEMENTED`. /// /// NOTE: the `name` binding below allows API services to override the binding /// to use different resource name schemes, such as `users/*/operations`. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.LongRunning.ListOperationsResponse> ListOperations(global::Google.LongRunning.ListOperationsRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Gets the latest state of a long-running operation. Clients can use this /// method to poll the operation result at intervals as recommended by the API /// service. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.LongRunning.Operation> GetOperation(global::Google.LongRunning.GetOperationRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Deletes a long-running operation. This method indicates that the client is /// no longer interested in the operation result. It does not cancel the /// operation. If the server doesn't support this method, it returns /// `google.rpc.Code.UNIMPLEMENTED`. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> DeleteOperation(global::Google.LongRunning.DeleteOperationRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Starts asynchronous cancellation on a long-running operation. The server /// makes a best effort to cancel the operation, but success is not /// guaranteed. If the server doesn't support this method, it returns /// `google.rpc.Code.UNIMPLEMENTED`. Clients can use /// [Operations.GetOperation][google.longrunning.Operations.GetOperation] or /// other methods to check whether the cancellation succeeded or whether the /// operation completed despite cancellation. On successful cancellation, /// the operation is not deleted; instead, it becomes an operation with /// an [Operation.error][google.longrunning.Operation.error] value with a [google.rpc.Status.code][google.rpc.Status.code] of 1, /// corresponding to `Code.CANCELLED`. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> CancelOperation(global::Google.LongRunning.CancelOperationRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } } /// <summary>Client for Operations</summary> public partial class OperationsClient : grpc::ClientBase<OperationsClient> { /// <summary>Creates a new client for Operations</summary> /// <param name="channel">The channel to use to make remote calls.</param> public OperationsClient(grpc::Channel channel) : base(channel) { } /// <summary>Creates a new client for Operations that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public OperationsClient(grpc::CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected OperationsClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected OperationsClient(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// Lists operations that match the specified filter in the request. If the /// server doesn't support this method, it returns `UNIMPLEMENTED`. /// /// NOTE: the `name` binding below allows API services to override the binding /// to use different resource name schemes, such as `users/*/operations`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.LongRunning.ListOperationsResponse ListOperations(global::Google.LongRunning.ListOperationsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListOperations(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists operations that match the specified filter in the request. If the /// server doesn't support this method, it returns `UNIMPLEMENTED`. /// /// NOTE: the `name` binding below allows API services to override the binding /// to use different resource name schemes, such as `users/*/operations`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.LongRunning.ListOperationsResponse ListOperations(global::Google.LongRunning.ListOperationsRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListOperations, null, options, request); } /// <summary> /// Lists operations that match the specified filter in the request. If the /// server doesn't support this method, it returns `UNIMPLEMENTED`. /// /// NOTE: the `name` binding below allows API services to override the binding /// to use different resource name schemes, such as `users/*/operations`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.LongRunning.ListOperationsResponse> ListOperationsAsync(global::Google.LongRunning.ListOperationsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListOperationsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists operations that match the specified filter in the request. If the /// server doesn't support this method, it returns `UNIMPLEMENTED`. /// /// NOTE: the `name` binding below allows API services to override the binding /// to use different resource name schemes, such as `users/*/operations`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.LongRunning.ListOperationsResponse> ListOperationsAsync(global::Google.LongRunning.ListOperationsRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListOperations, null, options, request); } /// <summary> /// Gets the latest state of a long-running operation. Clients can use this /// method to poll the operation result at intervals as recommended by the API /// service. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.LongRunning.Operation GetOperation(global::Google.LongRunning.GetOperationRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetOperation(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets the latest state of a long-running operation. Clients can use this /// method to poll the operation result at intervals as recommended by the API /// service. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.LongRunning.Operation GetOperation(global::Google.LongRunning.GetOperationRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetOperation, null, options, request); } /// <summary> /// Gets the latest state of a long-running operation. Clients can use this /// method to poll the operation result at intervals as recommended by the API /// service. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.LongRunning.Operation> GetOperationAsync(global::Google.LongRunning.GetOperationRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetOperationAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets the latest state of a long-running operation. Clients can use this /// method to poll the operation result at intervals as recommended by the API /// service. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.LongRunning.Operation> GetOperationAsync(global::Google.LongRunning.GetOperationRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetOperation, null, options, request); } /// <summary> /// Deletes a long-running operation. This method indicates that the client is /// no longer interested in the operation result. It does not cancel the /// operation. If the server doesn't support this method, it returns /// `google.rpc.Code.UNIMPLEMENTED`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteOperation(global::Google.LongRunning.DeleteOperationRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteOperation(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes a long-running operation. This method indicates that the client is /// no longer interested in the operation result. It does not cancel the /// operation. If the server doesn't support this method, it returns /// `google.rpc.Code.UNIMPLEMENTED`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteOperation(global::Google.LongRunning.DeleteOperationRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_DeleteOperation, null, options, request); } /// <summary> /// Deletes a long-running operation. This method indicates that the client is /// no longer interested in the operation result. It does not cancel the /// operation. If the server doesn't support this method, it returns /// `google.rpc.Code.UNIMPLEMENTED`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteOperationAsync(global::Google.LongRunning.DeleteOperationRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteOperationAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes a long-running operation. This method indicates that the client is /// no longer interested in the operation result. It does not cancel the /// operation. If the server doesn't support this method, it returns /// `google.rpc.Code.UNIMPLEMENTED`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteOperationAsync(global::Google.LongRunning.DeleteOperationRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_DeleteOperation, null, options, request); } /// <summary> /// Starts asynchronous cancellation on a long-running operation. The server /// makes a best effort to cancel the operation, but success is not /// guaranteed. If the server doesn't support this method, it returns /// `google.rpc.Code.UNIMPLEMENTED`. Clients can use /// [Operations.GetOperation][google.longrunning.Operations.GetOperation] or /// other methods to check whether the cancellation succeeded or whether the /// operation completed despite cancellation. On successful cancellation, /// the operation is not deleted; instead, it becomes an operation with /// an [Operation.error][google.longrunning.Operation.error] value with a [google.rpc.Status.code][google.rpc.Status.code] of 1, /// corresponding to `Code.CANCELLED`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty CancelOperation(global::Google.LongRunning.CancelOperationRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CancelOperation(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Starts asynchronous cancellation on a long-running operation. The server /// makes a best effort to cancel the operation, but success is not /// guaranteed. If the server doesn't support this method, it returns /// `google.rpc.Code.UNIMPLEMENTED`. Clients can use /// [Operations.GetOperation][google.longrunning.Operations.GetOperation] or /// other methods to check whether the cancellation succeeded or whether the /// operation completed despite cancellation. On successful cancellation, /// the operation is not deleted; instead, it becomes an operation with /// an [Operation.error][google.longrunning.Operation.error] value with a [google.rpc.Status.code][google.rpc.Status.code] of 1, /// corresponding to `Code.CANCELLED`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty CancelOperation(global::Google.LongRunning.CancelOperationRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CancelOperation, null, options, request); } /// <summary> /// Starts asynchronous cancellation on a long-running operation. The server /// makes a best effort to cancel the operation, but success is not /// guaranteed. If the server doesn't support this method, it returns /// `google.rpc.Code.UNIMPLEMENTED`. Clients can use /// [Operations.GetOperation][google.longrunning.Operations.GetOperation] or /// other methods to check whether the cancellation succeeded or whether the /// operation completed despite cancellation. On successful cancellation, /// the operation is not deleted; instead, it becomes an operation with /// an [Operation.error][google.longrunning.Operation.error] value with a [google.rpc.Status.code][google.rpc.Status.code] of 1, /// corresponding to `Code.CANCELLED`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> CancelOperationAsync(global::Google.LongRunning.CancelOperationRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CancelOperationAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Starts asynchronous cancellation on a long-running operation. The server /// makes a best effort to cancel the operation, but success is not /// guaranteed. If the server doesn't support this method, it returns /// `google.rpc.Code.UNIMPLEMENTED`. Clients can use /// [Operations.GetOperation][google.longrunning.Operations.GetOperation] or /// other methods to check whether the cancellation succeeded or whether the /// operation completed despite cancellation. On successful cancellation, /// the operation is not deleted; instead, it becomes an operation with /// an [Operation.error][google.longrunning.Operation.error] value with a [google.rpc.Status.code][google.rpc.Status.code] of 1, /// corresponding to `Code.CANCELLED`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> CancelOperationAsync(global::Google.LongRunning.CancelOperationRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CancelOperation, null, options, request); } /// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary> protected override OperationsClient NewInstance(ClientBaseConfiguration configuration) { return new OperationsClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static grpc::ServerServiceDefinition BindService(OperationsBase serviceImpl) { return grpc::ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_ListOperations, serviceImpl.ListOperations) .AddMethod(__Method_GetOperation, serviceImpl.GetOperation) .AddMethod(__Method_DeleteOperation, serviceImpl.DeleteOperation) .AddMethod(__Method_CancelOperation, serviceImpl.CancelOperation).Build(); } } } #endregion
using System; using System.Collections.Generic; using Orchard.ContentManagement.Records; namespace Orchard.ContentManagement { /// <summary> /// Reprensents dynamically created query on Content Items. /// </summary> public interface IHqlQuery { /// <summary> /// The underlying <see cref="ContentManager"/> instance used to execute the query. /// </summary> IContentManager ContentManager { get; } /// <summary> /// Add content type constraints to the query. /// </summary> IHqlQuery ForType(params string[] contentTypes); /// <summary> /// Eagerly fetches specific content parts. /// </summary> IHqlQuery Include(params string[] contentPartRecords); /// <summary> /// Adds versioning options to the query. /// </summary> IHqlQuery ForVersion(VersionOptions options); /// <summary> /// Defines the resulting type. /// </summary> /// <returns>An <see cref="IHqlQuery&lt;T&gt;"/></returns> IHqlQuery<T> ForPart<T>() where T : IContent; /// <summary> /// Executes the query and returns all results. /// </summary> IEnumerable<ContentItem> List(); /// <summary> /// Executes the query and returns all ids for matching content items. /// </summary> IEnumerable<int> ListIds(); /// <summary> /// Returns a subset of the matching content items. /// </summary> IEnumerable<ContentItem> Slice(int skip, int count); /// <summary> /// Returns the number of matching content items. /// </summary> int Count(); /// <summary> /// Adds a join to a the query. /// </summary> /// <param name="alias">An expression pointing to the joined relationship.</param> IHqlQuery Join(Action<IAliasFactory> alias); /// <summary> /// Adds a where constraint to the query. /// </summary> /// <param name="alias">An expression pointing to the joined relationship.</param> /// <param name="predicate">A predicate expression.</param> IHqlQuery Where(Action<IAliasFactory> alias, Action<IHqlExpressionFactory> predicate); /// <summary> /// Adds a join to a specific relationship. /// </summary> /// <param name="alias">An expression pointing to the joined relationship.</param> /// <param name="order">An order expression.</param> IHqlQuery OrderBy(Action<IAliasFactory> alias, Action<IHqlSortFactory> order); } /// <summary> /// Reprensents dynamically created query on Content Items, having a specific Content Part. /// </summary> public interface IHqlQuery<TPart> where TPart : IContent { /// <summary> /// Add content type constraints to the query. /// </summary> IHqlQuery<TPart> ForType(params string[] contentTypes); /// <summary> /// Adds versioning options to the query. /// </summary> IHqlQuery<TPart> ForVersion(VersionOptions options); /// <summary> /// Executes the query and returns all results. /// </summary> IEnumerable<TPart> List(); /// <summary> /// Returns a subset of the matching content items. /// </summary> IEnumerable<TPart> Slice(int skip, int count); /// <summary> /// Returns the number of matching content items. /// </summary> int Count(); /// <summary> /// Adds a join to a the query. /// </summary> /// <param name="alias">An expression pointing to the joined relationship.</param> IHqlQuery<TPart> Join(Action<IAliasFactory> alias); /// <summary> /// Adds a where constraint to the query. /// </summary> /// <param name="alias">An expression pointing to the joined relationship.</param> /// <param name="predicate">A predicate expression.</param> IHqlQuery<TPart> Where(Action<IAliasFactory> alias, Action<IHqlExpressionFactory> predicate); /// <summary> /// Adds a join to a specific relationship. /// </summary> /// <param name="alias">An expression pointing to the joined relationship.</param> /// <param name="order">An order expression.</param> IHqlQuery<TPart> OrderBy(Action<IAliasFactory> alias, Action<IHqlSortFactory> order); } public interface IAlias { /// <summary> /// The name of the alias. /// </summary> string Name { get; } } public interface IAliasFactory { /// <summary> /// Creates a join on a content part record or returns it if it already exists. /// <param name="type">The type of join, e.g. "left outer join"</param> /// <param name="withPredicate">An expression for an additional constraint on the join</param> /// </summary> IAliasFactory ContentPartRecord<TRecord>(string type = null, Action<IHqlExpressionFactory> withPredicate = null) where TRecord : ContentPartRecord; /// <summary> /// Creates a join on a content part record or returns it if it already exists. /// <param name="contentPartRecord">The type of the part to join</param> /// <param name="type">The type of join, e.g. "left outer join"</param> /// <param name="withPredicate">An expression for an additional constraint on the join</param> /// </summary> IAliasFactory ContentPartRecord(Type contentPartRecord, string type = null, Action<IHqlExpressionFactory> withPredicate = null); /// <summary> /// Creates a join based on a property, or returns it if it already exists. /// </summary> IAliasFactory Property(string propertyName, string alias); /// <summary> /// Returns an existing alias by its name. /// </summary> IAliasFactory Named(string alias); /// <summary> /// Returns an the <see cref="ContentItemRecord"/> alias. /// </summary> IAliasFactory ContentItem(); /// <summary> /// Returns an the <see cref="ContentItemVersionRecord"/> alias. /// </summary> IAliasFactory ContentItemVersion(); /// <summary> /// Returns an the <see cref="ContentTypeRecord"/> alias. /// </summary> IAliasFactory ContentType(); } public interface IHqlSortFactory { /// <summary> /// Sorts by ascending order /// </summary> void Asc(string propertyName); /// <summary> /// Sorts by descending order /// </summary> void Desc(string propertyName); /// <summary> /// Sorts randomly /// </summary> void Random(); /// <summary> /// Sort in ascending order, adding custom HQL strings /// to the SELECT and ORDER BY statements /// </summary> /// <param name="propertyName">Name of the property</param> /// <param name="additionalSelectOps">Additional HQL for the SELECT statement</param> /// <param name="additionalOrderOps">Additional HQL for the ORDER BY statement</param> /// <remarks>ORDER BY items must appear in the select list if SELECT DISTINCT is specified. /// If such query is being generated by the implementation (as is the case for DefaultHqlQuery), /// make sure to respect that constraint when generating the addtionalOrderOps and /// additionalSelectOps parameters.</remarks> void Asc(string propertyName, string additionalSelectOps, string additionalOrderOps); /// <summary> /// Sort in descending order, adding custom HQL strings /// to the SELECT and ORDER BY statements /// </summary> /// <param name="propertyName">Name of the property</param> /// <param name="additionalSelectOps">Additional HQL for the SELECT statement</param> /// <param name="additionalOrderOps">Additional HQL for the ORDER BY statement</param> /// <remarks>ORDER BY items must appear in the select list if SELECT DISTINCT is specified. /// If such query is being generated by the implementation (as is the case for DefaultHqlQuery), /// make sure to respect that constraint when generating the addtionalOrderOps and /// additionalSelectOps parameters.</remarks> void Desc(string propertyName, string additionalSelectOps, string additionalOrderOps); } }
/// <summary> /// UnityTutorials - A Unity Game Design Prototyping Sandbox /// <copyright>(c) John McElmurray and Julian Adams 2013</copyright> /// /// UnityTutorials homepage: https://github.com/jm991/UnityTutorials /// /// This software is provided 'as-is', without any express or implied /// warranty. In no event will the authors be held liable for any damages /// arising from the use of this software. /// /// Permission is granted to anyone to use this software for any purpose, /// and to alter it and redistribute it freely, subject to the following restrictions: /// /// 1. The origin of this software must not be misrepresented; you must not /// claim that you wrote the original software. If you use this software /// in a product, an acknowledgment in the product documentation would be /// appreciated but is not required. /// 2. Altered source versions must be plainly marked as such, and must not be /// misrepresented as being the original software. /// 3. This notice may not be removed or altered from any source distribution. /// </summary> using UnityEngine; using System.Collections; /// <summary> /// #DESCRIPTION OF CLASS# /// </summary> public class CharacterControllerLogic : MonoBehaviour { #region Variables (private) // Inspector serialized [SerializeField] private Animator animator; [SerializeField] private ThirdPersonCamera gamecam; [SerializeField] private float rotationDegreePerSecond = 120f; [SerializeField] private float directionSpeed = 1.5f; [SerializeField] private float directionDampTime = 0.25f; [SerializeField] private float speedDampTime = 0.05f; [SerializeField] private float fovDampTime = 3f; [SerializeField] private float jumpMultiplier = 1f; [SerializeField] private CapsuleCollider capCollider; [SerializeField] private float jumpDist = 1f; // Private global only private float leftX = 0f; private float leftY = 0f; private AnimatorStateInfo stateInfo; private AnimatorTransitionInfo transInfo; private float speed = 0f; private float direction = 0f; private float charAngle = 0f; private const float SPRINT_SPEED = 2.0f; private const float SPRINT_FOV = 75.0f; private const float NORMAL_FOV = 60.0f; private float capsuleHeight; // Hashes private int m_LocomotionId = 0; private int m_LocomotionPivotLId = 0; private int m_LocomotionPivotRId = 0; private int m_LocomotionPivotLTransId = 0; private int m_LocomotionPivotRTransId = 0; #endregion #region Properties (public) public Animator Animator { get { return this.animator; } } public float Speed { get { return this.speed; } } public float LocomotionThreshold { get { return 0.2f; } } #endregion #region Unity event functions /// <summary> /// Use this for initialization. /// </summary> void Start() { animator = GetComponent<Animator>(); capCollider = GetComponent<CapsuleCollider>(); capsuleHeight = capCollider.height; if(animator.layerCount >= 2) { animator.SetLayerWeight(1, 1); } // Hash all animation names for performance m_LocomotionId = Animator.StringToHash("Base Layer.Locomotion"); m_LocomotionPivotLId = Animator.StringToHash("Base Layer.LocomotionPivotL"); m_LocomotionPivotRId = Animator.StringToHash("Base Layer.LocomotionPivotR"); m_LocomotionPivotLTransId = Animator.StringToHash("Base Layer.Locomotion -> Base Layer.LocomotionPivotL"); m_LocomotionPivotRTransId = Animator.StringToHash("Base Layer.Locomotion -> Base Layer.LocomotionPivotR"); } /// <summary> /// Update is called once per frame. /// </summary> void Update() { if (animator && gamecam.CamState != ThirdPersonCamera.CamStates.FirstPerson) { stateInfo = animator.GetCurrentAnimatorStateInfo(0); transInfo = animator.GetAnimatorTransitionInfo(0); // Press A to jump if (Input.GetButton("Jump")) { animator.SetBool("Jump", true); } else { animator.SetBool("Jump", false); } // Pull values from controller/keyboard leftX = Input.GetAxis("Horizontal"); leftY = Input.GetAxis("Vertical"); charAngle = 0f; direction = 0f; float charSpeed = 0f; // Translate controls stick coordinates into world/cam/character space StickToWorldspace(this.transform, gamecam.transform, ref direction, ref charSpeed, ref charAngle, IsInPivot()); // Press B to sprint if (Input.GetButton("Sprint")) { speed = Mathf.Lerp(speed, SPRINT_SPEED, Time.deltaTime); gamecam.camera.fieldOfView = Mathf.Lerp(gamecam.camera.fieldOfView, SPRINT_FOV, fovDampTime * Time.deltaTime); } else { speed = charSpeed; gamecam.camera.fieldOfView = Mathf.Lerp(gamecam.camera.fieldOfView, NORMAL_FOV, fovDampTime * Time.deltaTime); } animator.SetFloat("Speed", speed, speedDampTime, Time.deltaTime); animator.SetFloat("Direction", direction, directionDampTime, Time.deltaTime); if (speed > LocomotionThreshold) // Dead zone { if (!IsInPivot()) { Animator.SetFloat("Angle", charAngle); } } if (speed < LocomotionThreshold && Mathf.Abs(leftX) < 0.05f) // Dead zone { animator.SetFloat("Direction", 0f); animator.SetFloat("Angle", 0f); } } } /// <summary> /// Any code that moves the character needs to be checked against physics /// </summary> void FixedUpdate() { // Rotate character model if stick is tilted right or left, but only if character is moving in that direction if (IsInLocomotion() && gamecam.CamState != ThirdPersonCamera.CamStates.Free && !IsInPivot() && ((direction >= 0 && leftX >= 0) || (direction < 0 && leftX < 0))) { Vector3 rotationAmount = Vector3.Lerp(Vector3.zero, new Vector3(0f, rotationDegreePerSecond * (leftX < 0f ? -1f : 1f), 0f), Mathf.Abs(leftX)); Quaternion deltaRotation = Quaternion.Euler(rotationAmount * Time.deltaTime); this.transform.rotation = (this.transform.rotation * deltaRotation); } if (IsInJump()) { float oldY = transform.position.y; transform.Translate(Vector3.up * jumpMultiplier * animator.GetFloat("JumpCurve")); if (IsInLocomotionJump()) { transform.Translate(Vector3.forward * Time.deltaTime * jumpDist); } capCollider.height = capsuleHeight + (animator.GetFloat("CapsuleCurve") * 0.5f); if (gamecam.CamState != ThirdPersonCamera.CamStates.Free) { gamecam.ParentRig.Translate(Vector3.up * (transform.position.y - oldY)); } } } /// <summary> /// Debugging information should be put here. /// </summary> void OnDrawGizmos() { } #endregion #region Methods public bool IsInJump() { return (IsInIdleJump() || IsInLocomotionJump()); } public bool IsInIdleJump() { return animator.GetCurrentAnimatorStateInfo(0).IsName("Base Layer.IdleJump"); } public bool IsInLocomotionJump() { return animator.GetCurrentAnimatorStateInfo(0).IsName("Base Layer.LocomotionJump"); } public bool IsInPivot() { return stateInfo.nameHash == m_LocomotionPivotLId || stateInfo.nameHash == m_LocomotionPivotRId || transInfo.nameHash == m_LocomotionPivotLTransId || transInfo.nameHash == m_LocomotionPivotRTransId; } public bool IsInLocomotion() { return stateInfo.nameHash == m_LocomotionId; } public void StickToWorldspace(Transform root, Transform camera, ref float directionOut, ref float speedOut, ref float angleOut, bool isPivoting) { Vector3 rootDirection = root.forward; Vector3 stickDirection = new Vector3(leftX, 0, leftY); speedOut = stickDirection.sqrMagnitude; // Get camera rotation Vector3 CameraDirection = camera.forward; CameraDirection.y = 0.0f; // kill Y Quaternion referentialShift = Quaternion.FromToRotation(Vector3.forward, Vector3.Normalize(CameraDirection)); // Convert joystick input in Worldspace coordinates Vector3 moveDirection = referentialShift * stickDirection; Vector3 axisSign = Vector3.Cross(moveDirection, rootDirection); Debug.DrawRay(new Vector3(root.position.x, root.position.y + 2f, root.position.z), moveDirection, Color.green); Debug.DrawRay(new Vector3(root.position.x, root.position.y + 2f, root.position.z), rootDirection, Color.magenta); Debug.DrawRay(new Vector3(root.position.x, root.position.y + 2f, root.position.z), stickDirection, Color.blue); Debug.DrawRay(new Vector3(root.position.x, root.position.y + 2.5f, root.position.z), axisSign, Color.red); float angleRootToMove = Vector3.Angle(rootDirection, moveDirection) * (axisSign.y >= 0 ? -1f : 1f); if (!isPivoting) { angleOut = angleRootToMove; } angleRootToMove /= 180f; directionOut = angleRootToMove * directionSpeed; } #endregion Methods }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // In the desktop version of the framework, this file is generated from ProviderBase\DbParameterHelper.cs //#line 1 "e:\\fxdata\\src\\ndp\\fx\\src\\data\\system\\data\\providerbase\\dbparameterhelper.cs" using System.Data.Common; namespace System.Data.SqlClient { public sealed partial class SqlParameter : DbParameter { private object _value; private object _parent; private ParameterDirection _direction; private int _size; private int _offset; private string _sourceColumn; private object _coercedValue; private object CoercedValue { get => _coercedValue; set => _coercedValue = value; } override public ParameterDirection Direction { get { ParameterDirection direction = _direction; return ((0 != direction) ? direction : ParameterDirection.Input); } set { if (_direction != value) { switch (value) { case ParameterDirection.Input: case ParameterDirection.Output: case ParameterDirection.InputOutput: case ParameterDirection.ReturnValue: PropertyChanging(); _direction = value; break; default: throw ADP.InvalidParameterDirection(value); } } } } override public bool IsNullable { get => _flags.HasFlag(SqlParameterFlags.IsNullable); set => Set(SqlParameterFlags.IsNullable, value); } public int Offset { get { return _offset; } set { if (value < 0) { throw ADP.InvalidOffsetValue(value); } _offset = value; } } override public int Size { get { int size = _size; if (0 == size) { size = ValueSize(Value); } return size; } set { if (_size != value) { if (value < -1) { throw ADP.InvalidSizeValue(value); } PropertyChanging(); _size = value; } } } private bool ShouldSerializeSize() { return (0 != _size); } override public string SourceColumn { get => (_sourceColumn ?? ADP.StrEmpty); set => _sourceColumn = value; } public override bool SourceColumnNullMapping { get => _flags.HasFlag(SqlParameterFlags.SourceColumnNullMapping); set => Set(SqlParameterFlags.SourceColumnNullMapping, value); } internal object CompareExchangeParent(object value, object comparand) { object parent = _parent; if (comparand == parent) { _parent = value; } return parent; } internal void ResetParent() { _parent = null; } override public string ToString() { return ParameterName; } private byte ValuePrecisionCore(object value) { if (value is decimal) { return ((System.Data.SqlTypes.SqlDecimal)(Decimal)value).Precision; } return 0; } private byte ValueScaleCore(object value) { if (value is decimal) { return (byte)((decimal.GetBits((decimal)value)[3] & 0x00ff0000) >> 0x10); } return 0; } private int ValueSizeCore(object value) { if (!ADP.IsNull(value)) { string svalue = (value as string); if (null != svalue) { return svalue.Length; } byte[] bvalue = (value as byte[]); if (null != bvalue) { return bvalue.Length; } char[] cvalue = (value as char[]); if (null != cvalue) { return cvalue.Length; } if ((value is byte) || (value is char)) { return 1; } } return 0; } internal void CopyTo(SqlParameter destination) { ADP.CheckArgumentNull(destination, nameof(destination)); // NOTE: _parent is not cloned destination._value = _value; destination._direction = _direction; destination._size = _size; destination._offset = _offset; destination._sourceColumn = _sourceColumn; destination._sourceVersion = _sourceVersion; destination._parameterName = _parameterName; SqlParameterFlags setFlags = SqlParameterFlags.SourceColumnNullMapping | SqlParameterFlags.IsNullable | SqlParameterFlags.IsNull; destination._flags = (destination._flags & ~setFlags) | (_flags & setFlags); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Reflection; using Xunit; namespace System.Linq.Expressions.Tests { public class OpAssign { [Theory] [PerCompilationType(nameof(AssignAndEquivalentMethods))] public void AssignmentEquivalents(MethodInfo nonAssign, MethodInfo assign, Type type, bool useInterpreter) { Func<Expression, Expression, Expression> withoutAssignment = (Func<Expression, Expression, Expression>)nonAssign.CreateDelegate(typeof(Func<Expression, Expression, Expression>)); Func<Expression, Expression, Expression> withAssignment = (Func<Expression, Expression, Expression>)assign.CreateDelegate(typeof(Func<Expression, Expression, Expression>)); foreach (object x in new[] { 0, -1, 1, 10 }.Select(i => Convert.ChangeType(i, type))) foreach (object y in new[] { -1, 1, 10 }.Select(i => Convert.ChangeType(i, type))) { ConstantExpression xExp = Expression.Constant(x); ConstantExpression yExp = Expression.Constant(y); Expression woAssign = withoutAssignment(xExp, yExp); ParameterExpression variable = Expression.Variable(type); Expression initAssign = Expression.Assign(variable, xExp); Expression assignment = withAssignment(variable, yExp); Expression wAssign = Expression.Block( new ParameterExpression[] { variable }, initAssign, assignment ); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(woAssign, wAssign)).Compile(useInterpreter)()); LabelTarget target = Expression.Label(type); Expression wAssignReturningVariable = Expression.Block( new ParameterExpression[] { variable }, initAssign, assignment, Expression.Return(target, variable), Expression.Label(target, Expression.Default(type)) ); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(woAssign, wAssignReturningVariable)).Compile(useInterpreter)()); } } private class Box<T> { public static T StaticValue { get; set; } public T Value { get; set; } public T this[int index] { get { return Value; } set { Value = value; } } public Box(T value) { Value = value; } } [Theory] [PerCompilationType(nameof(AssignAndEquivalentMethods))] public void AssignmentEquivalentsWithMemberAccess(MethodInfo nonAssign, MethodInfo assign, Type type, bool useInterpreter) { Func<Expression, Expression, Expression> withoutAssignment = (Func<Expression, Expression, Expression>)nonAssign.CreateDelegate(typeof(Func<Expression, Expression, Expression>)); Func<Expression, Expression, Expression> withAssignment = (Func<Expression, Expression, Expression>)assign.CreateDelegate(typeof(Func<Expression, Expression, Expression>)); foreach (object x in new[] { 0, -1, 1, 10 }.Select(i => Convert.ChangeType(i, type))) foreach (object y in new[] { -1, 1, 10 }.Select(i => Convert.ChangeType(i, type))) { ConstantExpression xExp = Expression.Constant(x); ConstantExpression yExp = Expression.Constant(y); Expression woAssign = withoutAssignment(xExp, yExp); Type boxType = typeof(Box<>).MakeGenericType(type); object box = boxType.GetConstructor(new[] { type }).Invoke(new object[] { x }); Expression boxExp = Expression.Constant(box); Expression property = Expression.Property(boxExp, boxType.GetProperty("Value")); Expression assignment = withAssignment(property, yExp); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(woAssign, assignment)).Compile(useInterpreter)()); LabelTarget target = Expression.Label(type); box = boxType.GetConstructor(new[] { type }).Invoke(new object[] { x }); boxExp = Expression.Constant(box); property = Expression.Property(boxExp, boxType.GetProperty("Value")); assignment = withAssignment(property, yExp); Expression wAssignReturningVariable = Expression.Block( assignment, Expression.Return(target, property), Expression.Label(target, Expression.Default(type)) ); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(woAssign, wAssignReturningVariable)).Compile(useInterpreter)()); } } [Theory, PerCompilationType(nameof(AssignAndEquivalentMethods))] public void AssignmentEquivalentsWithStaticMemberAccess(MethodInfo nonAssign, MethodInfo assign, Type type, bool useInterpreter) { Func<Expression, Expression, Expression> withoutAssignment = (Func<Expression, Expression, Expression>)nonAssign.CreateDelegate(typeof(Func<Expression, Expression, Expression>)); Func<Expression, Expression, Expression> withAssignment = (Func<Expression, Expression, Expression>)assign.CreateDelegate(typeof(Func<Expression, Expression, Expression>)); foreach (object x in new[] { 0, -1, 1, 10 }.Select(i => Convert.ChangeType(i, type))) foreach (object y in new[] { -1, 1, 10 }.Select(i => Convert.ChangeType(i, type))) { ConstantExpression xExp = Expression.Constant(x); ConstantExpression yExp = Expression.Constant(y); Expression woAssign = withoutAssignment(xExp, yExp); Type boxType = typeof(Box<>).MakeGenericType(type); var prop = boxType.GetProperty("StaticValue"); prop.SetValue(null, x); Expression property = Expression.Property(null, prop); Expression assignment = withAssignment(property, yExp); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(woAssign, assignment)).Compile(useInterpreter)()); prop.SetValue(null, x); Expression wAssignReturningVariable = Expression.Block( assignment, property ); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(woAssign, wAssignReturningVariable)).Compile(useInterpreter)()); } } [Theory] [PerCompilationType(nameof(AssignAndEquivalentMethods))] public void AssignmentEquivalentsWithIndexAccess(MethodInfo nonAssign, MethodInfo assign, Type type, bool useInterpreter) { Func<Expression, Expression, Expression> withoutAssignment = (Func<Expression, Expression, Expression>)nonAssign.CreateDelegate(typeof(Func<Expression, Expression, Expression>)); Func<Expression, Expression, Expression> withAssignment = (Func<Expression, Expression, Expression>)assign.CreateDelegate(typeof(Func<Expression, Expression, Expression>)); foreach (object x in new[] { 0, -1, 1, 10 }.Select(i => Convert.ChangeType(i, type))) foreach (object y in new[] { -1, 1, 10 }.Select(i => Convert.ChangeType(i, type))) { ConstantExpression xExp = Expression.Constant(x); ConstantExpression yExp = Expression.Constant(y); Expression woAssign = withoutAssignment(xExp, yExp); Type boxType = typeof(Box<>).MakeGenericType(type); object box = boxType.GetConstructor(new[] { type }).Invoke(new object[] { x }); Expression boxExp = Expression.Constant(box); Expression property = Expression.Property(boxExp, boxType.GetProperty("Item"), Expression.Constant(0)); Expression assignment = withAssignment(property, yExp); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(woAssign, assignment)).Compile(useInterpreter)()); LabelTarget target = Expression.Label(type); box = boxType.GetConstructor(new[] { type }).Invoke(new object[] { x }); boxExp = Expression.Constant(box); property = Expression.Property(boxExp, boxType.GetProperty("Item"), Expression.Constant(0)); assignment = withAssignment(property, yExp); Expression wAssignReturningVariable = Expression.Block( assignment, Expression.Return(target, property), Expression.Label(target, Expression.Default(type)) ); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(woAssign, wAssignReturningVariable)).Compile(useInterpreter)()); } } [Theory] [MemberData(nameof(AssignmentMethods))] public void AssignmentReducable(MethodInfo assign, Type type) { Func<Expression, Expression, Expression> withAssignment = (Func<Expression, Expression, Expression>)assign.CreateDelegate(typeof(Func<Expression, Expression, Expression>)); ParameterExpression variable = Expression.Variable(type); Expression assignment = withAssignment(variable, Expression.Default(type)); Assert.True(assignment.CanReduce); Assert.NotSame(assignment, assignment.ReduceAndCheck()); } [Theory] [MemberData(nameof(AssignmentMethods))] public void CannotAssignToNonWritable(MethodInfo assign, Type type) { Func<Expression, Expression, Expression> withAssignment = (Func<Expression, Expression, Expression>)assign.CreateDelegate(typeof(Func<Expression, Expression, Expression>)); Assert.Throws<ArgumentException>("left", () => withAssignment(Expression.Default(type), Expression.Default(type))); } [Theory] [MemberData(nameof(AssignmentMethods))] public void AssignmentWithMemberAccessReducable(MethodInfo assign, Type type) { Func<Expression, Expression, Expression> withAssignment = (Func<Expression, Expression, Expression>)assign.CreateDelegate(typeof(Func<Expression, Expression, Expression>)); Type boxType = typeof(Box<>).MakeGenericType(type); object box = boxType.GetConstructor(new[] { type }).Invoke(new object[] { Convert.ChangeType(0, type) }); Expression boxExp = Expression.Constant(box); Expression property = Expression.Property(boxExp, boxType.GetProperty("Value")); Expression assignment = withAssignment(property, Expression.Default(type)); Assert.True(assignment.CanReduce); Assert.NotSame(assignment, assignment.ReduceAndCheck()); } [Theory] [MemberData(nameof(AssignmentMethods))] public void AssignmentWithIndexAccessReducable(MethodInfo assign, Type type) { Func<Expression, Expression, Expression> withAssignment = (Func<Expression, Expression, Expression>)assign.CreateDelegate(typeof(Func<Expression, Expression, Expression>)); Type boxType = typeof(Box<>).MakeGenericType(type); object box = boxType.GetConstructor(new[] { type }).Invoke(new object[] { Convert.ChangeType(0, type) }); Expression boxExp = Expression.Constant(box); Expression property = Expression.Property(boxExp, boxType.GetProperty("Item"), Expression.Constant(0)); Expression assignment = withAssignment(property, Expression.Default(type)); Assert.True(assignment.CanReduce); Assert.NotSame(assignment, assignment.ReduceAndCheck()); } private static class Unreadable<T> { public static T WriteOnly { set { } } } [Theory] [MemberData(nameof(AssignmentMethods))] public static void ThrowsOnLeftUnreadable(MethodInfo assign, Type type) { Func<Expression, Expression, Expression> withAssignment = (Func<Expression, Expression, Expression>)assign.CreateDelegate(typeof(Func<Expression, Expression, Expression>)); Type unreadableType = typeof(Unreadable<>).MakeGenericType(type); Expression property = Expression.Property(null, unreadableType.GetProperty("WriteOnly")); Assert.Throws<ArgumentException>("left", () => withAssignment(property, Expression.Default(type))); } [Theory] [MemberData(nameof(AssignmentMethods))] public static void ThrowsOnRightUnreadable(MethodInfo assign, Type type) { Func<Expression, Expression, Expression> withAssignment = (Func<Expression, Expression, Expression>)assign.CreateDelegate(typeof(Func<Expression, Expression, Expression>)); Type unreadableType = typeof(Unreadable<>).MakeGenericType(type); Expression property = Expression.Property(null, unreadableType.GetProperty("WriteOnly")); Expression variable = Expression.Variable(type); Assert.Throws<ArgumentException>("right", () => withAssignment(variable, property)); } [Theory] [MemberData(nameof(AssignmentMethodsWithoutTypes))] public void ThrowIfNoSuchBinaryOperation(MethodInfo assign) { Func<Expression, Expression, Expression> withAssignment = (Func<Expression, Expression, Expression>)assign.CreateDelegate(typeof(Func<Expression, Expression, Expression>)); ParameterExpression variable = Expression.Variable(typeof(string)); Expression value = Expression.Default(typeof(string)); Assert.Throws<InvalidOperationException>(() => withAssignment(variable, value)); } private static IEnumerable<object[]> AssignmentMethods() { MethodInfo[] expressionMethods = typeof(Expression).GetMethods().Where(mi => mi.GetParameters().Length == 2).ToArray(); foreach (Tuple<string, string> names in AssignAndEquivalentMethodNames(true)) yield return new object[] { expressionMethods.First(mi => mi.Name == names.Item2), typeof(int) }; foreach (Tuple<string, string> names in AssignAndEquivalentMethodNames(false)) yield return new object[] { expressionMethods.First(mi => mi.Name == names.Item2), typeof(double) }; } private static IEnumerable<object[]> AssignmentMethodsWithoutTypes() { MethodInfo[] expressionMethods = typeof(Expression).GetMethods().Where(mi => mi.GetParameters().Length == 2).ToArray(); return AssignAndEquivalentMethodNames(true).Concat(AssignAndEquivalentMethodNames(false)) .Select(i => i.Item2) .Distinct() .Select(i => new object[] { expressionMethods.First(mi => mi.Name == i) }); } private static IEnumerable<object[]> AssignAndEquivalentMethods() { MethodInfo[] expressionMethods = typeof(Expression).GetMethods().Where(mi => mi.GetParameters().Length == 2).ToArray(); foreach (Tuple<string, string> names in AssignAndEquivalentMethodNames(true)) yield return new object[] { expressionMethods.First(mi => mi.Name == names.Item1), expressionMethods.First(mi => mi.Name == names.Item2), typeof(int) }; foreach (Tuple<string, string> names in AssignAndEquivalentMethodNames(false)) yield return new object[] { expressionMethods.First(mi => mi.Name == names.Item1), expressionMethods.First(mi => mi.Name == names.Item2), typeof(double) }; } private static IEnumerable<Tuple<string, string>> AssignAndEquivalentMethodNames(bool integral) { yield return Tuple.Create("Add", "AddAssign"); yield return Tuple.Create("AddChecked", "AddAssignChecked"); yield return Tuple.Create("Divide", "DivideAssign"); yield return Tuple.Create("Modulo", "ModuloAssign"); yield return Tuple.Create("Multiply", "MultiplyAssign"); yield return Tuple.Create("MultiplyChecked", "MultiplyAssignChecked"); yield return Tuple.Create("Subtract", "SubtractAssign"); yield return Tuple.Create("SubtractChecked", "SubtractAssignChecked"); if (integral) { yield return Tuple.Create("And", "AndAssign"); yield return Tuple.Create("ExclusiveOr", "ExclusiveOrAssign"); yield return Tuple.Create("LeftShift", "LeftShiftAssign"); yield return Tuple.Create("Or", "OrAssign"); yield return Tuple.Create("RightShift", "RightShiftAssign"); } else yield return Tuple.Create("Power", "PowerAssign"); } } }
using System; using Csla; using SelfLoad.DataAccess; using SelfLoad.DataAccess.ERLevel; namespace SelfLoad.Business.ERLevel { /// <summary> /// C04_SubContinent (editable child object).<br/> /// This is a generated base class of <see cref="C04_SubContinent"/> business object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="C05_CountryObjects"/> of type <see cref="C05_CountryColl"/> (1:M relation to <see cref="C06_Country"/>)<br/> /// This class is an item of <see cref="C03_SubContinentColl"/> collection. /// </remarks> [Serializable] public partial class C04_SubContinent : BusinessBase<C04_SubContinent> { #region Static Fields private static int _lastID; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="SubContinent_ID"/> property. /// </summary> public static readonly PropertyInfo<int> SubContinent_IDProperty = RegisterProperty<int>(p => p.SubContinent_ID, "SubContinents ID"); /// <summary> /// Gets the SubContinents ID. /// </summary> /// <value>The SubContinents ID.</value> public int SubContinent_ID { get { return GetProperty(SubContinent_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="SubContinent_Name"/> property. /// </summary> public static readonly PropertyInfo<string> SubContinent_NameProperty = RegisterProperty<string>(p => p.SubContinent_Name, "SubContinents Name"); /// <summary> /// Gets or sets the SubContinents Name. /// </summary> /// <value>The SubContinents Name.</value> public string SubContinent_Name { get { return GetProperty(SubContinent_NameProperty); } set { SetProperty(SubContinent_NameProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="C05_SubContinent_SingleObject"/> property. /// </summary> public static readonly PropertyInfo<C05_SubContinent_Child> C05_SubContinent_SingleObjectProperty = RegisterProperty<C05_SubContinent_Child>(p => p.C05_SubContinent_SingleObject, "C05 SubContinent Single Object", RelationshipTypes.Child); /// <summary> /// Gets the C05 Sub Continent Single Object ("self load" child property). /// </summary> /// <value>The C05 Sub Continent Single Object.</value> public C05_SubContinent_Child C05_SubContinent_SingleObject { get { return GetProperty(C05_SubContinent_SingleObjectProperty); } private set { LoadProperty(C05_SubContinent_SingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="C05_SubContinent_ASingleObject"/> property. /// </summary> public static readonly PropertyInfo<C05_SubContinent_ReChild> C05_SubContinent_ASingleObjectProperty = RegisterProperty<C05_SubContinent_ReChild>(p => p.C05_SubContinent_ASingleObject, "C05 SubContinent ASingle Object", RelationshipTypes.Child); /// <summary> /// Gets the C05 Sub Continent ASingle Object ("self load" child property). /// </summary> /// <value>The C05 Sub Continent ASingle Object.</value> public C05_SubContinent_ReChild C05_SubContinent_ASingleObject { get { return GetProperty(C05_SubContinent_ASingleObjectProperty); } private set { LoadProperty(C05_SubContinent_ASingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="C05_CountryObjects"/> property. /// </summary> public static readonly PropertyInfo<C05_CountryColl> C05_CountryObjectsProperty = RegisterProperty<C05_CountryColl>(p => p.C05_CountryObjects, "C05 Country Objects", RelationshipTypes.Child); /// <summary> /// Gets the C05 Country Objects ("self load" child property). /// </summary> /// <value>The C05 Country Objects.</value> public C05_CountryColl C05_CountryObjects { get { return GetProperty(C05_CountryObjectsProperty); } private set { LoadProperty(C05_CountryObjectsProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="C04_SubContinent"/> object. /// </summary> /// <returns>A reference to the created <see cref="C04_SubContinent"/> object.</returns> internal static C04_SubContinent NewC04_SubContinent() { return DataPortal.CreateChild<C04_SubContinent>(); } /// <summary> /// Factory method. Loads a <see cref="C04_SubContinent"/> object from the given C04_SubContinentDto. /// </summary> /// <param name="data">The <see cref="C04_SubContinentDto"/>.</param> /// <returns>A reference to the fetched <see cref="C04_SubContinent"/> object.</returns> internal static C04_SubContinent GetC04_SubContinent(C04_SubContinentDto data) { C04_SubContinent obj = new C04_SubContinent(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(data); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="C04_SubContinent"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public C04_SubContinent() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="C04_SubContinent"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { LoadProperty(SubContinent_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID)); LoadProperty(C05_SubContinent_SingleObjectProperty, DataPortal.CreateChild<C05_SubContinent_Child>()); LoadProperty(C05_SubContinent_ASingleObjectProperty, DataPortal.CreateChild<C05_SubContinent_ReChild>()); LoadProperty(C05_CountryObjectsProperty, DataPortal.CreateChild<C05_CountryColl>()); var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="C04_SubContinent"/> object from the given <see cref="C04_SubContinentDto"/>. /// </summary> /// <param name="data">The C04_SubContinentDto to use.</param> private void Fetch(C04_SubContinentDto data) { // Value properties LoadProperty(SubContinent_IDProperty, data.SubContinent_ID); LoadProperty(SubContinent_NameProperty, data.SubContinent_Name); var args = new DataPortalHookArgs(data); OnFetchRead(args); } /// <summary> /// Loads child objects. /// </summary> internal void FetchChildren() { LoadProperty(C05_SubContinent_SingleObjectProperty, C05_SubContinent_Child.GetC05_SubContinent_Child(SubContinent_ID)); LoadProperty(C05_SubContinent_ASingleObjectProperty, C05_SubContinent_ReChild.GetC05_SubContinent_ReChild(SubContinent_ID)); LoadProperty(C05_CountryObjectsProperty, C05_CountryColl.GetC05_CountryColl(SubContinent_ID)); } /// <summary> /// Inserts a new <see cref="C04_SubContinent"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(C02_Continent parent) { var dto = new C04_SubContinentDto(); dto.Parent_Continent_ID = parent.Continent_ID; dto.SubContinent_Name = SubContinent_Name; using (var dalManager = DalFactorySelfLoad.GetManager()) { var args = new DataPortalHookArgs(dto); OnInsertPre(args); var dal = dalManager.GetProvider<IC04_SubContinentDal>(); using (BypassPropertyChecks) { var resultDto = dal.Insert(dto); LoadProperty(SubContinent_IDProperty, resultDto.SubContinent_ID); args = new DataPortalHookArgs(resultDto); } OnInsertPost(args); // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Updates in the database all changes made to the <see cref="C04_SubContinent"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update() { if (!IsDirty) return; var dto = new C04_SubContinentDto(); dto.SubContinent_ID = SubContinent_ID; dto.SubContinent_Name = SubContinent_Name; using (var dalManager = DalFactorySelfLoad.GetManager()) { var args = new DataPortalHookArgs(dto); OnUpdatePre(args); var dal = dalManager.GetProvider<IC04_SubContinentDal>(); using (BypassPropertyChecks) { var resultDto = dal.Update(dto); args = new DataPortalHookArgs(resultDto); } OnUpdatePost(args); // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Self deletes the <see cref="C04_SubContinent"/> object from database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf() { using (var dalManager = DalFactorySelfLoad.GetManager()) { var args = new DataPortalHookArgs(); // flushes all pending data operations FieldManager.UpdateChildren(this); OnDeletePre(args); var dal = dalManager.GetProvider<IC04_SubContinentDal>(); using (BypassPropertyChecks) { dal.Delete(ReadProperty(SubContinent_IDProperty)); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
using UnityEngine; using System.Collections.Generic; public enum MegaIntegrator { Euler, Verlet, VerletTimeCorrected, MidPoint, } public class BaryVert2D { public int gx; // Grid position public int gy; public Vector2 bary; } [System.Serializable] public class Constraint2D { public bool active; public int p1; public int p2; public float length; public Vector2 pos; public int contype = 0; public Transform obj; public static Constraint2D CreatePointTargetCon(int _p1, Transform trans) { Constraint2D con = new Constraint2D(); con.p1 = _p1; con.active = true; con.contype = 2; con.obj = trans; return con; } public static Constraint2D CreateLenCon(int _p1, int _p2, float _len) { Constraint2D con = new Constraint2D(); con.p1 = _p1; con.p2 = _p2; con.length = _len; con.active = true; con.contype = 0; return con; } public static Constraint2D CreatePointCon(int _p1, Vector2 _pos) { Constraint2D con = new Constraint2D(); con.p1 = _p1; con.pos = _pos; con.active = true; con.contype = 1; return con; } public void Apply(MegaSoft2D soft) { switch ( contype ) { case 0: ApplyLengthConstraint2D(soft); break; case 1: ApplyPointConstraint2D(soft); break; //case 2: ApplyPointTargetConstraint2D(soft); break; } } // Can have a one that has a range to keep in public void ApplyLengthConstraint2D(MegaSoft2D soft) { if ( active && soft.applyConstraints ) { //calculate direction Vector2 direction = soft.masses[p2].pos - soft.masses[p1].pos; //calculate current length float currentLength = direction.magnitude; //check for zero vector if ( currentLength != 0.0f ) //direction.x != 0.0f || direction.y != 0.0f || direction.y != 0.0f ) { direction.x /= currentLength; direction.y /= currentLength; //move to goal positions Vector2 moveVector = 0.5f * (currentLength - length) * direction; soft.masses[p1].pos.x += moveVector.x; soft.masses[p1].pos.y += moveVector.y; soft.masses[p2].pos.x += -moveVector.x; soft.masses[p2].pos.y += -moveVector.y; } } } public void ApplyPointConstraint2D(MegaSoft2D soft) { if ( active ) soft.masses[p1].pos = pos; } public void ApplyAngleConstraint(MegaSoft2D soft) { } } [System.Serializable] public class Mass2D { public Vector2 pos; public Vector2 last; public Vector2 force; public Vector2 vel; public Vector2 posc; public Vector2 velc; public Vector2 forcec; public Vector2 coef1; public Vector2 coef2; public float mass; public float oneovermass; public Mass2D(float m, Vector2 p) { mass = m; oneovermass = 1.0f / mass; pos = p; last = p; force = Vector2.zero; vel = Vector2.zero; } } [System.Serializable] public class Spring2D { public int p1; public int p2; public float restLen; public float ks; public float kd; public float len; public Spring2D(int _p1, int _p2, float _ks, float _kd, MegaSoft2D mod) { p1 = _p1; p2 = _p2; ks = _ks; kd = _kd; restLen = Vector2.Distance(mod.masses[p1].pos, mod.masses[p2].pos); len = restLen; } public void doCalculateSpringForce(MegaSoft2D mod) { Vector2 deltaP = mod.masses[p1].pos - mod.masses[p2].pos; float dist = deltaP.magnitude; //VectorLength(&deltaP); // Magnitude of deltaP float Hterm = (dist - restLen) * ks; // Ks * (dist - rest) Vector2 deltaV = mod.masses[p1].vel - mod.masses[p2].vel; float Dterm = (Vector2.Dot(deltaV, deltaP) * kd) / dist; // Damping Term Vector2 springForce = deltaP * (1.0f / dist); springForce *= -(Hterm + Dterm); mod.masses[p1].force += springForce; mod.masses[p2].force -= springForce; } public void doCalculateSpringForce1(MegaSoft2D mod) { //get the direction vector Vector2 direction = mod.masses[p1].pos - mod.masses[p2].pos; //check for zero vector if ( direction != Vector2.zero ) { //get length float currLength = direction.magnitude; //normalize direction = direction.normalized; //add spring force Vector2 force = -ks * ((currLength - restLen) * direction); //add spring damping force //float v = (currLength - len) / mod.timeStep; //force += -kd * v * direction; //apply the equal and opposite forces to the objects mod.masses[p1].force += force; mod.masses[p2].force -= force; len = currLength; } } public void doCalculateSpringForce2(MegaSoft2D mod) { Vector2 deltaP = mod.masses[p1].pos - mod.masses[p2].pos; float dist = deltaP.magnitude; //VectorLength(&deltaP); // Magnitude of deltaP float Hterm = (dist - restLen) * ks; // Ks * (dist - rest) //Vector2 deltaV = mod.masses[p1].vel - mod.masses[p2].vel; float v = (dist - len); // / mod.timeStep; float Dterm = (v * kd) / dist; // Damping Term Vector2 springForce = deltaP * (1.0f / dist); springForce *= -(Hterm + Dterm); mod.masses[p1].force += springForce; mod.masses[p2].force -= springForce; } } // Want verlet for this as no collision will be done, solver type enum // need to add contact forces for weights on bridge [System.Serializable] public class MegaSoft2D { public List<Mass2D> masses = new List<Mass2D>(); public List<Spring2D> springs = new List<Spring2D>(); public List<Constraint2D> constraints = new List<Constraint2D>(); public Vector2 gravity = new Vector2(0.0f, -9.81f); public float airdrag = 0.999f; public float friction = 1.0f; public float timeStep = 0.01f; public int iters = 4; public MegaIntegrator method = MegaIntegrator.Verlet; public bool applyConstraints = true; void doCalculateForceseuler() { for ( int i = 0; i < masses.Count; i++ ) { masses[i].force = masses[i].mass * gravity; masses[i].force += masses[i].forcec; } for ( int i = 0; i < springs.Count; i++ ) springs[i].doCalculateSpringForce(this); } void doCalculateForces() { for ( int i = 0; i < masses.Count; i++ ) { masses[i].force = masses[i].mass * gravity; masses[i].force += masses[i].forcec; } for ( int i = 0; i < springs.Count; i++ ) springs[i].doCalculateSpringForce1(this); } void doIntegration1(float dt) { doCalculateForceseuler(); // Calculate forces, only changes _f /* Then do correction step by integration with central average (Heun) */ for ( int i = 0; i < masses.Count; i++ ) { masses[i].last = masses[i].pos; masses[i].vel += dt * masses[i].force * masses[i].oneovermass; masses[i].pos += masses[i].vel * dt; masses[i].vel *= friction; } DoConstraints(); } public float floor = 0.0f; void DoCollisions(float dt) { for ( int i = 0; i < masses.Count; i++ ) { if ( masses[i].pos.y < floor ) masses[i].pos.y = floor; } } // Change the base code over to Skeel or similar //public bool UseVerlet = false; // Can do drag per point using a curve // perform the verlet integration step void VerletIntegrate(float t, float lastt) { doCalculateForces(); // Calculate forces, only changes _f float t2 = t * t; /* Then do correction step by integration with central average (Heun) */ for ( int i = 0; i < masses.Count; i++ ) { Vector2 last = masses[i].pos; masses[i].pos += airdrag * (masses[i].pos - masses[i].last) + masses[i].force * masses[i].oneovermass * t2; // * t; masses[i].last = last; } DoConstraints(); } // Pointless void VerletIntegrateTC(float t, float lastt) { doCalculateForces(); // Calculate forces, only changes _f float t2 = t * t; float dt = t / lastt; /* Then do correction step by integration with central average (Heun) */ for ( int i = 0; i < masses.Count; i++ ) { Vector2 last = masses[i].pos; masses[i].pos += airdrag * (masses[i].pos - masses[i].last) * dt + (masses[i].force * masses[i].oneovermass) * t2; // * t; masses[i].last = last; } DoConstraints(); } void MidPointIntegrate(float t) { } // Satisfy constraints public void DoConstraints() { for ( int i = 0; i < iters; i++ ) { for ( int c = 0; c < constraints.Count; c++ ) { constraints[c].Apply(this); } } } public float lasttime = 0.0f; public float simtime = 0.0f; public void Update() { if ( masses == null ) return; if ( Application.isPlaying ) simtime += Time.deltaTime; // * fudge; if ( Time.deltaTime == 0.0f ) { simtime = 0.01f; } if ( timeStep <= 0.0f ) timeStep = 0.001f; float ts = 0.0f; if ( lasttime == 0.0f ) lasttime = timeStep; while ( simtime > 0.0f) //timeStep ) //0.0f ) { simtime -= timeStep; ts = timeStep; switch ( method ) { case MegaIntegrator.Euler: doIntegration1(ts); break; case MegaIntegrator.Verlet: VerletIntegrate(ts, lasttime); //timeStep); break; case MegaIntegrator.VerletTimeCorrected: VerletIntegrateTC(ts, lasttime); //timeStep); break; case MegaIntegrator.MidPoint: MidPointIntegrate(ts); //timeStep); break; } lasttime = ts; } } }
#region Apache License Version 2.0 /*---------------------------------------------------------------- Copyright 2017 Yang Chen ([email protected]) 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. Detail: https://github.com/etechi/ServiceFramework/blob/master/license.md ----------------------------------------------------------------*/ #endregion Apache License Version 2.0 using System; using Xunit; using System.Linq; using System.Collections.Generic; using System.Reflection; using System.Linq.Expressions; using SF.Sys.Services; using SF.Sys.Services.Storages; namespace SF.UT.DI { public class FeatureTest { interface IInterface<T> { string ToString(T obj); } interface IInterface2<T> { string ToString(T obj); } class Implement<T> : IInterface<T>, IInterface2<T> { public string ToString(T obj) { return obj.ToString(); } } class ImplementWithArg<T> : IInterface<T>, IInterface2<T> { string Prefix { get; } public ImplementWithArg(string Prefix) { this.Prefix = Prefix??"null"; } public string ToString(T obj) { return Prefix+obj.ToString(); } } [Fact] public void Generic() { var sc = new ServiceCollection(); sc.AddMicrosoftMemoryCacheAsLocalCache(); sc.UseMemoryManagedServiceSource(); sc.AddTransient(typeof(IInterface<>), typeof(Implement<>)); var sp = sc.BuildServiceResolver(); var re = sp.Resolve<IInterface<int>>(); Assert.Equal("123", re.ToString(123)); } public interface IMultipleImplTest { string Text(); } public class MultipleImplTestGlobal : IMultipleImplTest { public string Text() { return "Global Text"; } } public class MultipleImplTestScope : IMultipleImplTest { int idx = 0; public string Text() { return "Scope Text "+(idx++); } } [Fact] public void ScopeWithMultipleImplements() { var sc = new ServiceCollection(); sc.AddScoped<IMultipleImplTest,MultipleImplTestScope>(); //sc.AddSingleton<IMultipleImplTest,MultipleImplTestGlobal>(); sc.AddMicrosoftMemoryCacheAsLocalCache(); sc.UseMemoryManagedServiceSource(); var sp = sc.BuildServiceResolver(); var re = sp.Resolve<IMultipleImplTest>(); Assert.Equal("Scope Text 0", re.Text()); sp.WithScope((isp) => { var re1 = isp.Resolve<IMultipleImplTest>(); Assert.Equal("Scope Text 0", re1.Text()); }); Assert.Equal("Scope Text 1", re.Text()); sp.WithScope((isp) => { var re1 = isp.Resolve<IMultipleImplTest>(); Assert.Equal("Scope Text 0", re1.Text()); }); Assert.Equal("Scope Text 2", re.Text()); } [Fact] public void ByFunc() { var sc = new ServiceCollection(); sc.AddTransient<IInterface<int>, Implement<int>>(); sc.AddMicrosoftMemoryCacheAsLocalCache(); sc.UseMemoryManagedServiceSource(); var sp = sc.BuildServiceResolver(); var re = sp.Resolve<Func<IInterface<int>>>(); var r = re(); Assert.Equal("123", r.ToString(123)); } [Fact] public void ByFuncWithId() { var sc = new ServiceCollection(); sc.AddTransient<IInterface<int>, Implement<int>>(); sc.AddManagedService(); sc.AddMicrosoftMemoryCacheAsLocalCache(); sc.UseMemoryManagedServiceSource(); sc.AddNewtonsoftJson(); var sp = sc.BuildServiceResolver(); var cfgs = sp.Resolve<MemoryServiceSource>(); cfgs.SetConfig<IInterface<int>, Implement<int>>(1,new { }); var re = sp.Resolve<TypedInstanceResolver<IInterface<int>>>(); var r = re(1); Assert.Equal("123", r.ToString(123)); } [Fact] public void ByLazy() { var sc = new ServiceCollection(); sc.AddTransient<IInterface<int>, Implement<int>>(); sc.AddMicrosoftMemoryCacheAsLocalCache(); sc.UseMemoryManagedServiceSource(); var sp = sc.BuildServiceResolver(); var re = sp.Resolve<Lazy<IInterface<int>>>(); var r = re.Value; Assert.Equal("123", r.ToString(123)); } [Fact] public void UnmanagedEnumerable() { var sc = new ServiceCollection(); sc.AddTransient<IInterface<int>, Implement<int>>(); sc.AddTransient<IInterface<int>>((s)=>new Implement<int>()); sc.AddMicrosoftMemoryCacheAsLocalCache(); sc.UseMemoryManagedServiceSource(); var sp = sc.BuildServiceResolver(); var re = sp.Resolve<IEnumerable<IInterface<int>>>(); Assert.Equal(2,re.Count()); foreach (var i in re) Assert.Equal("123", i.ToString(123)); } [Fact] public void ManagedEnumerable() { var sc = new ServiceCollection(); sc.AddTransient<IInterface<int>, Implement<int>>(); sc.AddManagedService(); sc.AddMicrosoftMemoryCacheAsLocalCache(); sc.UseMemoryManagedServiceSource(); sc.AddNewtonsoftJson(); var sp = sc.BuildServiceResolver(); var cfgs = sp.Resolve<MemoryServiceSource>(); cfgs.SetConfig<IInterface<int>, Implement<int>>(1, new { },3); cfgs.SetConfig<IInterface<int>, Implement<int>>(2, new { },2,1); cfgs.SetConfig<IInterface<int>, Implement<int>>(3, new { },1,1); var re = sp.GetServices<IInterface<int>>(1); Assert.Equal(2, re.Count()); foreach (var i in re) Assert.Equal("123", i.ToString(123)); } [Fact] public void ManagedNamedEnumerable() { var sc = new ServiceCollection(); sc.AddTransient<IInterface<int>, Implement<int>>(); sc.AddManagedService(); sc.AddMicrosoftMemoryCacheAsLocalCache(); sc.UseMemoryManagedServiceSource(); sc.AddNewtonsoftJson(); var sp = sc.BuildServiceResolver(); var cfgs = sp.Resolve<MemoryServiceSource>(); cfgs.SetConfig<IInterface<int>, Implement<int>>(1, new { }, 3); cfgs.SetConfig<IInterface<int>, Implement<int>>(2, new { }, 2, 1,"svc1"); cfgs.SetConfig<IInterface<int>, Implement<int>>(3, new { }, 1, 1,"svc2"); cfgs.SetConfig<IInterface<int>, Implement<int>>(4, new { }, 0, 1, "svc2"); var re = sp.GetServices<IInterface<int>>(1); Assert.Equal(3, re.Count()); foreach (var i in re) Assert.Equal("123", i.ToString(123)); re = sp.GetServices<IInterface<int>>(1,"svc2"); Assert.Equal(2, re.Count()); foreach (var i in re) Assert.Equal("123", i.ToString(123)); } [Fact] public void ManagedNamedService() { var sc = new ServiceCollection(); sc.AddTransient<IInterface<int>, Implement<int>>(); sc.AddTransient<IInterface<int>, ImplementWithArg<int>>(); sc.AddManagedService(); sc.AddMicrosoftMemoryCacheAsLocalCache(); sc.UseMemoryManagedServiceSource(); sc.AddNewtonsoftJson(); var sp = sc.BuildServiceResolver(); var cfgs = sp.Resolve<MemoryServiceSource>(); cfgs.SetConfig<IInterface<int>, Implement<int>>(1, new { }, 3); cfgs.SetConfig<IInterface<int>, Implement<int>>(2, new { }, 2, 1, "svc1"); cfgs.SetConfig<IInterface<int>, Implement<int>>(3, new { }, 1, 1, "svc2"); cfgs.SetConfig<IInterface<int>, ImplementWithArg<int>>(4, new {Prefix="svc4" }, 0, 1, "svc2"); var re = sp.ResolveInternal<IInterface<int>>(1,"svc2"); Assert.Equal("svc4123", re.ToString(123)); } [Fact] public void InternalServiceExists() { var sc = new ServiceCollection(); sc.AddTransient<IInterface<int>, Implement<int>>(); sc.AddTransient<IInterface<int>, ImplementWithArg<int>>(); sc.AddManagedService(); sc.AddMicrosoftMemoryCacheAsLocalCache(); sc.UseMemoryManagedServiceSource(); sc.AddNewtonsoftJson(); var sp = sc.BuildServiceResolver(); var cfgs = sp.Resolve<MemoryServiceSource>(); cfgs.SetConfig<IInterface<int>, ImplementWithArg<int>>(1, new { Prefix = "s1" }, 3); cfgs.SetConfig<IInterface<int>, ImplementWithArg<int>>(2, new { Prefix="s2" }, 2, 1); cfgs.SetConfig<IInterface<int>, ImplementWithArg<int>>(3, new { Prefix = "s3" }, 0, 1); var re = sp.ResolveInternal<IInterface<int>>(1); Assert.Equal("s3123", re.ToString(123)); } [Fact] public void InternalServiceNotExists() { var sc = new ServiceCollection(); sc.AddTransient<IInterface<int>, Implement<int>>(); sc.AddTransient<IInterface<int>, ImplementWithArg<int>>(); sc.AddTransient<IInterface2<int>, ImplementWithArg<int>>(); sc.AddManagedService(); sc.AddMicrosoftMemoryCacheAsLocalCache(); sc.UseMemoryManagedServiceSource(); sc.AddNewtonsoftJson(); var sp = sc.BuildServiceResolver(); var cfgs = sp.Resolve<MemoryServiceSource>(); cfgs.SetConfig<IInterface<int>, ImplementWithArg<int>>(1, new { Prefix = "s1" }, 3); cfgs.SetConfig<IInterface2<int>, ImplementWithArg<int>>(2, new { Prefix = "s2" }, 2, 1); cfgs.SetConfig<IInterface2<int>, ImplementWithArg<int>>(3, new { Prefix = "s3" }, 1, 1); var re = sp.ResolveInternal<IInterface<int>>(1); Assert.Equal("s1123", re.ToString(123)); } [Fact] public void InternalServiceNotExists2() { var sc = new ServiceCollection(); sc.AddTransient<IInterface<int>, Implement<int>>(); sc.AddTransient<IInterface<int>, ImplementWithArg<int>>(); sc.AddTransient<IInterface2<int>, ImplementWithArg<int>>(); sc.AddMicrosoftMemoryCacheAsLocalCache(); sc.UseMemoryManagedServiceSource(); sc.AddNewtonsoftJson(); var sp = sc.BuildServiceResolver(); var cfgs = sp.Resolve<MemoryServiceSource>(); cfgs.SetConfig<IInterface2<int>, ImplementWithArg<int>>(1, new { Prefix = "s1" }, 3); cfgs.SetConfig<IInterface2<int>, ImplementWithArg<int>>(2, new { Prefix = "s2" }, 2, 1); cfgs.SetConfig<IInterface2<int>, ImplementWithArg<int>>(3, new { Prefix = "s3" }, 1, 1); var re = sp.ResolveInternal<IInterface<int>>(1); Assert.Equal("null123", re.ToString(123)); } [Fact] public void ServiceConfigChanged() { var sc = new ServiceCollection(); sc.AddTransient<IInterface<int>, ImplementWithArg<int>>(); sc.AddManagedService(); sc.AddMicrosoftMemoryCacheAsLocalCache(); sc.UseMemoryManagedServiceSource(); sc.AddNewtonsoftJson(); var sp = sc.BuildServiceResolver(); var cfgs = sp.Resolve<MemoryServiceSource>(); cfgs.SetConfig<IInterface<int>, ImplementWithArg<int>>(1, new { Prefix = "s1" }); var re = sp.ResolveInternal<IInterface<int>>(1); Assert.Equal("s1123", re.ToString(123)); cfgs.SetConfig<IInterface<int>, ImplementWithArg<int>>(1, new { Prefix = "s2" }); re = sp.ResolveInternal<IInterface<int>>(1); Assert.Equal("s2123", re.ToString(123)); } [Fact] public void ServicePriorityChanged() { var sc = new ServiceCollection(); sc.AddTransient<IInterface<int>, ImplementWithArg<int>>(); sc.AddManagedService(); sc.AddMicrosoftMemoryCacheAsLocalCache(); sc.UseMemoryManagedServiceSource(); sc.AddNewtonsoftJson(); var sp = sc.BuildServiceResolver(); var cfgs = sp.Resolve<MemoryServiceSource>(); cfgs.SetConfig<IInterface<int>, ImplementWithArg<int>>(1, new { Prefix = "s1" },1); cfgs.SetConfig<IInterface<int>, ImplementWithArg<int>>(2, new { Prefix = "s2" },2); var re = sp.Resolve<IInterface<int>>(); Assert.Equal("s1123", re.ToString(123)); cfgs.SetConfig<IInterface<int>, ImplementWithArg<int>>(2, new { Prefix = "s2" }, 0); re = sp.Resolve<IInterface<int>>(); Assert.Equal("s2123", re.ToString(123)); } } }
#region Using Directives using System; using Microsoft.Practices.ComponentModel; using Microsoft.Practices.RecipeFramework; using Microsoft.Practices.RecipeFramework.Services; using System.IO; using Microsoft.Practices.Common; using System.ComponentModel.Design; using Microsoft.Practices.RecipeFramework.VisualStudio.Templates; using System.Collections.Generic; using EnvDTE; using Microsoft.Practices.RecipeFramework.Library.Templates.Actions; using System.Text.RegularExpressions; using Microsoft.Practices.RecipeFramework.Library; using Microsoft.Practices.Common.Services; using System.Xml; using EnvDTE80; using Microsoft.Win32; using System.Collections; using Microsoft.Practices.RecipeFramework.VisualStudio; using Microsoft.VisualStudio; using System.Globalization; using System.Security.Permissions; #endregion namespace SPALM.SPSF.Library.Actions { [ServiceDependency(typeof(DTE)), ServiceDependency(typeof(ITypeResolutionService))] public class ExtendedUnfoldTemplateAction : ExtendedUnfoldTemplateActionBase { /* * * FileIOPermission(SecurityAction.Demand, Write = @"C:\Program Files\")] * FileIOPermission FIOP = new FileIOPermission(PermissionState.Unrestricted); FIOP.AllFiles = FileIOPermissionAccess.AllAccess; * */ private IConfigurationService configurationService; private List<TemplateItem> templateItemLists; [Input(Required = true)] public string ProjectName { get { return _ProjectName; } set { _ProjectName = value; ItemName = value; } } private string _ProjectName = ""; [Input(Required = false)] public bool AdditionalCondition { get { return _AdditionalCondition; } set { _AdditionalCondition = value; } } private bool _AdditionalCondition = true; [Input(Required = false)] public string SolutionFolder { get { return _SolutionFolder; } set { _SolutionFolder = value; } } private string _SolutionFolder = ""; [Input(Required = false)] public bool UseSolutionFolder { get { return _UseSolutionFolder; } set { _UseSolutionFolder = value; } } private bool _UseSolutionFolder = false; public override void Execute() { if (!_AdditionalCondition) { return; } EnvDTE.DTE vs = this.GetService<EnvDTE.DTE>(true); if ((_SolutionFolder != "") && (_UseSolutionFolder)) { Solution2 soln = (Solution2)vs.Solution; Project p = Helpers.GetSolutionFolder(soln, _SolutionFolder); if (p == null) { p = soln.AddSolutionFolder(_SolutionFolder); } this.Root = p; } else { this.Root = vs.Solution; } string solutionPath = (string)vs.Solution.Properties.Item("Path").Value; string solutionDir = System.IO.Path.GetDirectoryName(solutionPath); //solutionpath + ProjectName //string solutionfolder = vs.Solution.FullName; //solutionfolder = solutionfolder.Substring(0,solutionfolder.LastIndexOf("\\")); DestinationFolder = solutionDir + "\\" + ProjectName; //ProjectName ItemName = ProjectName; templateItemLists = new List<TemplateItem>(); configurationService = GetService<IConfigurationService>(true); if (!System.IO.Path.IsPathRooted(this.Template) && configurationService != null) { this.Template = new FileInfo(System.IO.Path.Combine(configurationService.BasePath + @"\Templates\", this.Template)).FullName; } //Helpers.LogMessage(vs, this, "Unfolding template " + this.Template); string templateDirectory = Directory.GetParent(this.Template).FullName; FileIOPermission FIOP = new FileIOPermission(FileIOPermissionAccess.Read, templateDirectory); FIOP.Demand(); IDictionaryService dictionaryService = GetService<IDictionaryService>(); // * !!! //remove wizard not possible because dictionary with recipe arguments is //already loaded and we have conflicts :-( // vsnet loads the vstemplate file from the internal cached zip file // later update impossible //remove recipe from the vstemplate file /* string vstemplateOriginal = this.Template; string vstemplatBackupFileName = System.IO.Path.GetTempFileName(); File.Copy(vstemplateOriginal, vstemplatBackupFileName, true); RemoveWizards(vstemplateOriginal); //this.Template = vstemplateOriginal; //set the template again */ ReadTemplate(); foreach (TemplateItem templateItem in templateItemLists) { if (templateItem.OriginalFileName.ToLower().Contains(".dll") || templateItem.OriginalFileName.ToLower().Contains(".exe")) { //donothing } else { templateItem.ParseItem(dictionaryService); } } try { base.Execute(); } finally { //copy vstemplate back //File.Copy(vstemplatBackupFileName, vstemplateOriginal, true); foreach (TemplateItem templateItem in templateItemLists) { templateItem.Restore(); } } } /// <summary> /// Removes the wizard from a .vstemplate file /// </summary> /// <param name="templateContent"></param> /// <returns></returns> internal void RemoveWizards(string vstemplateFilepath) { XmlDocument vsTemplateDocument = new XmlDocument(); vsTemplateDocument.Load(vstemplateFilepath); //search for wizard WizardData XmlNamespaceManager manager = new XmlNamespaceManager(vsTemplateDocument.NameTable); manager.AddNamespace("ns", "http://schemas.microsoft.com/developer/vstemplate/2005"); XmlNode templateContentNode = vsTemplateDocument.SelectSingleNode("//ns:VSTemplate/ns:WizardData", manager); if (templateContentNode != null) { templateContentNode.ParentNode.RemoveChild(templateContentNode); } vsTemplateDocument.Save(vstemplateFilepath); } public override void Undo() { // nothing to do. } #region Private Helpers private void ReadTemplate() { XmlDocument vsTemplateDocument = new XmlDocument(); XmlNamespaceManager manager = new XmlNamespaceManager(vsTemplateDocument.NameTable); manager.AddNamespace("ns", "http://schemas.microsoft.com/developer/vstemplate/2005"); vsTemplateDocument.Load(this.Template); XmlNode templateContentNode = vsTemplateDocument.SelectSingleNode("//ns:VSTemplate/ns:TemplateContent", manager); if (templateContentNode != null) { foreach (XmlNode projectNode in templateContentNode.SelectNodes("ns:Project", manager)) { if (projectNode.Attributes["File"] != null) { string projectFilename = GetFullPath(projectNode.Attributes["File"].Value); if (File.Exists(projectFilename)) { templateItemLists.Add(new TemplateItem(projectFilename)); } } FindProjecItems(projectNode, manager, System.IO.Path.GetDirectoryName(this.Template)); } FindProjecItems(templateContentNode, manager, System.IO.Path.GetDirectoryName(this.Template)); } } private string GetProjectFolderName(XmlNode foldernode) { if (foldernode.Attributes["TargetFolderName"] != null) { return foldernode.Attributes["TargetFolderName"].Value; } if (foldernode.Attributes["FolderName"] != null) { return foldernode.Attributes["TargetFolderName"].Value; } return ""; } private void FindProjecItems(XmlNode parentNode, XmlNamespaceManager manager, string path) { //Ordner foreach (XmlNode projectFolderNode in parentNode.SelectNodes("ns:Folder", manager)) { FindProjecItems(projectFolderNode, manager, path + "/" + GetProjectFolderName(projectFolderNode)); } foreach (XmlNode projectItemNode in parentNode.SelectNodes("ns:ProjectItem", manager)) { string projectItemFilename = path + "/" + projectItemNode.InnerText; if (File.Exists(projectItemFilename)) { templateItemLists.Add(new TemplateItem(projectItemFilename)); } } } private string GetFullPath(string file) { if (!System.IO.Path.IsPathRooted(file)) { return new FileInfo(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(this.Template), file)).FullName; } return file; } private class TemplateItem { private string originalFilename; public string OriginalFileName { get { return originalFilename; } set { originalFilename = value; } } private string backupFileName; public TemplateItem(string fileName) { this.originalFilename = fileName; } public void Backup() { backupFileName = System.IO.Path.GetTempFileName(); File.Copy(originalFilename, backupFileName, true); } public void Restore() { if (!string.IsNullOrEmpty(backupFileName) && File.Exists(backupFileName)) { File.Copy(backupFileName, originalFilename, true); } } public void ParseItem(IDictionaryService dictionaryService) { string templateContent = File.ReadAllText(this.originalFilename); Regex expression = new Regex("\\$(?<argumentName>\\S+?)\\$", RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.ExplicitCapture); if (dictionaryService != null) { foreach (Match match in expression.Matches(templateContent)) { Group matchGroup = match.Groups["argumentName"]; if (matchGroup.Success) { object value = dictionaryService.GetValue(matchGroup.Value); if (value != null && value is string) { templateContent = templateContent.Replace(match.Value, (string)value); } else if (value != null) { templateContent = templateContent.Replace(match.Value, value.ToString()); } } } } Backup(); File.WriteAllText(originalFilename, templateContent); } } #endregion } }
using J2N.Text; using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Text; using WritableArrayAttribute = Lucene.Net.Support.WritableArrayAttribute; namespace Lucene.Net.Util { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Represents <see cref="T:byte[]"/>, as a slice (offset + length) into an /// existing <see cref="T:byte[]"/>. The <see cref="Bytes"/> property should never be <c>null</c>; /// use <see cref="EMPTY_BYTES"/> if necessary. /// /// <para/><b>Important note:</b> Unless otherwise noted, Lucene uses this class to /// represent terms that are encoded as <b>UTF8</b> bytes in the index. To /// convert them to a .NET <see cref="string"/> (which is UTF16), use <see cref="Utf8ToString()"/>. /// Using code like <c>new String(bytes, offset, length)</c> to do this /// is <b>wrong</b>, as it does not respect the correct character set /// and may return wrong results (depending on the platform's defaults)! /// </summary> #if FEATURE_SERIALIZABLE [Serializable] #endif [DebuggerDisplay("{Utf8ToString()} {ToString()}")] public sealed class BytesRef : IComparable<BytesRef>, IComparable, IEquatable<BytesRef> // LUCENENET specific - implemented IComparable for FieldComparator, IEquatable<BytesRef> #if FEATURE_CLONEABLE , System.ICloneable #endif { /// <summary> /// An empty byte array for convenience </summary> public static readonly byte[] EMPTY_BYTES = #if FEATURE_ARRAYEMPTY Array.Empty<byte>(); #else new byte[0]; #endif /// <summary> /// The contents of the BytesRef. Should never be <c>null</c>. /// </summary> [WritableArray] [SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")] public byte[] Bytes { get => bytes; set => bytes = value; // LUCENENET NOTE: Although the comments state this cannot be null, some of the tests depend on setting it to null! } private byte[] bytes; /// <summary> /// Offset of first valid byte. /// </summary> public int Offset { get; set; } /// <summary> /// Length of used bytes. /// </summary> public int Length { get; set; } /// <summary> /// Create a <see cref="BytesRef"/> with <see cref="EMPTY_BYTES"/> </summary> public BytesRef() : this(EMPTY_BYTES) { } /// <summary> /// This instance will directly reference <paramref name="bytes"/> w/o making a copy. /// <paramref name="bytes"/> should not be <c>null</c>. /// </summary> public BytesRef(byte[] bytes, int offset, int length) { this.bytes = bytes; this.Offset = offset; this.Length = length; Debug.Assert(IsValid()); } /// <summary> /// This instance will directly reference <paramref name="bytes"/> w/o making a copy. /// <paramref name="bytes"/> should not be <c>null</c>. /// </summary> public BytesRef(byte[] bytes) : this(bytes, 0, bytes.Length) { } /// <summary> /// Create a <see cref="BytesRef"/> pointing to a new array of size <paramref name="capacity"/>. /// Offset and length will both be zero. /// </summary> public BytesRef(int capacity) { this.bytes = new byte[capacity]; } /// <summary> /// Initialize the <see cref="T:byte[]"/> from the UTF8 bytes /// for the provided <see cref="ICharSequence"/>. /// </summary> /// <param name="text"> This must be well-formed /// unicode text, with no unpaired surrogates. </param> public BytesRef(ICharSequence text) : this() { CopyChars(text); } /// <summary> /// Initialize the <see cref="T:byte[]"/> from the UTF8 bytes /// for the provided <see cref="string"/>. /// </summary> /// <param name="text"> This must be well-formed /// unicode text, with no unpaired surrogates. </param> public BytesRef(string text) : this() { CopyChars(text); } /// <summary> /// Copies the UTF8 bytes for this <see cref="ICharSequence"/>. /// </summary> /// <param name="text"> Must be well-formed unicode text, with no /// unpaired surrogates or invalid UTF16 code units. </param> public void CopyChars(ICharSequence text) { Debug.Assert(Offset == 0); // TODO broken if offset != 0 UnicodeUtil.UTF16toUTF8(text, 0, text.Length, this); } /// <summary> /// Copies the UTF8 bytes for this <see cref="string"/>. /// </summary> /// <param name="text"> Must be well-formed unicode text, with no /// unpaired surrogates or invalid UTF16 code units. </param> public void CopyChars(string text) { Debug.Assert(Offset == 0); // TODO broken if offset != 0 UnicodeUtil.UTF16toUTF8(text, 0, text.Length, this); } /// <summary> /// Expert: Compares the bytes against another <see cref="BytesRef"/>, /// returning <c>true</c> if the bytes are equal. /// <para/> /// @lucene.internal /// </summary> /// <param name="other"> Another <see cref="BytesRef"/>, should not be <c>null</c>. </param> public bool BytesEquals(BytesRef other) { Debug.Assert(other != null); if (Length == other.Length) { var otherUpto = other.Offset; var otherBytes = other.bytes; var end = Offset + Length; for (int upto = Offset; upto < end; upto++, otherUpto++) { if (bytes[upto] != otherBytes[otherUpto]) { return false; } } return true; } else { return false; } } /// <summary> /// Returns a shallow clone of this instance (the underlying bytes are /// <b>not</b> copied and will be shared by both the returned object and this /// object. /// </summary> /// <seealso cref="DeepCopyOf(BytesRef)"/> public object Clone() { return new BytesRef(bytes, Offset, Length); } /// <summary> /// Calculates the hash code as required by <see cref="Index.TermsHash"/> during indexing. /// <para/> This is currently implemented as MurmurHash3 (32 /// bit), using the seed from /// <see cref="StringHelper.GOOD_FAST_HASH_SEED"/>, but is subject to /// change from release to release. /// </summary> public override int GetHashCode() { return StringHelper.Murmurhash3_x86_32(this, StringHelper.GOOD_FAST_HASH_SEED); } public override bool Equals(object other) { if (other == null) return false; if (other is BytesRef otherBytes) return this.BytesEquals(otherBytes); return false; } bool IEquatable<BytesRef>.Equals(BytesRef other) // LUCENENET specific - implemented IEquatable<BytesRef> => BytesEquals(other); /// <summary> /// Interprets stored bytes as UTF8 bytes, returning the /// resulting <see cref="string"/>. /// </summary> public string Utf8ToString() { CharsRef @ref = new CharsRef(Length); UnicodeUtil.UTF8toUTF16(bytes, Offset, Length, @ref); return @ref.ToString(); } /// <summary> /// Returns hex encoded bytes, eg [0x6c 0x75 0x63 0x65 0x6e 0x65] </summary> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append('['); int end = Offset + Length; for (int i = Offset; i < end; i++) { if (i > Offset) { sb.Append(' '); } sb.Append((bytes[i] & 0xff).ToString("x")); } sb.Append(']'); return sb.ToString(); } /// <summary> /// Copies the bytes from the given <see cref="BytesRef"/> /// <para/> /// NOTE: if this would exceed the array size, this method creates a /// new reference array. /// </summary> public void CopyBytes(BytesRef other) { if (Bytes.Length - Offset < other.Length) { bytes = new byte[other.Length]; Offset = 0; } Array.Copy(other.bytes, other.Offset, bytes, Offset, other.Length); Length = other.Length; } /// <summary> /// Appends the bytes from the given <see cref="BytesRef"/> /// <para/> /// NOTE: if this would exceed the array size, this method creates a /// new reference array. /// </summary> public void Append(BytesRef other) { int newLen = Length + other.Length; if (bytes.Length - Offset < newLen) { var newBytes = new byte[newLen]; Array.Copy(bytes, Offset, newBytes, 0, Length); Offset = 0; bytes = newBytes; } Array.Copy(other.bytes, other.Offset, bytes, Length + Offset, other.Length); Length = newLen; } /// <summary> /// Used to grow the reference array. /// <para/> /// In general this should not be used as it does not take the offset into account. /// <para/> /// @lucene.internal /// </summary> public void Grow(int newLength) { Debug.Assert(Offset == 0); // NOTE: senseless if offset != 0 bytes = ArrayUtil.Grow(bytes, newLength); } /// <summary> /// Unsigned byte order comparison </summary> public int CompareTo(object other) // LUCENENET specific: Implemented IComparable for FieldComparer { BytesRef br = other as BytesRef; Debug.Assert(br != null); return utf8SortedAsUnicodeSortOrder.Compare(this, br); } /// <summary> /// Unsigned byte order comparison </summary> public int CompareTo(BytesRef other) { return utf8SortedAsUnicodeSortOrder.Compare(this, other); } private static readonly IComparer<BytesRef> utf8SortedAsUnicodeSortOrder = Utf8SortedAsUnicodeComparer.Instance; public static IComparer<BytesRef> UTF8SortedAsUnicodeComparer => utf8SortedAsUnicodeSortOrder; // LUCENENET NOTE: De-nested Utf8SortedAsUnicodeComparer class to prevent naming conflict /// @deprecated this comparer is only a transition mechanism [Obsolete("this comparer is only a transition mechanism")] private static readonly IComparer<BytesRef> utf8SortedAsUTF16SortOrder = new Utf8SortedAsUtf16Comparer(); /// @deprecated this comparer is only a transition mechanism [Obsolete("this comparer is only a transition mechanism")] public static IComparer<BytesRef> UTF8SortedAsUTF16Comparer => utf8SortedAsUTF16SortOrder; // LUCENENET NOTE: De-nested Utf8SortedAsUtf16Comparer class to prevent naming conflict /// <summary> /// Creates a new <see cref="BytesRef"/> that points to a copy of the bytes from /// <paramref name="other"/>. /// <para/> /// The returned <see cref="BytesRef"/> will have a length of <c>other.Length</c> /// and an offset of zero. /// </summary> public static BytesRef DeepCopyOf(BytesRef other) { BytesRef copy = new BytesRef(); copy.CopyBytes(other); return copy; } /// <summary> /// Performs internal consistency checks. /// Always returns true (or throws <see cref="InvalidOperationException"/>) /// </summary> public bool IsValid() { if (Bytes == null) { throw new InvalidOperationException("bytes is null"); } if (Length < 0) { throw new InvalidOperationException("length is negative: " + Length); } if (Length > Bytes.Length) { throw new InvalidOperationException("length is out of bounds: " + Length + ",bytes.length=" + Bytes.Length); } if (Offset < 0) { throw new InvalidOperationException("offset is negative: " + Offset); } if (Offset > Bytes.Length) { throw new InvalidOperationException("offset out of bounds: " + Offset + ",bytes.length=" + Bytes.Length); } if (Offset + Length < 0) { throw new InvalidOperationException("offset+length is negative: offset=" + Offset + ",length=" + Length); } if (Offset + Length > Bytes.Length) { throw new InvalidOperationException("offset+length out of bounds: offset=" + Offset + ",length=" + Length + ",bytes.length=" + Bytes.Length); } return true; } } internal class Utf8SortedAsUnicodeComparer : IComparer<BytesRef> { public static Utf8SortedAsUnicodeComparer Instance = new Utf8SortedAsUnicodeComparer(); // Only singleton private Utf8SortedAsUnicodeComparer() { } public virtual int Compare(BytesRef a, BytesRef b) { var aBytes = a.Bytes; int aUpto = a.Offset; var bBytes = b.Bytes; int bUpto = b.Offset; int aStop = aUpto + Math.Min(a.Length, b.Length); while (aUpto < aStop) { int aByte = aBytes[aUpto++] & 0xff; int bByte = bBytes[bUpto++] & 0xff; int diff = aByte - bByte; if (diff != 0) { return diff; } } // One is a prefix of the other, or, they are equal: return a.Length - b.Length; } } /// @deprecated this comparer is only a transition mechanism [Obsolete("this comparer is only a transition mechanism")] internal class Utf8SortedAsUtf16Comparer : IComparer<BytesRef> { // Only singleton internal Utf8SortedAsUtf16Comparer() { } public virtual int Compare(BytesRef a, BytesRef b) { var aBytes = a.Bytes; int aUpto = a.Offset; var bBytes = b.Bytes; int bUpto = b.Offset; int aStop; if (a.Length < b.Length) { aStop = aUpto + a.Length; } else { aStop = aUpto + b.Length; } while (aUpto < aStop) { int aByte = aBytes[aUpto++] & 0xff; int bByte = bBytes[bUpto++] & 0xff; if (aByte != bByte) { // See http://icu-project.org/docs/papers/utf16_code_point_order.html#utf-8-in-utf-16-order // We know the terms are not equal, but, we may // have to carefully fixup the bytes at the // difference to match UTF16's sort order: // NOTE: instead of moving supplementary code points (0xee and 0xef) to the unused 0xfe and 0xff, // we move them to the unused 0xfc and 0xfd [reserved for future 6-byte character sequences] // this reserves 0xff for preflex's term reordering (surrogate dance), and if unicode grows such // that 6-byte sequences are needed we have much bigger problems anyway. if (aByte >= 0xee && bByte >= 0xee) { if ((aByte & 0xfe) == 0xee) { aByte += 0xe; } if ((bByte & 0xfe) == 0xee) { bByte += 0xe; } } return aByte - bByte; } } // One is a prefix of the other, or, they are equal: return a.Length - b.Length; } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using osuTK; namespace osu.Framework.MathUtils { /// <summary> /// Helper methods to approximate a path by interpolating a sequence of control points. /// </summary> public static class PathApproximator { private const float bezier_tolerance = 0.25f; /// <summary> /// The amount of pieces to calculate for each control point quadruplet. /// </summary> private const int catmull_detail = 50; private const float circular_arc_tolerance = 0.1f; /// <summary> /// Creates a piecewise-linear approximation of a bezier curve, by adaptively repeatedly subdividing /// the control points until their approximation error vanishes below a given threshold. /// </summary> /// <returns>A list of vectors representing the piecewise-linear approximation.</returns> public static List<Vector2> ApproximateBezier(ReadOnlySpan<Vector2> controlPoints) { List<Vector2> output = new List<Vector2>(); int count = controlPoints.Length; if (count == 0) return output; var subdivisionBuffer1 = new Vector2[count]; var subdivisionBuffer2 = new Vector2[count * 2 - 1]; Stack<Vector2[]> toFlatten = new Stack<Vector2[]>(); Stack<Vector2[]> freeBuffers = new Stack<Vector2[]>(); // "toFlatten" contains all the curves which are not yet approximated well enough. // We use a stack to emulate recursion without the risk of running into a stack overflow. // (More specifically, we iteratively and adaptively refine our curve with a // <a href="https://en.wikipedia.org/wiki/Depth-first_search">Depth-first search</a> // over the tree resulting from the subdivisions we make.) toFlatten.Push(controlPoints.ToArray()); Vector2[] leftChild = subdivisionBuffer2; while (toFlatten.Count > 0) { Vector2[] parent = toFlatten.Pop(); if (bezierIsFlatEnough(parent)) { // If the control points we currently operate on are sufficiently "flat", we use // an extension to De Casteljau's algorithm to obtain a piecewise-linear approximation // of the bezier curve represented by our control points, consisting of the same amount // of points as there are control points. bezierApproximate(parent, output, subdivisionBuffer1, subdivisionBuffer2, count); freeBuffers.Push(parent); continue; } // If we do not yet have a sufficiently "flat" (in other words, detailed) approximation we keep // subdividing the curve we are currently operating on. Vector2[] rightChild = freeBuffers.Count > 0 ? freeBuffers.Pop() : new Vector2[count]; bezierSubdivide(parent, leftChild, rightChild, subdivisionBuffer1, count); // We re-use the buffer of the parent for one of the children, so that we save one allocation per iteration. for (int i = 0; i < count; ++i) parent[i] = leftChild[i]; toFlatten.Push(rightChild); toFlatten.Push(parent); } output.Add(controlPoints[count - 1]); return output; } /// <summary> /// Creates a piecewise-linear approximation of a Catmull-Rom spline. /// </summary> /// <returns>A list of vectors representing the piecewise-linear approximation.</returns> public static List<Vector2> ApproximateCatmull(ReadOnlySpan<Vector2> controlPoints) { var result = new List<Vector2>((controlPoints.Length - 1) * catmull_detail * 2); for (int i = 0; i < controlPoints.Length - 1; i++) { var v1 = i > 0 ? controlPoints[i - 1] : controlPoints[i]; var v2 = controlPoints[i]; var v3 = i < controlPoints.Length - 1 ? controlPoints[i + 1] : v2 + v2 - v1; var v4 = i < controlPoints.Length - 2 ? controlPoints[i + 2] : v3 + v3 - v2; for (int c = 0; c < catmull_detail; c++) { result.Add(catmullFindPoint(ref v1, ref v2, ref v3, ref v4, (float)c / catmull_detail)); result.Add(catmullFindPoint(ref v1, ref v2, ref v3, ref v4, (float)(c + 1) / catmull_detail)); } } return result; } /// <summary> /// Creates a piecewise-linear approximation of a circular arc curve. /// </summary> /// <returns>A list of vectors representing the piecewise-linear approximation.</returns> public static List<Vector2> ApproximateCircularArc(ReadOnlySpan<Vector2> controlPoints) { Vector2 a = controlPoints[0]; Vector2 b = controlPoints[1]; Vector2 c = controlPoints[2]; float aSq = (b - c).LengthSquared; float bSq = (a - c).LengthSquared; float cSq = (a - b).LengthSquared; // If we have a degenerate triangle where a side-length is almost zero, then give up and fall // back to a more numerically stable method. if (Precision.AlmostEquals(aSq, 0) || Precision.AlmostEquals(bSq, 0) || Precision.AlmostEquals(cSq, 0)) return new List<Vector2>(); float s = aSq * (bSq + cSq - aSq); float t = bSq * (aSq + cSq - bSq); float u = cSq * (aSq + bSq - cSq); float sum = s + t + u; // If we have a degenerate triangle with an almost-zero size, then give up and fall // back to a more numerically stable method. if (Precision.AlmostEquals(sum, 0)) return new List<Vector2>(); Vector2 centre = (s * a + t * b + u * c) / sum; Vector2 dA = a - centre; Vector2 dC = c - centre; float r = dA.Length; double thetaStart = Math.Atan2(dA.Y, dA.X); double thetaEnd = Math.Atan2(dC.Y, dC.X); while (thetaEnd < thetaStart) thetaEnd += 2 * Math.PI; double dir = 1; double thetaRange = thetaEnd - thetaStart; // Decide in which direction to draw the circle, depending on which side of // AC B lies. Vector2 orthoAtoC = c - a; orthoAtoC = new Vector2(orthoAtoC.Y, -orthoAtoC.X); if (Vector2.Dot(orthoAtoC, b - a) < 0) { dir = -dir; thetaRange = 2 * Math.PI - thetaRange; } // We select the amount of points for the approximation by requiring the discrete curvature // to be smaller than the provided tolerance. The exact angle required to meet the tolerance // is: 2 * Math.Acos(1 - TOLERANCE / r) // The special case is required for extremely short sliders where the radius is smaller than // the tolerance. This is a pathological rather than a realistic case. int amountPoints = 2 * r <= circular_arc_tolerance ? 2 : Math.Max(2, (int)Math.Ceiling(thetaRange / (2 * Math.Acos(1 - circular_arc_tolerance / r)))); List<Vector2> output = new List<Vector2>(amountPoints); for (int i = 0; i < amountPoints; ++i) { double fract = (double)i / (amountPoints - 1); double theta = thetaStart + dir * fract * thetaRange; Vector2 o = new Vector2((float)Math.Cos(theta), (float)Math.Sin(theta)) * r; output.Add(centre + o); } return output; } /// <summary> /// Creates a piecewise-linear approximation of a linear curve. /// Basically, returns the input. /// </summary> /// <returns>A list of vectors representing the piecewise-linear approximation.</returns> public static List<Vector2> ApproximateLinear(ReadOnlySpan<Vector2> controlPoints) { var result = new List<Vector2>(controlPoints.Length); foreach (var c in controlPoints) result.Add(c); return result; } /// <summary> /// Creates a piecewise-linear approximation of a lagrange polynomial. /// </summary> /// <returns>A list of vectors representing the piecewise-linear approximation.</returns> public static List<Vector2> ApproximateLagrangePolynomial(ReadOnlySpan<Vector2> controlPoints) { // TODO: add some smarter logic here, chebyshev nodes? const int num_steps = 51; var result = new List<Vector2>(num_steps); double[] weights = Interpolation.BarycentricWeights(controlPoints); float minX = controlPoints[0].X; float maxX = controlPoints[0].X; for (int i = 1; i < controlPoints.Length; i++) { minX = Math.Min(minX, controlPoints[i].X); maxX = Math.Max(maxX, controlPoints[i].X); } float dx = maxX - minX; for (int i = 0; i < num_steps; i++) { float x = minX + dx / (num_steps - 1) * i; float y = (float)Interpolation.BarycentricLagrange(controlPoints, weights, x); result.Add(new Vector2(x, y)); } return result; } /// <summary> /// Make sure the 2nd order derivative (approximated using finite elements) is within tolerable bounds. /// NOTE: The 2nd order derivative of a 2d curve represents its curvature, so intuitively this function /// checks (as the name suggests) whether our approximation is _locally_ "flat". More curvy parts /// need to have a denser approximation to be more "flat". /// </summary> /// <param name="controlPoints">The control points to check for flatness.</param> /// <returns>Whether the control points are flat enough.</returns> private static bool bezierIsFlatEnough(Vector2[] controlPoints) { for (int i = 1; i < controlPoints.Length - 1; i++) if ((controlPoints[i - 1] - 2 * controlPoints[i] + controlPoints[i + 1]).LengthSquared > bezier_tolerance * bezier_tolerance * 4) return false; return true; } /// <summary> /// Subdivides n control points representing a bezier curve into 2 sets of n control points, each /// describing a bezier curve equivalent to a half of the original curve. Effectively this splits /// the original curve into 2 curves which result in the original curve when pieced back together. /// </summary> /// <param name="controlPoints">The control points to split.</param> /// <param name="l">Output: The control points corresponding to the left half of the curve.</param> /// <param name="r">Output: The control points corresponding to the right half of the curve.</param> /// <param name="subdivisionBuffer">The first buffer containing the current subdivision state.</param> /// <param name="count">The number of control points in the original list.</param> private static void bezierSubdivide(Vector2[] controlPoints, Vector2[] l, Vector2[] r, Vector2[] subdivisionBuffer, int count) { Vector2[] midpoints = subdivisionBuffer; for (int i = 0; i < count; ++i) midpoints[i] = controlPoints[i]; for (int i = 0; i < count; i++) { l[i] = midpoints[0]; r[count - i - 1] = midpoints[count - i - 1]; for (int j = 0; j < count - i - 1; j++) midpoints[j] = (midpoints[j] + midpoints[j + 1]) / 2; } } /// <summary> /// This uses <a href="https://en.wikipedia.org/wiki/De_Casteljau%27s_algorithm">De Casteljau's algorithm</a> to obtain an optimal /// piecewise-linear approximation of the bezier curve with the same amount of points as there are control points. /// </summary> /// <param name="controlPoints">The control points describing the bezier curve to be approximated.</param> /// <param name="output">The points representing the resulting piecewise-linear approximation.</param> /// <param name="count">The number of control points in the original list.</param> /// <param name="subdivisionBuffer1">The first buffer containing the current subdivision state.</param> /// <param name="subdivisionBuffer2">The second buffer containing the current subdivision state.</param> private static void bezierApproximate(Vector2[] controlPoints, List<Vector2> output, Vector2[] subdivisionBuffer1, Vector2[] subdivisionBuffer2, int count) { Vector2[] l = subdivisionBuffer2; Vector2[] r = subdivisionBuffer1; bezierSubdivide(controlPoints, l, r, subdivisionBuffer1, count); for (int i = 0; i < count - 1; ++i) l[count + i] = r[i + 1]; output.Add(controlPoints[0]); for (int i = 1; i < count - 1; ++i) { int index = 2 * i; Vector2 p = 0.25f * (l[index - 1] + 2 * l[index] + l[index + 1]); output.Add(p); } } /// <summary> /// Finds a point on the spline at the position of a parameter. /// </summary> /// <param name="vec1">The first vector.</param> /// <param name="vec2">The second vector.</param> /// <param name="vec3">The third vector.</param> /// <param name="vec4">The fourth vector.</param> /// <param name="t">The parameter at which to find the point on the spline, in the range [0, 1].</param> /// <returns>The point on the spline at <paramref name="t"/>.</returns> private static Vector2 catmullFindPoint(ref Vector2 vec1, ref Vector2 vec2, ref Vector2 vec3, ref Vector2 vec4, float t) { float t2 = t * t; float t3 = t * t2; Vector2 result; result.X = 0.5f * (2f * vec2.X + (-vec1.X + vec3.X) * t + (2f * vec1.X - 5f * vec2.X + 4f * vec3.X - vec4.X) * t2 + (-vec1.X + 3f * vec2.X - 3f * vec3.X + vec4.X) * t3); result.Y = 0.5f * (2f * vec2.Y + (-vec1.Y + vec3.Y) * t + (2f * vec1.Y - 5f * vec2.Y + 4f * vec3.Y - vec4.Y) * t2 + (-vec1.Y + 3f * vec2.Y - 3f * vec3.Y + vec4.Y) * t3); return result; } } }
using System; using NUnit.Framework; using System.Text.RegularExpressions; using System.Drawing; using OpenQA.Selenium.Internal; namespace OpenQA.Selenium.Interactions { [TestFixture] [IgnoreBrowser(Browser.Safari, "Not implemented (issue 4136)")] public class BasicMouseInterfaceTest : DriverTestFixture { [SetUp] public void SetupTest() { IActionExecutor actionExecutor = driver as IActionExecutor; if (actionExecutor != null) { actionExecutor.ResetInputState(); } } [Test] [IgnoreBrowser(Browser.IPhone, "API not implemented in driver")] [IgnoreBrowser(Browser.Android, "API not implemented in driver")] public void ShouldAllowDraggingElementWithMouseMovesItToAnotherList() { PerformDragAndDropWithMouse(); IWebElement dragInto = driver.FindElement(By.Id("sortable1")); Assert.AreEqual(6, dragInto.FindElements(By.TagName("li")).Count); } // This test is very similar to DraggingElementWithMouse. The only // difference is that this test also verifies the correct events were fired. [Test] [IgnoreBrowser(Browser.IPhone, "API not implemented in driver")] [IgnoreBrowser(Browser.Android, "API not implemented in driver")] public void DraggingElementWithMouseFiresEvents() { PerformDragAndDropWithMouse(); IWebElement dragReporter = driver.FindElement(By.Id("dragging_reports")); // This is failing under HtmlUnit. A bug was filed. Assert.IsTrue(Regex.IsMatch(dragReporter.Text, "Nothing happened\\. (?:DragOut *)+DropIn RightItem 3")); } [Test] [IgnoreBrowser(Browser.IPhone, "API not implemented in driver")] [IgnoreBrowser(Browser.Android, "API not implemented in driver")] public void ShouldAllowDoubleClickThenNavigate() { driver.Url = javascriptPage; IWebElement toDoubleClick = driver.FindElement(By.Id("doubleClickField")); Actions actionProvider = new Actions(driver); IAction dblClick = actionProvider.DoubleClick(toDoubleClick).Build(); dblClick.Perform(); driver.Url = droppableItems; } [Test] [IgnoreBrowser(Browser.IPhone, "API not implemented in driver")] [IgnoreBrowser(Browser.Android, "API not implemented in driver")] public void ShouldAllowDragAndDrop() { driver.Url = droppableItems; DateTime waitEndTime = DateTime.Now.Add(TimeSpan.FromSeconds(15)); while (!IsElementAvailable(driver, By.Id("draggable")) && (DateTime.Now < waitEndTime)) { System.Threading.Thread.Sleep(200); } if (!IsElementAvailable(driver, By.Id("draggable"))) { throw new Exception("Could not find draggable element after 15 seconds."); } IWebElement toDrag = driver.FindElement(By.Id("draggable")); IWebElement dropInto = driver.FindElement(By.Id("droppable")); Actions actionProvider = new Actions(driver); IAction holdDrag = actionProvider.ClickAndHold(toDrag).Build(); IAction move = actionProvider.MoveToElement(dropInto).Build(); IAction drop = actionProvider.Release(dropInto).Build(); holdDrag.Perform(); move.Perform(); drop.Perform(); dropInto = driver.FindElement(By.Id("droppable")); string text = dropInto.FindElement(By.TagName("p")).Text; Assert.AreEqual("Dropped!", text); } [Test] [IgnoreBrowser(Browser.IPhone, "API not implemented in driver")] [IgnoreBrowser(Browser.Android, "API not implemented in driver")] public void ShouldAllowDoubleClick() { driver.Url = javascriptPage; IWebElement toDoubleClick = driver.FindElement(By.Id("doubleClickField")); Actions actionProvider = new Actions(driver); IAction dblClick = actionProvider.DoubleClick(toDoubleClick).Build(); dblClick.Perform(); Assert.AreEqual("DoubleClicked", toDoubleClick.GetAttribute("value")); } [Test] //[IgnoreBrowser(Browser.Chrome, "ChromeDriver2 does not perform this yet")] [IgnoreBrowser(Browser.IPhone, "API not implemented in driver")] [IgnoreBrowser(Browser.Android, "API not implemented in driver")] public void ShouldAllowContextClick() { driver.Url = javascriptPage; IWebElement toContextClick = driver.FindElement(By.Id("doubleClickField")); Actions actionProvider = new Actions(driver); IAction contextClick = actionProvider.ContextClick(toContextClick).Build(); contextClick.Perform(); Assert.AreEqual("ContextClicked", toContextClick.GetAttribute("value")); } [Test] [IgnoreBrowser(Browser.IPhone, "API not implemented in driver")] [IgnoreBrowser(Browser.Remote, "API not implemented in driver")] [IgnoreBrowser(Browser.Android, "API not implemented in driver")] [IgnoreBrowser(Browser.Safari, "API not implemented in driver")] public void ShouldAllowMoveAndClick() { driver.Url = javascriptPage; IWebElement toClick = driver.FindElement(By.Id("clickField")); Actions actionProvider = new Actions(driver); IAction contextClick = actionProvider.MoveToElement(toClick).Click().Build(); contextClick.Perform(); Assert.AreEqual("Clicked", toClick.GetAttribute("value"), "Value should change to Clicked."); } [Test] [IgnoreBrowser(Browser.IE, "Clicking without context is perfectly valid for W3C-compliant remote ends.")] [IgnoreBrowser(Browser.Firefox, "Clicking without context is perfectly valid for W3C-compliant remote ends.")] [IgnoreBrowser(Browser.Chrome, "Clicking without context is perfectly valid for Chrome.")] [IgnoreBrowser(Browser.IPhone, "API not implemented in driver")] [IgnoreBrowser(Browser.Remote, "API not implemented in driver")] [IgnoreBrowser(Browser.Android, "API not implemented in driver")] [IgnoreBrowser(Browser.Safari, "API not implemented in driver")] public void ShouldNotMoveToANullLocator() { driver.Url = javascriptPage; try { IAction contextClick = new Actions(driver).MoveToElement(null).Build(); contextClick.Perform(); Assert.Fail("Shouldn't be allowed to click on null element."); } catch (ArgumentException) { // Expected. } try { new Actions(driver).Click().Build().Perform(); Assert.Fail("Shouldn't be allowed to click without a context."); } catch (Exception) { // expected } } [Test] [IgnoreBrowser(Browser.IPhone, "API not implemented in driver")] [IgnoreBrowser(Browser.Android, "API not implemented in driver")] [IgnoreBrowser(Browser.Opera, "API not implemented in driver")] public void ShouldClickElementInIFrame() { driver.Url = clicksPage; try { driver.SwitchTo().Frame("source"); IWebElement element = driver.FindElement(By.Id("otherframe")); new Actions(driver).MoveToElement(element).Click().Perform(); driver.SwitchTo().DefaultContent().SwitchTo().Frame("target"); WaitFor(() => { return driver.FindElement(By.Id("span")).Text == "An inline element"; }, "Could not find element with text 'An inline element'"); } finally { driver.SwitchTo().DefaultContent(); } } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.IPhone)] [IgnoreBrowser(Browser.Opera)] [IgnoreBrowser(Browser.HtmlUnit)] [IgnoreBrowser(Browser.Safari, "Advanced user interactions not implemented for Safari")] public void ShouldAllowUsersToHoverOverElements() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("menu1")); if (!Platform.CurrentPlatform.IsPlatformType(PlatformType.Windows)) { Assert.Ignore("Skipping test: Simulating hover needs native events"); } IHasInputDevices inputDevicesDriver = driver as IHasInputDevices; if (inputDevicesDriver == null) { return; } IWebElement item = driver.FindElement(By.Id("item1")); Assert.AreEqual("", item.Text); ((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].style.background = 'green'", element); //element.Hover(); Actions actionBuilder = new Actions(driver); actionBuilder.MoveToElement(element).Perform(); item = driver.FindElement(By.Id("item1")); Assert.AreEqual("Item 1", item.Text); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "Advanced mouse actions only implemented in rendered browsers")] [IgnoreBrowser(Browser.Safari, "Advanced user interactions not implemented for Safari")] public void MovingMouseByRelativeOffset() { driver.Url = mouseTrackerPage; IWebElement trackerDiv = driver.FindElement(By.Id("mousetracker")); new Actions(driver).MoveToElement(trackerDiv).Build().Perform(); IWebElement reporter = driver.FindElement(By.Id("status")); WaitFor(FuzzyMatchingOfCoordinates(reporter, 50, 200), "Coordinate matching was not within tolerance"); new Actions(driver).MoveByOffset(10, 20).Build().Perform(); WaitFor(FuzzyMatchingOfCoordinates(reporter, 60, 220), "Coordinate matching was not within tolerance"); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "Advanced mouse actions only implemented in rendered browsers")] [IgnoreBrowser(Browser.Safari, "Advanced user interactions not implemented for Safari")] public void MovingMouseToRelativeElementOffset() { driver.Url = mouseTrackerPage; IWebElement trackerDiv = driver.FindElement(By.Id("mousetracker")); new Actions(driver).MoveToElement(trackerDiv, 95, 195).Build().Perform(); IWebElement reporter = driver.FindElement(By.Id("status")); WaitFor(FuzzyMatchingOfCoordinates(reporter, 95, 195), "Coordinate matching was not within tolerance"); } [Test] [Category("Javascript")] [NeedsFreshDriver(IsCreatedBeforeTest = true)] [IgnoreBrowser(Browser.HtmlUnit, "Advanced mouse actions only implemented in rendered browsers")] [IgnoreBrowser(Browser.Safari, "Advanced user interactions not implemented for Safari")] public void MoveRelativeToBody() { driver.Url = mouseTrackerPage; new Actions(driver).MoveByOffset(50, 100).Build().Perform(); IWebElement reporter = driver.FindElement(By.Id("status")); WaitFor(FuzzyMatchingOfCoordinates(reporter, 40, 20), "Coordinate matching was not within tolerance"); } [Test] [Category("Javascript")] [NeedsFreshDriver(IsCreatedBeforeTest = true)] [IgnoreBrowser(Browser.HtmlUnit, "Advanced mouse actions only implemented in rendered browsers")] [IgnoreBrowser(Browser.Safari, "Advanced user interactions not implemented for Safari")] public void CanMouseOverAndOutOfAnElement() { driver.Url = mouseOverPage; IWebElement greenbox = driver.FindElement(By.Id("greenbox")); IWebElement redbox = driver.FindElement(By.Id("redbox")); Size size = redbox.Size; new Actions(driver).MoveToElement(greenbox, 1, 1).Perform(); Assert.That(redbox.GetCssValue("background-color"), Is.EqualTo("rgba(0, 128, 0, 1)").Or.EqualTo("rgb(0, 128, 0)")); new Actions(driver).MoveToElement(redbox).Perform(); Assert.That(redbox.GetCssValue("background-color"), Is.EqualTo("rgba(255, 0, 0, 1)").Or.EqualTo("rgb(255, 0, 0)")); new Actions(driver).MoveToElement(redbox, size.Width + 2, size.Height + 2).Perform(); Assert.That(redbox.GetCssValue("background-color"), Is.EqualTo("rgba(0, 128, 0, 1)").Or.EqualTo("rgb(0, 128, 0)")); } private Func<bool> FuzzyMatchingOfCoordinates(IWebElement element, int x, int y) { return () => { return FuzzyPositionMatching(x, y, element.Text); }; } private bool FuzzyPositionMatching(int expectedX, int expectedY, String locationTuple) { string[] splitString = locationTuple.Split(','); int gotX = int.Parse(splitString[0].Trim()); int gotY = int.Parse(splitString[1].Trim()); // Everything within 5 pixels range is OK const int ALLOWED_DEVIATION = 5; return Math.Abs(expectedX - gotX) < ALLOWED_DEVIATION && Math.Abs(expectedY - gotY) < ALLOWED_DEVIATION; } private void PerformDragAndDropWithMouse() { driver.Url = draggableLists; IWebElement dragReporter = driver.FindElement(By.Id("dragging_reports")); IWebElement toDrag = driver.FindElement(By.Id("rightitem-3")); IWebElement dragInto = driver.FindElement(By.Id("sortable1")); IAction holdItem = new Actions(driver).ClickAndHold(toDrag).Build(); IAction moveToSpecificItem = new Actions(driver).MoveToElement(driver.FindElement(By.Id("leftitem-4"))).Build(); IAction moveToOtherList = new Actions(driver).MoveToElement(dragInto).Build(); IAction drop = new Actions(driver).Release(dragInto).Build(); Assert.AreEqual("Nothing happened.", dragReporter.Text); holdItem.Perform(); moveToSpecificItem.Perform(); moveToOtherList.Perform(); Assert.IsTrue(Regex.IsMatch(dragReporter.Text, "Nothing happened\\. (?:DragOut *)+")); drop.Perform(); } private bool IsElementAvailable(IWebDriver driver, By locator) { try { driver.FindElement(locator); return true; } catch (NoSuchElementException) { return false; } } } }
using System; namespace C5 { /// <summary> /// Base class (abstract) for ICollection implementations. /// </summary> [Serializable] public abstract class CollectionBase<T> : CollectionValueBase<T> { #region Fields /// <summary> /// The underlying field of the ReadOnly property /// </summary> protected bool isReadOnlyBase = false; /// <summary> /// The current stamp value /// </summary> protected int stamp; /// <summary> /// The number of items in the collection /// </summary> protected int size; /// <summary> /// The item equalityComparer of the collection /// </summary> protected readonly System.Collections.Generic.IEqualityComparer<T> itemequalityComparer; private int iUnSequencedHashCode, iUnSequencedHashCodeStamp = -1; #endregion /// <summary> /// /// </summary> /// <param name="itemequalityComparer"></param> protected CollectionBase(System.Collections.Generic.IEqualityComparer<T> itemequalityComparer) { this.itemequalityComparer = itemequalityComparer ?? throw new NullReferenceException("Item EqualityComparer cannot be null."); } #region Util /// <summary> /// Utility method for range checking. /// </summary> /// <exception cref="ArgumentOutOfRangeException"> if the start or count is negative or /// if the range does not fit within collection size.</exception> /// <param name="start">start of range</param> /// <param name="count">size of range</param> protected void CheckRange(int start, int count) { if (start < 0 || count < 0 || start + count > size) { throw new ArgumentOutOfRangeException(); } } /// <summary> /// Compute the unsequenced hash code of a collection /// </summary> /// <param name="items">The collection to compute hash code for</param> /// <param name="itemequalityComparer">The item equalitySCG.Comparer</param> /// <returns>The hash code</returns> public static int ComputeHashCode(ICollectionValue<T> items, System.Collections.Generic.IEqualityComparer<T> itemequalityComparer) { int h = 0; //But still heuristic: //Note: the three odd factors should really be random, //but there will be a problem with serialization/deserialization! //Two products is too few foreach (T item in items) { uint h1 = (uint)itemequalityComparer.GetHashCode(item); h += (int)((h1 * 1529784657 + 1) ^ (h1 * 2912831877) ^ (h1 * 1118771817 + 2)); } return h; /* The pairs (-1657792980, -1570288808) and (1862883298, -272461342) gives the same unsequenced hashcode with this hashfunction. The pair was found with code like HashDictionary<int, int[]> set = new HashDictionary<int, int[]>(); Random rnd = new C5Random(12345); while (true) { int[] a = new int[2]; a[0] = rnd.Next(); a[1] = rnd.Next(); int h = unsequencedhashcode(a); int[] b = a; if (set.FindOrAdd(h, ref b)) { Logger.Log(string.Format("Code {5}, Pair ({1},{2}) number {0} matched other pair ({3},{4})", set.Count, a[0], a[1], b[0], b[1], h)); } } */ } // static Type isortedtype = typeof(ISorted<T>); /// <summary> /// Examine if collection1 and collection2 are equal as unsequenced collections /// using the specified item equalityComparer (assumed compatible with the two collections). /// </summary> /// <param name="collection1">The first collection</param> /// <param name="collection2">The second collection</param> /// <param name="itemequalityComparer">The item equalityComparer to use for comparison</param> /// <returns>True if equal</returns> public static bool StaticEquals(ICollection<T> collection1, ICollection<T> collection2, System.Collections.Generic.IEqualityComparer<T> itemequalityComparer) { if (object.ReferenceEquals(collection1, collection2)) { return true; } // bug20070227: if (collection1 == null || collection2 == null) { return false; } if (collection1.Count != collection2.Count) { return false; } //This way we might run through both enumerations twice, but //probably not (if the hash codes are good) //TODO: check equal equalityComparers, at least here! if (collection1.GetUnsequencedHashCode() != collection2.GetUnsequencedHashCode()) { return false; } //TODO: move this to the sorted implementation classes? //Really depends on speed of InstanceOfType: we could save a cast { if (collection1 is ISorted<T> stit && collection2 is ISorted<T> stat && stit.Comparer == stat.Comparer) { using System.Collections.Generic.IEnumerator<T> dat = collection2.GetEnumerator(), dit = collection1.GetEnumerator(); while (dit.MoveNext()) { dat.MoveNext(); if (!itemequalityComparer.Equals(dit.Current, dat.Current)) { return false; } } return true; } } if (!collection1.AllowsDuplicates && (collection2.AllowsDuplicates || collection2.ContainsSpeed >= collection1.ContainsSpeed)) { foreach (T x in collection1) { if (!collection2.Contains(x)) { return false; } } } else if (!collection2.AllowsDuplicates) { foreach (T x in collection2) { if (!collection1.Contains(x)) { return false; } } } // Now tit.AllowsDuplicates && tat.AllowsDuplicates else if (collection1.DuplicatesByCounting && collection2.DuplicatesByCounting) { foreach (T item in collection2) { if (collection1.ContainsCount(item) != collection2.ContainsCount(item)) { return false; } } } else { // To avoid an O(n^2) algorithm, we make an aux hashtable to hold the count of items // bug20101103: HashDictionary<T, int> dict = new HashDictionary<T, int>(); HashDictionary<T, int> dict = new HashDictionary<T, int>(itemequalityComparer); foreach (T item in collection2) { int count = 1; if (dict.FindOrAdd(item, ref count)) { dict[item] = count + 1; } } foreach (T item in collection1) { var i = item; if (dict.Find(ref i, out int count) && count > 0) { dict[item] = count - 1; } else { return false; } } return true; } return true; } /// <summary> /// Get the unsequenced collection hash code of this collection: from the cached /// value if present and up to date, else (re)compute. /// </summary> /// <returns>The hash code</returns> public virtual int GetUnsequencedHashCode() { if (iUnSequencedHashCodeStamp == stamp) { return iUnSequencedHashCode; } iUnSequencedHashCode = ComputeHashCode(this, itemequalityComparer); iUnSequencedHashCodeStamp = stamp; return iUnSequencedHashCode; } /// <summary> /// Check if the contents of otherCollection is equal to the contents of this /// in the unsequenced sense. Uses the item equality comparer of this collection /// </summary> /// <param name="otherCollection">The collection to compare to.</param> /// <returns>True if equal</returns> public virtual bool UnsequencedEquals(ICollection<T> otherCollection) { return otherCollection != null && StaticEquals((ICollection<T>)this, otherCollection, itemequalityComparer); } /// <summary> /// Check if the collection has been modified since a specified time, expressed as a stamp value. /// </summary> /// <exception cref="CollectionModifiedException"> if this collection has been updated /// since a target time</exception> /// <param name="thestamp">The stamp identifying the target time</param> protected virtual void ModifyCheck(int thestamp) { if (stamp != thestamp) { throw new CollectionModifiedException(); } } /// <summary> /// Check if it is valid to perform update operations, and if so increment stamp. /// </summary> /// <exception cref="ReadOnlyCollectionException">If collection is read-only</exception> protected virtual void UpdateCheck() { if (isReadOnlyBase) { throw new ReadOnlyCollectionException(); } stamp++; } #endregion #region ICollection<T> members /// <summary> /// /// </summary> /// <value>True if this collection is read only</value> public virtual bool IsReadOnly => isReadOnlyBase; #endregion #region ICollectionValue<T> members /// <summary> /// /// </summary> /// <value>The size of this collection</value> public override int Count => size; /// <summary> /// The value is symbolic indicating the type of asymptotic complexity /// in terms of the size of this collection (worst-case or amortized as /// relevant). /// </summary> /// <value>A characterization of the speed of the /// <code>Count</code> property in this collection.</value> public override Speed CountSpeed => Speed.Constant; #endregion #region IExtensible<T> members /// <summary> /// /// </summary> /// <value></value> public virtual System.Collections.Generic.IEqualityComparer<T> EqualityComparer => itemequalityComparer; /// <summary> /// /// </summary> /// <value>True if this collection is empty</value> public override bool IsEmpty => size == 0; #endregion #region IEnumerable<T> Members /// <summary> /// Create an enumerator for this collection. /// </summary> /// <returns>The enumerator</returns> public abstract override System.Collections.Generic.IEnumerator<T> GetEnumerator(); #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using CFStringRef = System.IntPtr; using FSEventStreamRef = System.IntPtr; using size_t = System.IntPtr; using FSEventStreamEventId = System.UInt64; using CFRunLoopRef = System.IntPtr; using Microsoft.Win32.SafeHandles; namespace System.IO { public partial class FileSystemWatcher { /// <summary>Called when FileSystemWatcher is finalized.</summary> private void FinalizeDispose() { // Make sure we cleanup StopRaisingEvents(); } private void StartRaisingEvents() { // Don't start another instance if one is already runnings if (_cancellation != null) { return; } try { CancellationTokenSource cancellation = new CancellationTokenSource(); RunningInstance instance = new RunningInstance(this, _directory, _includeSubdirectories, TranslateFlags(_notifyFilters), cancellation.Token); _enabled = true; _cancellation = cancellation; instance.Start(); } catch { _enabled = false; _cancellation = null; throw; } } private void StopRaisingEvents() { _enabled = false; CancellationTokenSource token = _cancellation; if (token != null) { _cancellation = null; token.Cancel(); } } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- private CancellationTokenSource _cancellation; private static Interop.EventStream.FSEventStreamEventFlags TranslateFlags(NotifyFilters flagsToTranslate) { Interop.EventStream.FSEventStreamEventFlags flags = 0; // Always re-create the filter flags when start is called since they could have changed if ((flagsToTranslate & (NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Size)) != 0) { flags = Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemInodeMetaMod | Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemFinderInfoMod | Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemModified | Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemChangeOwner; } if ((flagsToTranslate & NotifyFilters.Security) != 0) { flags |= Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemChangeOwner | Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemXattrMod; } if ((flagsToTranslate & NotifyFilters.DirectoryName) != 0) { flags |= Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsDir | Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsSymlink | Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemCreated | Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemRemoved | Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemRenamed; } if ((flagsToTranslate & NotifyFilters.FileName) != 0) { flags |= Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsFile | Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsSymlink | Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemCreated | Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemRemoved | Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemRenamed; } return flags; } private sealed class RunningInstance { // Flags used to create the event stream private const Interop.EventStream.FSEventStreamCreateFlags EventStreamFlags = (Interop.EventStream.FSEventStreamCreateFlags.kFSEventStreamCreateFlagFileEvents | Interop.EventStream.FSEventStreamCreateFlags.kFSEventStreamCreateFlagNoDefer | Interop.EventStream.FSEventStreamCreateFlags.kFSEventStreamCreateFlagWatchRoot); // Weak reference to the associated watcher. A weak reference is used so that the FileSystemWatcher may be collected and finalized, // causing an active operation to be torn down. private readonly WeakReference<FileSystemWatcher> _weakWatcher; // The user can input relative paths, which can muck with our path comparisons. Save off the // actual full path so we can use it for comparing private string _fullDirectory; // Boolean if we allow events from nested folders private bool _includeChildren; // The bitmask of events that we want to send to the user private Interop.EventStream.FSEventStreamEventFlags _filterFlags; // The EventStream to listen for events on private SafeEventStreamHandle _eventStream; // A reference to the RunLoop that we can use to start or stop a Watcher private CFRunLoopRef _watcherRunLoop; // Callback delegate for the EventStream events private Interop.EventStream.FSEventStreamCallback _callback; // Token to monitor for cancellation requests, upon which processing is stopped and all // state is cleaned up. private readonly CancellationToken _cancellationToken; // Calling RunLoopStop multiple times SegFaults so protect the call to it private bool _stopping; internal RunningInstance( FileSystemWatcher watcher, string directory, bool includeChildren, Interop.EventStream.FSEventStreamEventFlags filter, CancellationToken cancelToken) { Debug.Assert(string.IsNullOrEmpty(directory) == false); Debug.Assert(!cancelToken.IsCancellationRequested); _weakWatcher = new WeakReference<FileSystemWatcher>(watcher); _fullDirectory = System.IO.Path.GetFullPath(directory); _includeChildren = includeChildren; _filterFlags = filter; _cancellationToken = cancelToken; _cancellationToken.Register(obj => ((RunningInstance)obj).CancellationCallback(), this); _stopping = false; } private void CancellationCallback() { if (!_stopping) { _stopping = true; // Stop the FS event message pump Interop.RunLoop.CFRunLoopStop(_watcherRunLoop); } } internal void Start() { // Normalize the _fullDirectory path to have a trailing slash if (_fullDirectory[_fullDirectory.Length - 1] != '/') _fullDirectory += "/"; // Make sure _fullPath doesn't contain a link or alias // since the OS will give back the actual, non link'd or alias'd paths _fullDirectory = Interop.Sys.RealPath(_fullDirectory); if (_fullDirectory == null) { throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), _fullDirectory, true); } // Get the path to watch and verify we created the CFStringRef SafeCreateHandle path = Interop.CoreFoundation.CFStringCreateWithCString(_fullDirectory); if (path.IsInvalid) { throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), _fullDirectory, true); } // Take the CFStringRef and put it into an array to pass to the EventStream SafeCreateHandle arrPaths = Interop.CoreFoundation.CFArrayCreate(new CFStringRef[1] { path.DangerousGetHandle() }, 1); if (arrPaths.IsInvalid) { path.Dispose(); throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), _fullDirectory, true); } // Create the callback for the EventStream if it wasn't previously created for this instance. if (_callback == null) { _callback = new Interop.EventStream.FSEventStreamCallback(FileSystemEventCallback); } // Make sure the OS file buffer(s) are fully flushed so we don't get events from cached I/O Interop.Sys.Sync(); // Create the event stream for the path and tell the stream to watch for file system events. _eventStream = Interop.EventStream.FSEventStreamCreate( _callback, arrPaths, Interop.EventStream.kFSEventStreamEventIdSinceNow, 0.0f, EventStreamFlags); if (_eventStream.IsInvalid) { arrPaths.Dispose(); path.Dispose(); throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), _fullDirectory, true); } // Create and start our watcher thread then wait for the thread to initialize and start // the RunLoop. We wait for that to prevent this function from returning before the RunLoop // has a chance to start so that any callers won't race with the background thread's initialization // and calling Stop, which would attempt to stop a RunLoop that hasn't started yet. var runLoopStarted = new ManualResetEventSlim(); new Thread(WatchForFileSystemEventsThreadStart) { IsBackground = true }.Start(runLoopStarted); runLoopStarted.Wait(); } private void WatchForFileSystemEventsThreadStart(object arg) { var runLoopStarted = (ManualResetEventSlim)arg; // Get this thread's RunLoop _watcherRunLoop = Interop.RunLoop.CFRunLoopGetCurrent(); Debug.Assert(_watcherRunLoop != IntPtr.Zero); // Schedule the EventStream to run on the thread's RunLoop Interop.EventStream.FSEventStreamScheduleWithRunLoop(_eventStream, _watcherRunLoop, Interop.RunLoop.kCFRunLoopDefaultMode); try { bool started = Interop.EventStream.FSEventStreamStart(_eventStream); // Notify the StartRaisingEvents call that we are initialized and about to start // so that it can return and avoid a race-condition around multiple threads calling Stop and Start runLoopStarted.Set(); if (started) { // Start the OS X RunLoop (a blocking call) that will pump file system changes into the callback function Interop.RunLoop.CFRunLoopRun(); // When we get here, we've requested to stop so cleanup the EventStream and unschedule from the RunLoop Interop.EventStream.FSEventStreamStop(_eventStream); } else { // Try to get the Watcher to raise the error event; if we can't do that, just silently exist since the watcher is gone anyway FileSystemWatcher watcher; if (_weakWatcher.TryGetTarget(out watcher)) { // An error occurred while trying to start the run loop so fail out watcher.OnError(new ErrorEventArgs(new IOException(SR.EventStream_FailedToStart, Marshal.GetLastWin32Error()))); } } } finally { // Always unschedule the RunLoop before cleaning up Interop.EventStream.FSEventStreamUnscheduleFromRunLoop(_eventStream, _watcherRunLoop, Interop.RunLoop.kCFRunLoopDefaultMode); } } private void FileSystemEventCallback( FSEventStreamRef streamRef, IntPtr clientCallBackInfo, size_t numEvents, String[] eventPaths, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] Interop.EventStream.FSEventStreamEventFlags[] eventFlags, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] FSEventStreamEventId[] eventIds) { Debug.Assert((numEvents.ToInt32() == eventPaths.Length) && (numEvents.ToInt32() == eventFlags.Length) && (numEvents.ToInt32() == eventIds.Length)); // Try to get the actual watcher from our weak reference. We maintain a weak reference most of the time // so as to avoid a rooted cycle that would prevent our processing loop from ever ending // if the watcher is dropped by the user without being disposed. If we can't get the watcher, // there's nothing more to do (we can't raise events), so bail. FileSystemWatcher watcher; if (!_weakWatcher.TryGetTarget(out watcher)) { CancellationCallback(); return; } // Since renames come in pairs, when we find the first we need to search for the next one. Once we find it, we'll add it to this // list so when the for-loop comes across it, we'll skip it since it's already been processed as part of the original of the pair. List<FSEventStreamEventId> handledRenameEvents = null; for (long i = 0; i < numEvents.ToInt32(); i++) { // Match Windows and don't notify us about changes to the Root folder string path = eventPaths[i]; if (path.Equals(_fullDirectory, StringComparison.OrdinalIgnoreCase)) { continue; } // First, we should check if this event should kick off a re-scan since we can't really rely on anything after this point if that is true if (ShouldRescanOccur(eventFlags[i])) { watcher.OnError(new ErrorEventArgs(new IOException(SR.FSW_BufferOverflow, (int)eventFlags[i]))); break; } else if ((handledRenameEvents != null) && (handledRenameEvents.Contains(eventIds[i]))) { // If this event is the second in a rename pair then skip it continue; } else if ((CheckIfPathIsNested(path)) && ((_filterFlags & eventFlags[i]) != 0)) { // The base FileSystemWatcher does a match check against the relative path before combining with // the root dir; however, null is special cased to signify the root dir, so check if we should use that. string relativePath = null; if (eventPaths[i].Equals(_fullDirectory, StringComparison.OrdinalIgnoreCase) == false) { // Remove the root directory to get the relative path relativePath = eventPaths[i].Remove(0, _fullDirectory.Length); } // Check if this is a rename if (IsFlagSet(eventFlags[i], Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemRenamed)) { // Find the rename that is paired to this rename, which should be the next rename in the list long pairedId = FindRenameChangePairedChange(i, eventPaths, eventFlags, eventIds); if (pairedId == long.MinValue) { // Getting here means we have a rename without a pair, meaning it should be a create for the // move from unwatched folder to watcher folder scenario or a move from the watcher folder out. // Check if the item exists on disk to check which it is WatcherChangeTypes wct = DoesItemExist(eventPaths[i], IsFlagSet(eventFlags[i], Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsFile)) ? WatcherChangeTypes.Created : WatcherChangeTypes.Deleted; watcher.NotifyFileSystemEventArgs(wct, relativePath); } else { // Remove the base directory prefix and add the paired event to the list of // events to skip and notify the user of the rename string newPathRelativeName = eventPaths[pairedId].Remove(0, _fullDirectory.Length); watcher.NotifyRenameEventArgs(WatcherChangeTypes.Renamed, newPathRelativeName, relativePath); // Create a new list, if necessary, and add the event if (handledRenameEvents == null) { handledRenameEvents = new List<FSEventStreamEventId>(); } handledRenameEvents.Add(eventIds[pairedId]); } } else { // OS X is wonky where it can give back kFSEventStreamEventFlagItemCreated and kFSEventStreamEventFlagItemRemoved // for the same item. The only option we have is to stat and see if the item exists; if so send created, otherwise send deleted. if ((IsFlagSet(eventFlags[i], Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemCreated)) || (IsFlagSet(eventFlags[i], Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemRemoved))) { WatcherChangeTypes wct = DoesItemExist(eventPaths[i], IsFlagSet(eventFlags[i], Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsFile)) ? WatcherChangeTypes.Created : WatcherChangeTypes.Deleted; watcher.NotifyFileSystemEventArgs(wct, relativePath); } if (IsFlagSet(eventFlags[i], Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemInodeMetaMod) || IsFlagSet(eventFlags[i], Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemModified) || IsFlagSet(eventFlags[i], Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemFinderInfoMod) || IsFlagSet(eventFlags[i], Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemChangeOwner) || IsFlagSet(eventFlags[i], Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemXattrMod)) { // Everything else is a modification watcher.NotifyFileSystemEventArgs(WatcherChangeTypes.Changed, relativePath); } } } } } private bool ShouldRescanOccur(Interop.EventStream.FSEventStreamEventFlags flags) { // Check if any bit is set that signals that the caller should rescan return (IsFlagSet(flags, Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagMustScanSubDirs) || IsFlagSet(flags, Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagUserDropped) || IsFlagSet(flags, Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagKernelDropped) || IsFlagSet(flags, Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagRootChanged) || IsFlagSet(flags, Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagMount) || IsFlagSet(flags, Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagUnmount)); } private bool CheckIfPathIsNested(string eventPath) { bool doesPathPass = true; // If we shouldn't include subdirectories, check if this path's parent is the watch directory if (_includeChildren == false) { // Check if the parent is the root. If so, then we'll continue processing based on the name. // If it isn't, then this will be set to false and we'll skip the name processing since it's irrelevant. string parent = System.IO.Path.GetDirectoryName(eventPath); doesPathPass = (parent.Equals(_fullDirectory, StringComparison.OrdinalIgnoreCase)); } return doesPathPass; } private long FindRenameChangePairedChange( long currentIndex, String[] eventPaths, Interop.EventStream.FSEventStreamEventFlags[] eventFlags, FSEventStreamEventId[] eventIds) { // Start at one past the current index and try to find the next Rename item, which should be the old path. for (long i = currentIndex + 1; i < eventPaths.Length; i++) { if (IsFlagSet(eventFlags[i], Interop.EventStream.FSEventStreamEventFlags.kFSEventStreamEventFlagItemRenamed)) { // We found match, stop looking return i; } } return long.MinValue; } private static bool IsFlagSet(Interop.EventStream.FSEventStreamEventFlags flags, Interop.EventStream.FSEventStreamEventFlags value) { return (value & flags) == value; } private static bool DoesItemExist(string path, bool isFile) { if (isFile) return File.Exists(path); else return Directory.Exists(path); } } } }
// Copyright (C) 2014 dot42 // // Original filename: Javax.Microedition.Khronos.Egl.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 Javax.Microedition.Khronos.Egl { /// <java-name> /// javax/microedition/khronos/egl/EGLConfig /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGLConfig", AccessFlags = 1057)] public abstract partial class EGLConfig /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public EGLConfig() /* MethodBuilder.Create */ { } } /// <java-name> /// javax/microedition/khronos/egl/EGL10 /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGL10", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IEGL10Constants /* scope: __dot42__ */ { /// <java-name> /// EGL_SUCCESS /// </java-name> [Dot42.DexImport("EGL_SUCCESS", "I", AccessFlags = 25)] public const int EGL_SUCCESS = 12288; /// <java-name> /// EGL_NOT_INITIALIZED /// </java-name> [Dot42.DexImport("EGL_NOT_INITIALIZED", "I", AccessFlags = 25)] public const int EGL_NOT_INITIALIZED = 12289; /// <java-name> /// EGL_BAD_ACCESS /// </java-name> [Dot42.DexImport("EGL_BAD_ACCESS", "I", AccessFlags = 25)] public const int EGL_BAD_ACCESS = 12290; /// <java-name> /// EGL_BAD_ALLOC /// </java-name> [Dot42.DexImport("EGL_BAD_ALLOC", "I", AccessFlags = 25)] public const int EGL_BAD_ALLOC = 12291; /// <java-name> /// EGL_BAD_ATTRIBUTE /// </java-name> [Dot42.DexImport("EGL_BAD_ATTRIBUTE", "I", AccessFlags = 25)] public const int EGL_BAD_ATTRIBUTE = 12292; /// <java-name> /// EGL_BAD_CONFIG /// </java-name> [Dot42.DexImport("EGL_BAD_CONFIG", "I", AccessFlags = 25)] public const int EGL_BAD_CONFIG = 12293; /// <java-name> /// EGL_BAD_CONTEXT /// </java-name> [Dot42.DexImport("EGL_BAD_CONTEXT", "I", AccessFlags = 25)] public const int EGL_BAD_CONTEXT = 12294; /// <java-name> /// EGL_BAD_CURRENT_SURFACE /// </java-name> [Dot42.DexImport("EGL_BAD_CURRENT_SURFACE", "I", AccessFlags = 25)] public const int EGL_BAD_CURRENT_SURFACE = 12295; /// <java-name> /// EGL_BAD_DISPLAY /// </java-name> [Dot42.DexImport("EGL_BAD_DISPLAY", "I", AccessFlags = 25)] public const int EGL_BAD_DISPLAY = 12296; /// <java-name> /// EGL_BAD_MATCH /// </java-name> [Dot42.DexImport("EGL_BAD_MATCH", "I", AccessFlags = 25)] public const int EGL_BAD_MATCH = 12297; /// <java-name> /// EGL_BAD_NATIVE_PIXMAP /// </java-name> [Dot42.DexImport("EGL_BAD_NATIVE_PIXMAP", "I", AccessFlags = 25)] public const int EGL_BAD_NATIVE_PIXMAP = 12298; /// <java-name> /// EGL_BAD_NATIVE_WINDOW /// </java-name> [Dot42.DexImport("EGL_BAD_NATIVE_WINDOW", "I", AccessFlags = 25)] public const int EGL_BAD_NATIVE_WINDOW = 12299; /// <java-name> /// EGL_BAD_PARAMETER /// </java-name> [Dot42.DexImport("EGL_BAD_PARAMETER", "I", AccessFlags = 25)] public const int EGL_BAD_PARAMETER = 12300; /// <java-name> /// EGL_BAD_SURFACE /// </java-name> [Dot42.DexImport("EGL_BAD_SURFACE", "I", AccessFlags = 25)] public const int EGL_BAD_SURFACE = 12301; /// <java-name> /// EGL_BUFFER_SIZE /// </java-name> [Dot42.DexImport("EGL_BUFFER_SIZE", "I", AccessFlags = 25)] public const int EGL_BUFFER_SIZE = 12320; /// <java-name> /// EGL_ALPHA_SIZE /// </java-name> [Dot42.DexImport("EGL_ALPHA_SIZE", "I", AccessFlags = 25)] public const int EGL_ALPHA_SIZE = 12321; /// <java-name> /// EGL_BLUE_SIZE /// </java-name> [Dot42.DexImport("EGL_BLUE_SIZE", "I", AccessFlags = 25)] public const int EGL_BLUE_SIZE = 12322; /// <java-name> /// EGL_GREEN_SIZE /// </java-name> [Dot42.DexImport("EGL_GREEN_SIZE", "I", AccessFlags = 25)] public const int EGL_GREEN_SIZE = 12323; /// <java-name> /// EGL_RED_SIZE /// </java-name> [Dot42.DexImport("EGL_RED_SIZE", "I", AccessFlags = 25)] public const int EGL_RED_SIZE = 12324; /// <java-name> /// EGL_DEPTH_SIZE /// </java-name> [Dot42.DexImport("EGL_DEPTH_SIZE", "I", AccessFlags = 25)] public const int EGL_DEPTH_SIZE = 12325; /// <java-name> /// EGL_STENCIL_SIZE /// </java-name> [Dot42.DexImport("EGL_STENCIL_SIZE", "I", AccessFlags = 25)] public const int EGL_STENCIL_SIZE = 12326; /// <java-name> /// EGL_CONFIG_CAVEAT /// </java-name> [Dot42.DexImport("EGL_CONFIG_CAVEAT", "I", AccessFlags = 25)] public const int EGL_CONFIG_CAVEAT = 12327; /// <java-name> /// EGL_CONFIG_ID /// </java-name> [Dot42.DexImport("EGL_CONFIG_ID", "I", AccessFlags = 25)] public const int EGL_CONFIG_ID = 12328; /// <java-name> /// EGL_LEVEL /// </java-name> [Dot42.DexImport("EGL_LEVEL", "I", AccessFlags = 25)] public const int EGL_LEVEL = 12329; /// <java-name> /// EGL_MAX_PBUFFER_HEIGHT /// </java-name> [Dot42.DexImport("EGL_MAX_PBUFFER_HEIGHT", "I", AccessFlags = 25)] public const int EGL_MAX_PBUFFER_HEIGHT = 12330; /// <java-name> /// EGL_MAX_PBUFFER_PIXELS /// </java-name> [Dot42.DexImport("EGL_MAX_PBUFFER_PIXELS", "I", AccessFlags = 25)] public const int EGL_MAX_PBUFFER_PIXELS = 12331; /// <java-name> /// EGL_MAX_PBUFFER_WIDTH /// </java-name> [Dot42.DexImport("EGL_MAX_PBUFFER_WIDTH", "I", AccessFlags = 25)] public const int EGL_MAX_PBUFFER_WIDTH = 12332; /// <java-name> /// EGL_NATIVE_RENDERABLE /// </java-name> [Dot42.DexImport("EGL_NATIVE_RENDERABLE", "I", AccessFlags = 25)] public const int EGL_NATIVE_RENDERABLE = 12333; /// <java-name> /// EGL_NATIVE_VISUAL_ID /// </java-name> [Dot42.DexImport("EGL_NATIVE_VISUAL_ID", "I", AccessFlags = 25)] public const int EGL_NATIVE_VISUAL_ID = 12334; /// <java-name> /// EGL_NATIVE_VISUAL_TYPE /// </java-name> [Dot42.DexImport("EGL_NATIVE_VISUAL_TYPE", "I", AccessFlags = 25)] public const int EGL_NATIVE_VISUAL_TYPE = 12335; /// <java-name> /// EGL_SAMPLES /// </java-name> [Dot42.DexImport("EGL_SAMPLES", "I", AccessFlags = 25)] public const int EGL_SAMPLES = 12337; /// <java-name> /// EGL_SAMPLE_BUFFERS /// </java-name> [Dot42.DexImport("EGL_SAMPLE_BUFFERS", "I", AccessFlags = 25)] public const int EGL_SAMPLE_BUFFERS = 12338; /// <java-name> /// EGL_SURFACE_TYPE /// </java-name> [Dot42.DexImport("EGL_SURFACE_TYPE", "I", AccessFlags = 25)] public const int EGL_SURFACE_TYPE = 12339; /// <java-name> /// EGL_TRANSPARENT_TYPE /// </java-name> [Dot42.DexImport("EGL_TRANSPARENT_TYPE", "I", AccessFlags = 25)] public const int EGL_TRANSPARENT_TYPE = 12340; /// <java-name> /// EGL_TRANSPARENT_BLUE_VALUE /// </java-name> [Dot42.DexImport("EGL_TRANSPARENT_BLUE_VALUE", "I", AccessFlags = 25)] public const int EGL_TRANSPARENT_BLUE_VALUE = 12341; /// <java-name> /// EGL_TRANSPARENT_GREEN_VALUE /// </java-name> [Dot42.DexImport("EGL_TRANSPARENT_GREEN_VALUE", "I", AccessFlags = 25)] public const int EGL_TRANSPARENT_GREEN_VALUE = 12342; /// <java-name> /// EGL_TRANSPARENT_RED_VALUE /// </java-name> [Dot42.DexImport("EGL_TRANSPARENT_RED_VALUE", "I", AccessFlags = 25)] public const int EGL_TRANSPARENT_RED_VALUE = 12343; /// <java-name> /// EGL_NONE /// </java-name> [Dot42.DexImport("EGL_NONE", "I", AccessFlags = 25)] public const int EGL_NONE = 12344; /// <java-name> /// EGL_LUMINANCE_SIZE /// </java-name> [Dot42.DexImport("EGL_LUMINANCE_SIZE", "I", AccessFlags = 25)] public const int EGL_LUMINANCE_SIZE = 12349; /// <java-name> /// EGL_ALPHA_MASK_SIZE /// </java-name> [Dot42.DexImport("EGL_ALPHA_MASK_SIZE", "I", AccessFlags = 25)] public const int EGL_ALPHA_MASK_SIZE = 12350; /// <java-name> /// EGL_COLOR_BUFFER_TYPE /// </java-name> [Dot42.DexImport("EGL_COLOR_BUFFER_TYPE", "I", AccessFlags = 25)] public const int EGL_COLOR_BUFFER_TYPE = 12351; /// <java-name> /// EGL_RENDERABLE_TYPE /// </java-name> [Dot42.DexImport("EGL_RENDERABLE_TYPE", "I", AccessFlags = 25)] public const int EGL_RENDERABLE_TYPE = 12352; /// <java-name> /// EGL_SLOW_CONFIG /// </java-name> [Dot42.DexImport("EGL_SLOW_CONFIG", "I", AccessFlags = 25)] public const int EGL_SLOW_CONFIG = 12368; /// <java-name> /// EGL_NON_CONFORMANT_CONFIG /// </java-name> [Dot42.DexImport("EGL_NON_CONFORMANT_CONFIG", "I", AccessFlags = 25)] public const int EGL_NON_CONFORMANT_CONFIG = 12369; /// <java-name> /// EGL_TRANSPARENT_RGB /// </java-name> [Dot42.DexImport("EGL_TRANSPARENT_RGB", "I", AccessFlags = 25)] public const int EGL_TRANSPARENT_RGB = 12370; /// <java-name> /// EGL_RGB_BUFFER /// </java-name> [Dot42.DexImport("EGL_RGB_BUFFER", "I", AccessFlags = 25)] public const int EGL_RGB_BUFFER = 12430; /// <java-name> /// EGL_LUMINANCE_BUFFER /// </java-name> [Dot42.DexImport("EGL_LUMINANCE_BUFFER", "I", AccessFlags = 25)] public const int EGL_LUMINANCE_BUFFER = 12431; /// <java-name> /// EGL_VENDOR /// </java-name> [Dot42.DexImport("EGL_VENDOR", "I", AccessFlags = 25)] public const int EGL_VENDOR = 12371; /// <java-name> /// EGL_VERSION /// </java-name> [Dot42.DexImport("EGL_VERSION", "I", AccessFlags = 25)] public const int EGL_VERSION = 12372; /// <java-name> /// EGL_EXTENSIONS /// </java-name> [Dot42.DexImport("EGL_EXTENSIONS", "I", AccessFlags = 25)] public const int EGL_EXTENSIONS = 12373; /// <java-name> /// EGL_HEIGHT /// </java-name> [Dot42.DexImport("EGL_HEIGHT", "I", AccessFlags = 25)] public const int EGL_HEIGHT = 12374; /// <java-name> /// EGL_WIDTH /// </java-name> [Dot42.DexImport("EGL_WIDTH", "I", AccessFlags = 25)] public const int EGL_WIDTH = 12375; /// <java-name> /// EGL_LARGEST_PBUFFER /// </java-name> [Dot42.DexImport("EGL_LARGEST_PBUFFER", "I", AccessFlags = 25)] public const int EGL_LARGEST_PBUFFER = 12376; /// <java-name> /// EGL_RENDER_BUFFER /// </java-name> [Dot42.DexImport("EGL_RENDER_BUFFER", "I", AccessFlags = 25)] public const int EGL_RENDER_BUFFER = 12422; /// <java-name> /// EGL_COLORSPACE /// </java-name> [Dot42.DexImport("EGL_COLORSPACE", "I", AccessFlags = 25)] public const int EGL_COLORSPACE = 12423; /// <java-name> /// EGL_ALPHA_FORMAT /// </java-name> [Dot42.DexImport("EGL_ALPHA_FORMAT", "I", AccessFlags = 25)] public const int EGL_ALPHA_FORMAT = 12424; /// <java-name> /// EGL_HORIZONTAL_RESOLUTION /// </java-name> [Dot42.DexImport("EGL_HORIZONTAL_RESOLUTION", "I", AccessFlags = 25)] public const int EGL_HORIZONTAL_RESOLUTION = 12432; /// <java-name> /// EGL_VERTICAL_RESOLUTION /// </java-name> [Dot42.DexImport("EGL_VERTICAL_RESOLUTION", "I", AccessFlags = 25)] public const int EGL_VERTICAL_RESOLUTION = 12433; /// <java-name> /// EGL_PIXEL_ASPECT_RATIO /// </java-name> [Dot42.DexImport("EGL_PIXEL_ASPECT_RATIO", "I", AccessFlags = 25)] public const int EGL_PIXEL_ASPECT_RATIO = 12434; /// <java-name> /// EGL_SINGLE_BUFFER /// </java-name> [Dot42.DexImport("EGL_SINGLE_BUFFER", "I", AccessFlags = 25)] public const int EGL_SINGLE_BUFFER = 12421; /// <java-name> /// EGL_CORE_NATIVE_ENGINE /// </java-name> [Dot42.DexImport("EGL_CORE_NATIVE_ENGINE", "I", AccessFlags = 25)] public const int EGL_CORE_NATIVE_ENGINE = 12379; /// <java-name> /// EGL_DRAW /// </java-name> [Dot42.DexImport("EGL_DRAW", "I", AccessFlags = 25)] public const int EGL_DRAW = 12377; /// <java-name> /// EGL_READ /// </java-name> [Dot42.DexImport("EGL_READ", "I", AccessFlags = 25)] public const int EGL_READ = 12378; /// <java-name> /// EGL_DONT_CARE /// </java-name> [Dot42.DexImport("EGL_DONT_CARE", "I", AccessFlags = 25)] public const int EGL_DONT_CARE = -1; /// <java-name> /// EGL_PBUFFER_BIT /// </java-name> [Dot42.DexImport("EGL_PBUFFER_BIT", "I", AccessFlags = 25)] public const int EGL_PBUFFER_BIT = 1; /// <java-name> /// EGL_PIXMAP_BIT /// </java-name> [Dot42.DexImport("EGL_PIXMAP_BIT", "I", AccessFlags = 25)] public const int EGL_PIXMAP_BIT = 2; /// <java-name> /// EGL_WINDOW_BIT /// </java-name> [Dot42.DexImport("EGL_WINDOW_BIT", "I", AccessFlags = 25)] public const int EGL_WINDOW_BIT = 4; /// <java-name> /// EGL_DEFAULT_DISPLAY /// </java-name> [Dot42.DexImport("EGL_DEFAULT_DISPLAY", "Ljava/lang/Object;", AccessFlags = 25)] public static readonly object EGL_DEFAULT_DISPLAY; /// <java-name> /// EGL_NO_DISPLAY /// </java-name> [Dot42.DexImport("EGL_NO_DISPLAY", "Ljavax/microedition/khronos/egl/EGLDisplay;", AccessFlags = 25)] public static readonly global::Javax.Microedition.Khronos.Egl.EGLDisplay EGL_NO_DISPLAY; /// <java-name> /// EGL_NO_CONTEXT /// </java-name> [Dot42.DexImport("EGL_NO_CONTEXT", "Ljavax/microedition/khronos/egl/EGLContext;", AccessFlags = 25)] public static readonly global::Javax.Microedition.Khronos.Egl.EGLContext EGL_NO_CONTEXT; /// <java-name> /// EGL_NO_SURFACE /// </java-name> [Dot42.DexImport("EGL_NO_SURFACE", "Ljavax/microedition/khronos/egl/EGLSurface;", AccessFlags = 25)] public static readonly global::Javax.Microedition.Khronos.Egl.EGLSurface EGL_NO_SURFACE; } /// <java-name> /// javax/microedition/khronos/egl/EGL10 /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGL10", AccessFlags = 1537)] public partial interface IEGL10 : global::Javax.Microedition.Khronos.Egl.IEGL /* scope: __dot42__ */ { /// <java-name> /// eglChooseConfig /// </java-name> [Dot42.DexImport("eglChooseConfig", "(Ljavax/microedition/khronos/egl/EGLDisplay;[I[Ljavax/microedition/khronos/egl/EG" + "LConfig;I[I)Z", AccessFlags = 1025)] bool EglChooseConfig(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, int[] attrib_list, global::Javax.Microedition.Khronos.Egl.EGLConfig[] configs, int config_size, int[] num_config) /* MethodBuilder.Create */ ; /// <java-name> /// eglCopyBuffers /// </java-name> [Dot42.DexImport("eglCopyBuffers", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSu" + "rface;Ljava/lang/Object;)Z", AccessFlags = 1025)] bool EglCopyBuffers(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLSurface surface, object native_pixmap) /* MethodBuilder.Create */ ; /// <java-name> /// eglCreateContext /// </java-name> [Dot42.DexImport("eglCreateContext", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" + "nfig;Ljavax/microedition/khronos/egl/EGLContext;[I)Ljavax/microedition/khronos/e" + "gl/EGLContext;", AccessFlags = 1025)] global::Javax.Microedition.Khronos.Egl.EGLContext EglCreateContext(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig config, global::Javax.Microedition.Khronos.Egl.EGLContext share_context, int[] attrib_list) /* MethodBuilder.Create */ ; /// <java-name> /// eglCreatePbufferSurface /// </java-name> [Dot42.DexImport("eglCreatePbufferSurface", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" + "nfig;[I)Ljavax/microedition/khronos/egl/EGLSurface;", AccessFlags = 1025)] global::Javax.Microedition.Khronos.Egl.EGLSurface EglCreatePbufferSurface(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig config, int[] attrib_list) /* MethodBuilder.Create */ ; /// <java-name> /// eglCreatePixmapSurface /// </java-name> [Dot42.DexImport("eglCreatePixmapSurface", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" + "nfig;Ljava/lang/Object;[I)Ljavax/microedition/khronos/egl/EGLSurface;", AccessFlags = 1025)] global::Javax.Microedition.Khronos.Egl.EGLSurface EglCreatePixmapSurface(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig config, object native_pixmap, int[] attrib_list) /* MethodBuilder.Create */ ; /// <java-name> /// eglCreateWindowSurface /// </java-name> [Dot42.DexImport("eglCreateWindowSurface", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" + "nfig;Ljava/lang/Object;[I)Ljavax/microedition/khronos/egl/EGLSurface;", AccessFlags = 1025)] global::Javax.Microedition.Khronos.Egl.EGLSurface EglCreateWindowSurface(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig config, object native_window, int[] attrib_list) /* MethodBuilder.Create */ ; /// <java-name> /// eglDestroyContext /// </java-name> [Dot42.DexImport("eglDestroyContext", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" + "ntext;)Z", AccessFlags = 1025)] bool EglDestroyContext(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLContext context) /* MethodBuilder.Create */ ; /// <java-name> /// eglDestroySurface /// </java-name> [Dot42.DexImport("eglDestroySurface", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSu" + "rface;)Z", AccessFlags = 1025)] bool EglDestroySurface(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLSurface surface) /* MethodBuilder.Create */ ; /// <java-name> /// eglGetConfigAttrib /// </java-name> [Dot42.DexImport("eglGetConfigAttrib", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" + "nfig;I[I)Z", AccessFlags = 1025)] bool EglGetConfigAttrib(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig config, int attribute, int[] value) /* MethodBuilder.Create */ ; /// <java-name> /// eglGetConfigs /// </java-name> [Dot42.DexImport("eglGetConfigs", "(Ljavax/microedition/khronos/egl/EGLDisplay;[Ljavax/microedition/khronos/egl/EGLC" + "onfig;I[I)Z", AccessFlags = 1025)] bool EglGetConfigs(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig[] configs, int config_size, int[] num_config) /* MethodBuilder.Create */ ; /// <java-name> /// eglGetCurrentContext /// </java-name> [Dot42.DexImport("eglGetCurrentContext", "()Ljavax/microedition/khronos/egl/EGLContext;", AccessFlags = 1025)] global::Javax.Microedition.Khronos.Egl.EGLContext EglGetCurrentContext() /* MethodBuilder.Create */ ; /// <java-name> /// eglGetCurrentDisplay /// </java-name> [Dot42.DexImport("eglGetCurrentDisplay", "()Ljavax/microedition/khronos/egl/EGLDisplay;", AccessFlags = 1025)] global::Javax.Microedition.Khronos.Egl.EGLDisplay EglGetCurrentDisplay() /* MethodBuilder.Create */ ; /// <java-name> /// eglGetCurrentSurface /// </java-name> [Dot42.DexImport("eglGetCurrentSurface", "(I)Ljavax/microedition/khronos/egl/EGLSurface;", AccessFlags = 1025)] global::Javax.Microedition.Khronos.Egl.EGLSurface EglGetCurrentSurface(int readdraw) /* MethodBuilder.Create */ ; /// <java-name> /// eglGetDisplay /// </java-name> [Dot42.DexImport("eglGetDisplay", "(Ljava/lang/Object;)Ljavax/microedition/khronos/egl/EGLDisplay;", AccessFlags = 1025)] global::Javax.Microedition.Khronos.Egl.EGLDisplay EglGetDisplay(object native_display) /* MethodBuilder.Create */ ; /// <java-name> /// eglGetError /// </java-name> [Dot42.DexImport("eglGetError", "()I", AccessFlags = 1025)] int EglGetError() /* MethodBuilder.Create */ ; /// <java-name> /// eglInitialize /// </java-name> [Dot42.DexImport("eglInitialize", "(Ljavax/microedition/khronos/egl/EGLDisplay;[I)Z", AccessFlags = 1025)] bool EglInitialize(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, int[] major_minor) /* MethodBuilder.Create */ ; /// <java-name> /// eglMakeCurrent /// </java-name> [Dot42.DexImport("eglMakeCurrent", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSu" + "rface;Ljavax/microedition/khronos/egl/EGLSurface;Ljavax/microedition/khronos/egl" + "/EGLContext;)Z", AccessFlags = 1025)] bool EglMakeCurrent(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLSurface draw, global::Javax.Microedition.Khronos.Egl.EGLSurface read, global::Javax.Microedition.Khronos.Egl.EGLContext context) /* MethodBuilder.Create */ ; /// <java-name> /// eglQueryContext /// </java-name> [Dot42.DexImport("eglQueryContext", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" + "ntext;I[I)Z", AccessFlags = 1025)] bool EglQueryContext(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLContext context, int attribute, int[] value) /* MethodBuilder.Create */ ; /// <java-name> /// eglQueryString /// </java-name> [Dot42.DexImport("eglQueryString", "(Ljavax/microedition/khronos/egl/EGLDisplay;I)Ljava/lang/String;", AccessFlags = 1025)] string EglQueryString(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, int name) /* MethodBuilder.Create */ ; /// <java-name> /// eglQuerySurface /// </java-name> [Dot42.DexImport("eglQuerySurface", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSu" + "rface;I[I)Z", AccessFlags = 1025)] bool EglQuerySurface(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLSurface surface, int attribute, int[] value) /* MethodBuilder.Create */ ; /// <java-name> /// eglSwapBuffers /// </java-name> [Dot42.DexImport("eglSwapBuffers", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSu" + "rface;)Z", AccessFlags = 1025)] bool EglSwapBuffers(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLSurface surface) /* MethodBuilder.Create */ ; /// <java-name> /// eglTerminate /// </java-name> [Dot42.DexImport("eglTerminate", "(Ljavax/microedition/khronos/egl/EGLDisplay;)Z", AccessFlags = 1025)] bool EglTerminate(global::Javax.Microedition.Khronos.Egl.EGLDisplay display) /* MethodBuilder.Create */ ; /// <java-name> /// eglWaitGL /// </java-name> [Dot42.DexImport("eglWaitGL", "()Z", AccessFlags = 1025)] bool EglWaitGL() /* MethodBuilder.Create */ ; /// <java-name> /// eglWaitNative /// </java-name> [Dot42.DexImport("eglWaitNative", "(ILjava/lang/Object;)Z", AccessFlags = 1025)] bool EglWaitNative(int engine, object bindTarget) /* MethodBuilder.Create */ ; } /// <java-name> /// javax/microedition/khronos/egl/EGLDisplay /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGLDisplay", AccessFlags = 1057)] public abstract partial class EGLDisplay /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public EGLDisplay() /* MethodBuilder.Create */ { } } /// <java-name> /// javax/microedition/khronos/egl/EGLSurface /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGLSurface", AccessFlags = 1057)] public abstract partial class EGLSurface /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public EGLSurface() /* MethodBuilder.Create */ { } } /// <java-name> /// javax/microedition/khronos/egl/EGL11 /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGL11", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IEGL11Constants /* scope: __dot42__ */ { /// <java-name> /// EGL_CONTEXT_LOST /// </java-name> [Dot42.DexImport("EGL_CONTEXT_LOST", "I", AccessFlags = 25)] public const int EGL_CONTEXT_LOST = 12302; } /// <java-name> /// javax/microedition/khronos/egl/EGL11 /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGL11", AccessFlags = 1537)] public partial interface IEGL11 : global::Javax.Microedition.Khronos.Egl.IEGL10 /* scope: __dot42__ */ { } /// <java-name> /// javax/microedition/khronos/egl/EGLContext /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGLContext", AccessFlags = 1057)] public abstract partial class EGLContext /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public EGLContext() /* MethodBuilder.Create */ { } /// <java-name> /// getEGL /// </java-name> [Dot42.DexImport("getEGL", "()Ljavax/microedition/khronos/egl/EGL;", AccessFlags = 9)] public static global::Javax.Microedition.Khronos.Egl.IEGL GetEGL() /* MethodBuilder.Create */ { return default(global::Javax.Microedition.Khronos.Egl.IEGL); } /// <java-name> /// getGL /// </java-name> [Dot42.DexImport("getGL", "()Ljavax/microedition/khronos/opengles/GL;", AccessFlags = 1025)] public abstract global::Javax.Microedition.Khronos.Opengles.IGL GetGL() /* MethodBuilder.Create */ ; /// <java-name> /// getEGL /// </java-name> public static global::Javax.Microedition.Khronos.Egl.IEGL EGL { [Dot42.DexImport("getEGL", "()Ljavax/microedition/khronos/egl/EGL;", AccessFlags = 9)] get{ return GetEGL(); } } /// <java-name> /// getGL /// </java-name> public global::Javax.Microedition.Khronos.Opengles.IGL GL { [Dot42.DexImport("getGL", "()Ljavax/microedition/khronos/opengles/GL;", AccessFlags = 1025)] get{ return GetGL(); } } } /// <java-name> /// javax/microedition/khronos/egl/EGL /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGL", AccessFlags = 1537)] public partial interface IEGL /* scope: __dot42__ */ { } }
namespace Azure.Messaging.EventHubs { public partial class EventData { public EventData(System.BinaryData eventBody) { } protected EventData(System.BinaryData eventBody, System.Collections.Generic.IDictionary<string, object> properties = null, System.Collections.Generic.IReadOnlyDictionary<string, object> systemProperties = null, long sequenceNumber = (long)-9223372036854775808, long offset = (long)-9223372036854775808, System.DateTimeOffset enqueuedTime = default(System.DateTimeOffset), string partitionKey = null) { } public EventData(System.ReadOnlyMemory<byte> eventBody) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] protected EventData(System.ReadOnlyMemory<byte> eventBody, System.Collections.Generic.IDictionary<string, object> properties = null, System.Collections.Generic.IReadOnlyDictionary<string, object> systemProperties = null, long sequenceNumber = (long)-9223372036854775808, long offset = (long)-9223372036854775808, System.DateTimeOffset enqueuedTime = default(System.DateTimeOffset), string partitionKey = null) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public System.ReadOnlyMemory<byte> Body { get { throw null; } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public System.IO.Stream BodyAsStream { get { throw null; } } public System.DateTimeOffset EnqueuedTime { get { throw null; } } public System.BinaryData EventBody { get { throw null; } } public long Offset { get { throw null; } } public string PartitionKey { get { throw null; } } public System.Collections.Generic.IDictionary<string, object> Properties { get { throw null; } } public long SequenceNumber { get { throw null; } } public System.Collections.Generic.IReadOnlyDictionary<string, object> SystemProperties { get { throw null; } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class EventHubConnection : System.IAsyncDisposable { protected EventHubConnection() { } public EventHubConnection(string connectionString) { } public EventHubConnection(string connectionString, Azure.Messaging.EventHubs.EventHubConnectionOptions connectionOptions) { } public EventHubConnection(string connectionString, string eventHubName) { } public EventHubConnection(string fullyQualifiedNamespace, string eventHubName, Azure.Core.TokenCredential credential, Azure.Messaging.EventHubs.EventHubConnectionOptions connectionOptions = null) { } public EventHubConnection(string connectionString, string eventHubName, Azure.Messaging.EventHubs.EventHubConnectionOptions connectionOptions) { } public string EventHubName { get { throw null; } } public string FullyQualifiedNamespace { get { throw null; } } public bool IsClosed { get { throw null; } } public virtual System.Threading.Tasks.Task CloseAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.ValueTask DisposeAsync() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class EventHubConnectionOptions { public EventHubConnectionOptions() { } public System.Uri CustomEndpointAddress { get { throw null; } set { } } public System.Net.IWebProxy Proxy { get { throw null; } set { } } public Azure.Messaging.EventHubs.EventHubsTransportType TransportType { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class EventHubProperties { protected internal EventHubProperties(string name, System.DateTimeOffset createdOn, string[] partitionIds) { } public System.DateTimeOffset CreatedOn { get { throw null; } } public string Name { get { throw null; } } public string[] PartitionIds { get { throw null; } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class EventHubsConnectionStringProperties { public EventHubsConnectionStringProperties() { } public System.Uri Endpoint { get { throw null; } } public string EventHubName { get { throw null; } } public string FullyQualifiedNamespace { get { throw null; } } public string SharedAccessKey { get { throw null; } } public string SharedAccessKeyName { get { throw null; } } public string SharedAccessSignature { get { throw null; } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static Azure.Messaging.EventHubs.EventHubsConnectionStringProperties Parse(string connectionString) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class EventHubsException : System.Exception { public EventHubsException(bool isTransient, string eventHubName) { } public EventHubsException(bool isTransient, string eventHubName, Azure.Messaging.EventHubs.EventHubsException.FailureReason reason) { } public EventHubsException(bool isTransient, string eventHubName, string message) { } public EventHubsException(bool isTransient, string eventHubName, string message, Azure.Messaging.EventHubs.EventHubsException.FailureReason reason) { } public EventHubsException(bool isTransient, string eventHubName, string message, Azure.Messaging.EventHubs.EventHubsException.FailureReason reason, System.Exception innerException) { } public EventHubsException(bool isTransient, string eventHubName, string message, System.Exception innerException) { } public EventHubsException(string eventHubName, string message, Azure.Messaging.EventHubs.EventHubsException.FailureReason reason) { } public string EventHubName { get { throw null; } } public bool IsTransient { get { throw null; } } public override string Message { get { throw null; } } public Azure.Messaging.EventHubs.EventHubsException.FailureReason Reason { get { throw null; } } public override string ToString() { throw null; } public enum FailureReason { GeneralError = 0, ClientClosed = 1, ConsumerDisconnected = 2, ResourceNotFound = 3, MessageSizeExceeded = 4, QuotaExceeded = 5, ServiceBusy = 6, ServiceTimeout = 7, ServiceCommunicationProblem = 8, ProducerDisconnected = 9, InvalidClientState = 10, } } public static partial class EventHubsModelFactory { public static Azure.Messaging.EventHubs.EventData EventData(System.BinaryData eventBody, System.Collections.Generic.IDictionary<string, object> properties = null, System.Collections.Generic.IReadOnlyDictionary<string, object> systemProperties = null, string partitionKey = null, long sequenceNumber = (long)-9223372036854775808, long offset = (long)-9223372036854775808, System.DateTimeOffset enqueuedTime = default(System.DateTimeOffset)) { throw null; } public static Azure.Messaging.EventHubs.Producer.EventDataBatch EventDataBatch(long batchSizeBytes, System.Collections.Generic.IList<Azure.Messaging.EventHubs.EventData> batchEventStore, Azure.Messaging.EventHubs.Producer.CreateBatchOptions batchOptions = null, System.Func<Azure.Messaging.EventHubs.EventData, bool> tryAddCallback = null) { throw null; } public static Azure.Messaging.EventHubs.EventHubProperties EventHubProperties(string name, System.DateTimeOffset createdOn, string[] partitionIds) { throw null; } public static Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties LastEnqueuedEventProperties(long? lastSequenceNumber, long? lastOffset, System.DateTimeOffset? lastEnqueuedTime, System.DateTimeOffset? lastReceivedTime) { throw null; } public static Azure.Messaging.EventHubs.Consumer.PartitionContext PartitionContext(string partitionId, Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties lastEnqueuedEventProperties = default(Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties)) { throw null; } public static Azure.Messaging.EventHubs.PartitionProperties PartitionProperties(string eventHubName, string partitionId, bool isEmpty, long beginningSequenceNumber, long lastSequenceNumber, long lastOffset, System.DateTimeOffset lastEnqueuedTime) { throw null; } } public enum EventHubsRetryMode { Fixed = 0, Exponential = 1, } public partial class EventHubsRetryOptions { public EventHubsRetryOptions() { } public Azure.Messaging.EventHubs.EventHubsRetryPolicy CustomRetryPolicy { get { throw null; } set { } } public System.TimeSpan Delay { get { throw null; } set { } } public System.TimeSpan MaximumDelay { get { throw null; } set { } } public int MaximumRetries { get { throw null; } set { } } public Azure.Messaging.EventHubs.EventHubsRetryMode Mode { get { throw null; } set { } } public System.TimeSpan TryTimeout { get { throw null; } set { } } } public abstract partial class EventHubsRetryPolicy { protected EventHubsRetryPolicy() { } public abstract System.TimeSpan? CalculateRetryDelay(System.Exception lastException, int attemptCount); public abstract System.TimeSpan CalculateTryTimeout(int attemptCount); [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public enum EventHubsTransportType { AmqpTcp = 0, AmqpWebSockets = 1, } public partial class PartitionProperties { protected internal PartitionProperties(string eventHubName, string partitionId, bool isEmpty, long beginningSequenceNumber, long lastSequenceNumber, long lastOffset, System.DateTimeOffset lastEnqueuedTime) { } public long BeginningSequenceNumber { get { throw null; } } public string EventHubName { get { throw null; } } public string Id { get { throw null; } } public bool IsEmpty { get { throw null; } } public long LastEnqueuedOffset { get { throw null; } } public long LastEnqueuedSequenceNumber { get { throw null; } } public System.DateTimeOffset LastEnqueuedTime { get { throw null; } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } } namespace Azure.Messaging.EventHubs.Consumer { public partial class EventHubConsumerClient : System.IAsyncDisposable { public const string DefaultConsumerGroupName = "$Default"; protected EventHubConsumerClient() { } public EventHubConsumerClient(string consumerGroup, Azure.Messaging.EventHubs.EventHubConnection connection, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions clientOptions = null) { } public EventHubConsumerClient(string consumerGroup, string connectionString) { } public EventHubConsumerClient(string consumerGroup, string connectionString, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions clientOptions) { } public EventHubConsumerClient(string consumerGroup, string connectionString, string eventHubName) { } public EventHubConsumerClient(string consumerGroup, string fullyQualifiedNamespace, string eventHubName, Azure.Core.TokenCredential credential, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions clientOptions = null) { } public EventHubConsumerClient(string consumerGroup, string connectionString, string eventHubName, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions clientOptions) { } public string ConsumerGroup { get { throw null; } } public string EventHubName { get { throw null; } } public string FullyQualifiedNamespace { get { throw null; } } public bool IsClosed { get { throw null; } protected set { } } public virtual System.Threading.Tasks.Task CloseAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.ValueTask DisposeAsync() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Messaging.EventHubs.EventHubProperties> GetEventHubPropertiesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public virtual System.Threading.Tasks.Task<string[]> GetPartitionIdsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Messaging.EventHubs.PartitionProperties> GetPartitionPropertiesAsync(string partitionId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Collections.Generic.IAsyncEnumerable<Azure.Messaging.EventHubs.Consumer.PartitionEvent> ReadEventsAsync(Azure.Messaging.EventHubs.Consumer.ReadEventOptions readOptions, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Collections.Generic.IAsyncEnumerable<Azure.Messaging.EventHubs.Consumer.PartitionEvent> ReadEventsAsync(bool startReadingAtEarliestEvent, Azure.Messaging.EventHubs.Consumer.ReadEventOptions readOptions = null, [System.Runtime.CompilerServices.EnumeratorCancellationAttribute] System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Collections.Generic.IAsyncEnumerable<Azure.Messaging.EventHubs.Consumer.PartitionEvent> ReadEventsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Collections.Generic.IAsyncEnumerable<Azure.Messaging.EventHubs.Consumer.PartitionEvent> ReadEventsFromPartitionAsync(string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition startingPosition, Azure.Messaging.EventHubs.Consumer.ReadEventOptions readOptions, [System.Runtime.CompilerServices.EnumeratorCancellationAttribute] System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Collections.Generic.IAsyncEnumerable<Azure.Messaging.EventHubs.Consumer.PartitionEvent> ReadEventsFromPartitionAsync(string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition startingPosition, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class EventHubConsumerClientOptions { public EventHubConsumerClientOptions() { } public Azure.Messaging.EventHubs.EventHubConnectionOptions ConnectionOptions { get { throw null; } set { } } public Azure.Messaging.EventHubs.EventHubsRetryOptions RetryOptions { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct EventPosition : System.IEquatable<Azure.Messaging.EventHubs.Consumer.EventPosition> { private object _dummy; private int _dummyPrimitive; public static Azure.Messaging.EventHubs.Consumer.EventPosition Earliest { get { throw null; } } public static Azure.Messaging.EventHubs.Consumer.EventPosition Latest { get { throw null; } } public bool Equals(Azure.Messaging.EventHubs.Consumer.EventPosition other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } public static Azure.Messaging.EventHubs.Consumer.EventPosition FromEnqueuedTime(System.DateTimeOffset enqueuedTime) { throw null; } public static Azure.Messaging.EventHubs.Consumer.EventPosition FromOffset(long offset, bool isInclusive = true) { throw null; } public static Azure.Messaging.EventHubs.Consumer.EventPosition FromSequenceNumber(long sequenceNumber, bool isInclusive = true) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Messaging.EventHubs.Consumer.EventPosition left, Azure.Messaging.EventHubs.Consumer.EventPosition right) { throw null; } public static bool operator !=(Azure.Messaging.EventHubs.Consumer.EventPosition left, Azure.Messaging.EventHubs.Consumer.EventPosition right) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct LastEnqueuedEventProperties : System.IEquatable<Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties> { public LastEnqueuedEventProperties(long? lastSequenceNumber, long? lastOffset, System.DateTimeOffset? lastEnqueuedTime, System.DateTimeOffset? lastReceivedTime) { throw null; } public System.DateTimeOffset? EnqueuedTime { get { throw null; } } public System.DateTimeOffset? LastReceivedTime { get { throw null; } } public long? Offset { get { throw null; } } public long? SequenceNumber { get { throw null; } } public bool Equals(Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties left, Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties right) { throw null; } public static bool operator !=(Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties left, Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties right) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class PartitionContext { protected internal PartitionContext(string partitionId) { } public string PartitionId { get { throw null; } } public virtual Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties ReadLastEnqueuedEventProperties() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct PartitionEvent { private object _dummy; private int _dummyPrimitive; public PartitionEvent(Azure.Messaging.EventHubs.Consumer.PartitionContext partition, Azure.Messaging.EventHubs.EventData data) { throw null; } public Azure.Messaging.EventHubs.EventData Data { get { throw null; } } public Azure.Messaging.EventHubs.Consumer.PartitionContext Partition { get { throw null; } } } public partial class ReadEventOptions { public ReadEventOptions() { } public int CacheEventCount { get { throw null; } set { } } public System.TimeSpan? MaximumWaitTime { get { throw null; } set { } } public long? OwnerLevel { get { throw null; } set { } } public int PrefetchCount { get { throw null; } set { } } public long? PrefetchSizeInBytes { get { throw null; } set { } } public bool TrackLastEnqueuedEventProperties { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } } namespace Azure.Messaging.EventHubs.Primitives { public partial class EventProcessorCheckpoint { public EventProcessorCheckpoint() { } public string ConsumerGroup { get { throw null; } set { } } public string EventHubName { get { throw null; } set { } } public string FullyQualifiedNamespace { get { throw null; } set { } } public string PartitionId { get { throw null; } set { } } public Azure.Messaging.EventHubs.Consumer.EventPosition StartingPosition { get { throw null; } set { } } } public partial class EventProcessorOptions { public EventProcessorOptions() { } public Azure.Messaging.EventHubs.EventHubConnectionOptions ConnectionOptions { get { throw null; } set { } } public Azure.Messaging.EventHubs.Consumer.EventPosition DefaultStartingPosition { get { throw null; } set { } } public string Identifier { get { throw null; } set { } } public Azure.Messaging.EventHubs.Processor.LoadBalancingStrategy LoadBalancingStrategy { get { throw null; } set { } } public System.TimeSpan LoadBalancingUpdateInterval { get { throw null; } set { } } public System.TimeSpan? MaximumWaitTime { get { throw null; } set { } } public System.TimeSpan PartitionOwnershipExpirationInterval { get { throw null; } set { } } public int PrefetchCount { get { throw null; } set { } } public long? PrefetchSizeInBytes { get { throw null; } set { } } public Azure.Messaging.EventHubs.EventHubsRetryOptions RetryOptions { get { throw null; } set { } } public bool TrackLastEnqueuedEventProperties { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class EventProcessorPartition { public EventProcessorPartition() { } public string PartitionId { get { throw null; } protected internal set { } } } public partial class EventProcessorPartitionOwnership { public EventProcessorPartitionOwnership() { } public string ConsumerGroup { get { throw null; } set { } } public string EventHubName { get { throw null; } set { } } public string FullyQualifiedNamespace { get { throw null; } set { } } public System.DateTimeOffset LastModifiedTime { get { throw null; } set { } } public string OwnerIdentifier { get { throw null; } set { } } public string PartitionId { get { throw null; } set { } } public string Version { get { throw null; } set { } } } public abstract partial class EventProcessor<TPartition> where TPartition : Azure.Messaging.EventHubs.Primitives.EventProcessorPartition, new() { protected EventProcessor() { } protected EventProcessor(int eventBatchMaximumCount, string consumerGroup, string connectionString, Azure.Messaging.EventHubs.Primitives.EventProcessorOptions options = null) { } protected EventProcessor(int eventBatchMaximumCount, string consumerGroup, string fullyQualifiedNamespace, string eventHubName, Azure.Core.TokenCredential credential, Azure.Messaging.EventHubs.Primitives.EventProcessorOptions options = null) { } protected EventProcessor(int eventBatchMaximumCount, string consumerGroup, string connectionString, string eventHubName, Azure.Messaging.EventHubs.Primitives.EventProcessorOptions options = null) { } public string ConsumerGroup { get { throw null; } } public string EventHubName { get { throw null; } } public string FullyQualifiedNamespace { get { throw null; } } public string Identifier { get { throw null; } } public bool IsRunning { get { throw null; } protected set { } } protected Azure.Messaging.EventHubs.EventHubsRetryPolicy RetryPolicy { get { throw null; } } protected abstract System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.Primitives.EventProcessorPartitionOwnership>> ClaimOwnershipAsync(System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.Primitives.EventProcessorPartitionOwnership> desiredOwnership, System.Threading.CancellationToken cancellationToken); protected internal virtual Azure.Messaging.EventHubs.EventHubConnection CreateConnection() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } protected virtual System.Threading.Tasks.Task<Azure.Messaging.EventHubs.Primitives.EventProcessorCheckpoint> GetCheckpointAsync(string partitionId, System.Threading.CancellationToken cancellationToken) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } protected abstract System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.Primitives.EventProcessorCheckpoint>> ListCheckpointsAsync(System.Threading.CancellationToken cancellationToken); protected abstract System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.Primitives.EventProcessorPartitionOwnership>> ListOwnershipAsync(System.Threading.CancellationToken cancellationToken); protected virtual System.Threading.Tasks.Task OnInitializingPartitionAsync(TPartition partition, System.Threading.CancellationToken cancellationToken) { throw null; } protected virtual System.Threading.Tasks.Task OnPartitionProcessingStoppedAsync(TPartition partition, Azure.Messaging.EventHubs.Processor.ProcessingStoppedReason reason, System.Threading.CancellationToken cancellationToken) { throw null; } protected abstract System.Threading.Tasks.Task OnProcessingErrorAsync(System.Exception exception, TPartition partition, string operationDescription, System.Threading.CancellationToken cancellationToken); protected abstract System.Threading.Tasks.Task OnProcessingEventBatchAsync(System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.EventData> events, TPartition partition, System.Threading.CancellationToken cancellationToken); protected virtual Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties ReadLastEnqueuedEventProperties(string partitionId) { throw null; } public virtual void StartProcessing(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { } public virtual System.Threading.Tasks.Task StartProcessingAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual void StopProcessing(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { } public virtual System.Threading.Tasks.Task StopProcessingAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class PartitionReceiver : System.IAsyncDisposable { protected PartitionReceiver() { } public PartitionReceiver(string consumerGroup, string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition eventPosition, Azure.Messaging.EventHubs.EventHubConnection connection, Azure.Messaging.EventHubs.Primitives.PartitionReceiverOptions options = null) { } public PartitionReceiver(string consumerGroup, string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition eventPosition, string connectionString, Azure.Messaging.EventHubs.Primitives.PartitionReceiverOptions options = null) { } public PartitionReceiver(string consumerGroup, string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition eventPosition, string fullyQualifiedNamespace, string eventHubName, Azure.Core.TokenCredential credential, Azure.Messaging.EventHubs.Primitives.PartitionReceiverOptions options = null) { } public PartitionReceiver(string consumerGroup, string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition eventPosition, string connectionString, string eventHubName, Azure.Messaging.EventHubs.Primitives.PartitionReceiverOptions options = null) { } public string ConsumerGroup { get { throw null; } } public string EventHubName { get { throw null; } } public string FullyQualifiedNamespace { get { throw null; } } public Azure.Messaging.EventHubs.Consumer.EventPosition InitialPosition { get { throw null; } } public bool IsClosed { get { throw null; } protected set { } } public string PartitionId { get { throw null; } } public virtual System.Threading.Tasks.Task CloseAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.ValueTask DisposeAsync() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public virtual System.Threading.Tasks.Task<Azure.Messaging.EventHubs.PartitionProperties> GetPartitionPropertiesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Messaging.EventHubs.Consumer.LastEnqueuedEventProperties ReadLastEnqueuedEventProperties() { throw null; } public virtual System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.EventData>> ReceiveBatchAsync(int maximumEventCount, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.EventData>> ReceiveBatchAsync(int maximumEventCount, System.TimeSpan maximumWaitTime, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class PartitionReceiverOptions { public PartitionReceiverOptions() { } public Azure.Messaging.EventHubs.EventHubConnectionOptions ConnectionOptions { get { throw null; } set { } } public System.TimeSpan? DefaultMaximumReceiveWaitTime { get { throw null; } set { } } public long? OwnerLevel { get { throw null; } set { } } public int PrefetchCount { get { throw null; } set { } } public long? PrefetchSizeInBytes { get { throw null; } set { } } public Azure.Messaging.EventHubs.EventHubsRetryOptions RetryOptions { get { throw null; } set { } } public bool TrackLastEnqueuedEventProperties { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } } namespace Azure.Messaging.EventHubs.Processor { public enum LoadBalancingStrategy { Balanced = 0, Greedy = 1, } public partial class PartitionClosingEventArgs { public PartitionClosingEventArgs(string partitionId, Azure.Messaging.EventHubs.Processor.ProcessingStoppedReason reason, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { } public System.Threading.CancellationToken CancellationToken { get { throw null; } } public string PartitionId { get { throw null; } } public Azure.Messaging.EventHubs.Processor.ProcessingStoppedReason Reason { get { throw null; } } } public partial class PartitionInitializingEventArgs { public PartitionInitializingEventArgs(string partitionId, Azure.Messaging.EventHubs.Consumer.EventPosition defaultStartingPosition, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { } public System.Threading.CancellationToken CancellationToken { get { throw null; } } public Azure.Messaging.EventHubs.Consumer.EventPosition DefaultStartingPosition { get { throw null; } set { } } public string PartitionId { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct ProcessErrorEventArgs { private object _dummy; private int _dummyPrimitive; public ProcessErrorEventArgs(string partitionId, string operation, System.Exception exception, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public System.Threading.CancellationToken CancellationToken { get { throw null; } } public System.Exception Exception { get { throw null; } } public string Operation { get { throw null; } } public string PartitionId { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct ProcessEventArgs { private object _dummy; private int _dummyPrimitive; public ProcessEventArgs(Azure.Messaging.EventHubs.Consumer.PartitionContext partition, Azure.Messaging.EventHubs.EventData data, System.Func<System.Threading.CancellationToken, System.Threading.Tasks.Task> updateCheckpointImplementation, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public System.Threading.CancellationToken CancellationToken { get { throw null; } } public Azure.Messaging.EventHubs.EventData Data { get { throw null; } } public bool HasEvent { get { throw null; } } public Azure.Messaging.EventHubs.Consumer.PartitionContext Partition { get { throw null; } } public System.Threading.Tasks.Task UpdateCheckpointAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public enum ProcessingStoppedReason { Shutdown = 0, OwnershipLost = 1, } } namespace Azure.Messaging.EventHubs.Producer { public partial class CreateBatchOptions : Azure.Messaging.EventHubs.Producer.SendEventOptions { public CreateBatchOptions() { } public long? MaximumSizeInBytes { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public sealed partial class EventDataBatch : System.IDisposable { internal EventDataBatch() { } public int Count { get { throw null; } } public long MaximumSizeInBytes { get { throw null; } } public long SizeInBytes { get { throw null; } } public void Dispose() { } public bool TryAdd(Azure.Messaging.EventHubs.EventData eventData) { throw null; } } public partial class EventHubProducerClient : System.IAsyncDisposable { protected EventHubProducerClient() { } public EventHubProducerClient(Azure.Messaging.EventHubs.EventHubConnection connection, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions clientOptions = null) { } public EventHubProducerClient(string connectionString) { } public EventHubProducerClient(string connectionString, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions clientOptions) { } public EventHubProducerClient(string connectionString, string eventHubName) { } public EventHubProducerClient(string fullyQualifiedNamespace, string eventHubName, Azure.Core.TokenCredential credential, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions clientOptions = null) { } public EventHubProducerClient(string connectionString, string eventHubName, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions clientOptions) { } public string EventHubName { get { throw null; } } public string FullyQualifiedNamespace { get { throw null; } } public bool IsClosed { get { throw null; } protected set { } } public virtual System.Threading.Tasks.Task CloseAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.ValueTask<Azure.Messaging.EventHubs.Producer.EventDataBatch> CreateBatchAsync(Azure.Messaging.EventHubs.Producer.CreateBatchOptions options, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.ValueTask<Azure.Messaging.EventHubs.Producer.EventDataBatch> CreateBatchAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.ValueTask DisposeAsync() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Messaging.EventHubs.EventHubProperties> GetEventHubPropertiesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public virtual System.Threading.Tasks.Task<string[]> GetPartitionIdsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Messaging.EventHubs.PartitionProperties> GetPartitionPropertiesAsync(string partitionId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task SendAsync(Azure.Messaging.EventHubs.Producer.EventDataBatch eventBatch, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task SendAsync(System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.EventData> eventBatch, Azure.Messaging.EventHubs.Producer.SendEventOptions options, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task SendAsync(System.Collections.Generic.IEnumerable<Azure.Messaging.EventHubs.EventData> eventBatch, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class EventHubProducerClientOptions { public EventHubProducerClientOptions() { } public Azure.Messaging.EventHubs.EventHubConnectionOptions ConnectionOptions { get { throw null; } set { } } public Azure.Messaging.EventHubs.EventHubsRetryOptions RetryOptions { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class SendEventOptions { public SendEventOptions() { } public string PartitionId { get { throw null; } set { } } public string PartitionKey { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } } namespace Microsoft.Extensions.Azure { public static partial class EventHubClientBuilderExtensions { public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Consumer.EventHubConsumerClient, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions> AddEventHubConsumerClientWithNamespace<TBuilder>(this TBuilder builder, string consumerGroup, string fullyQualifiedNamespace, string eventHubName) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithCredential { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Consumer.EventHubConsumerClient, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions> AddEventHubConsumerClient<TBuilder>(this TBuilder builder, string consumerGroup, string connectionString) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Consumer.EventHubConsumerClient, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions> AddEventHubConsumerClient<TBuilder>(this TBuilder builder, string consumerGroup, string connectionString, string eventHubName) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Consumer.EventHubConsumerClient, Azure.Messaging.EventHubs.Consumer.EventHubConsumerClientOptions> AddEventHubConsumerClient<TBuilder, TConfiguration>(this TBuilder builder, TConfiguration configuration) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithConfiguration<TConfiguration> { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Producer.EventHubProducerClient, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions> AddEventHubProducerClientWithNamespace<TBuilder>(this TBuilder builder, string fullyQualifiedNamespace, string eventHubName) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithCredential { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Producer.EventHubProducerClient, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions> AddEventHubProducerClient<TBuilder>(this TBuilder builder, string connectionString) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Producer.EventHubProducerClient, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions> AddEventHubProducerClient<TBuilder>(this TBuilder builder, string connectionString, string eventHubName) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Messaging.EventHubs.Producer.EventHubProducerClient, Azure.Messaging.EventHubs.Producer.EventHubProducerClientOptions> AddEventHubProducerClient<TBuilder, TConfiguration>(this TBuilder builder, TConfiguration configuration) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithConfiguration<TConfiguration> { throw null; } } }
using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http.Authentication; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using MusicStore.Models; namespace MusicStore.Controllers { [Authorize] public class AccountController : Controller { private readonly ILogger<AccountController> _logger; public AccountController( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, ILogger<AccountController> logger) { UserManager = userManager; SignInManager = signInManager; _logger = logger; } public UserManager<ApplicationUser> UserManager { get; } public SignInManager<ApplicationUser> SignInManager { get; } // // GET: /Account/Login [AllowAnonymous] public IActionResult Login(string returnUrl = null) { ViewBag.ReturnUrl = returnUrl; return View(); } // // POST: /Account/Login [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null) { if (!ModelState.IsValid) { return View(model); } // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, change to lockoutOnFailure: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false); if (result.Succeeded) { _logger.LogInformation("Logged in {userName}.", model.Email); return RedirectToLocal(returnUrl); } if (result.RequiresTwoFactor) { return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); } if (result.IsLockedOut) { return View("Lockout"); } else { _logger.LogWarning("Failed to log in {userName}.", model.Email); ModelState.AddModelError("", "Invalid login attempt."); return View(model); } } // // GET: /Account/VerifyCode [AllowAnonymous] public async Task<ActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null) { var user = await SignInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return View("Error"); } // Remove before production #if DEMO if (user != null) { ViewBag.Code = await UserManager.GenerateTwoFactorTokenAsync(user, provider); } #endif return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe }); } // // POST: /Account/VerifyCode [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model) { if (!ModelState.IsValid) { return View(model); } // The following code protects for brute force attacks against the two factor codes. // If a user enters incorrect codes for a specified amount of time then the user account // will be locked out for a specified amount of time. // You can configure the account lockout settings in IdentityConfig var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser); if (result.Succeeded) { return RedirectToLocal(model.ReturnUrl); } if (result.IsLockedOut) { return View("Lockout"); } else { ModelState.AddModelError("", "Invalid code."); return View(model); } } // // GET: /Account/Register [AllowAnonymous] public IActionResult Register() { return View(); } // // POST: /Account/Register [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { _logger.LogInformation("User {userName} was created.", model.Email); //Bug: Remember browser option missing? //Uncomment this and comment the later part if account verification is not needed. //await SignInManager.SignInAsync(user, isPersistent: false); // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link string code = await UserManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); await MessageServices.SendEmailAsync(model.Email, "Confirm your account", "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>"); #if !DEMO return RedirectToAction("Index", "Home"); #else //To display the email link in a friendly page instead of sending email ViewBag.Link = callbackUrl; return View("DemoLinkDisplay"); #endif } AddErrors(result); } // If we got this far, something failed, redisplay form return View(model); } // // GET: /Account/ConfirmEmail [AllowAnonymous] public async Task<ActionResult> ConfirmEmail(string userId, string code) { if (userId == null || code == null) { return View("Error"); } var user = await UserManager.FindByIdAsync(userId); if (user == null) { return View("Error"); } var result = await UserManager.ConfirmEmailAsync(user, code); return View(result.Succeeded ? "ConfirmEmail" : "Error"); } // // GET: /Account/ForgotPassword [AllowAnonymous] public ActionResult ForgotPassword() { return View(); } // // POST: /Account/ForgotPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model) { if (ModelState.IsValid) { var user = await UserManager.FindByNameAsync(model.Email); if (user == null || !(await UserManager.IsEmailConfirmedAsync(user))) { // Don't reveal that the user does not exist or is not confirmed return View("ForgotPasswordConfirmation"); } // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link string code = await UserManager.GeneratePasswordResetTokenAsync(user); var callbackUrl = Url.Action("ResetPassword", "Account", new { code = code }, protocol: HttpContext.Request.Scheme); await MessageServices.SendEmailAsync(model.Email, "Reset Password", "Please reset your password by clicking here: <a href=\"" + callbackUrl + "\">link</a>"); #if !DEMO return RedirectToAction("ForgotPasswordConfirmation"); #else //To display the email link in a friendly page instead of sending email ViewBag.Link = callbackUrl; return View("DemoLinkDisplay"); #endif } ModelState.AddModelError("", string.Format("We could not locate an account with email : {0}", model.Email)); // If we got this far, something failed, redisplay form return View(model); } // // GET: /Account/ForgotPasswordConfirmation [AllowAnonymous] public ActionResult ForgotPasswordConfirmation() { return View(); } // // GET: /Account/ResetPassword [AllowAnonymous] public ActionResult ResetPassword(string code) { //TODO: Fix this? var resetPasswordViewModel = new ResetPasswordViewModel() { Code = code }; return code == null ? View("Error") : View(resetPasswordViewModel); } // // POST: /Account/ResetPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await UserManager.FindByNameAsync(model.Email); if (user == null) { // Don't reveal that the user does not exist return RedirectToAction("ResetPasswordConfirmation", "Account"); } var result = await UserManager.ResetPasswordAsync(user, model.Code, model.Password); if (result.Succeeded) { return RedirectToAction("ResetPasswordConfirmation", "Account"); } AddErrors(result); return View(); } // // GET: /Account/ResetPasswordConfirmation [AllowAnonymous] public ActionResult ResetPasswordConfirmation() { return View(); } // // POST: /Account/ExternalLogin [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public ActionResult ExternalLogin(string provider, string returnUrl = null) { // Request a redirect to the external login provider var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }); var properties = SignInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl); return new ChallengeResult(provider, properties); } // // GET: /Account/SendCode [AllowAnonymous] public async Task<ActionResult> SendCode(bool rememberMe, string returnUrl = null) { //TODO : Default rememberMe as well? var user = await SignInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return View("Error"); } var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(user); var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList(); return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe }); } // // POST: /Account/SendCode [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> SendCode(SendCodeViewModel model) { if (!ModelState.IsValid) { return View(); } var user = await SignInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return View("Error"); } // Generate the token and send it var code = await UserManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider); if (string.IsNullOrWhiteSpace(code)) { return View("Error"); } var message = "Your security code is: " + code; if (model.SelectedProvider == "Email") { await MessageServices.SendEmailAsync(await UserManager.GetEmailAsync(user), "Security Code", message); } else if (model.SelectedProvider == "Phone") { await MessageServices.SendSmsAsync(await UserManager.GetPhoneNumberAsync(user), message); } return RedirectToAction("VerifyCode", new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe }); } // // GET: /Account/ExternalLoginCallback [AllowAnonymous] public async Task<ActionResult> ExternalLoginCallback(string returnUrl = null) { var loginInfo = await SignInManager.GetExternalLoginInfoAsync(); if (loginInfo == null) { return RedirectToAction("Login"); } // Sign in the user with this external login provider if the user already has a login var result = await SignInManager.ExternalLoginSignInAsync(loginInfo.LoginProvider, loginInfo.ProviderKey, isPersistent: false); if (result.Succeeded) { return RedirectToLocal(returnUrl); } if (result.RequiresTwoFactor) { return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false }); } if (result.IsLockedOut) { return View("Lockout"); } else { // If the user does not have an account, then prompt the user to create an account ViewBag.ReturnUrl = returnUrl; ViewBag.LoginProvider = loginInfo.LoginProvider; // REVIEW: handle case where email not in claims? var email = loginInfo.Principal.FindFirstValue(ClaimTypes.Email); return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email }); } } // // POST: /Account/ExternalLoginConfirmation [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null) { if (SignInManager.IsSignedIn(User)) { return RedirectToAction("Index", "Manage"); } if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await SignInManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user); #if TESTING //Just for automated testing adding a claim named 'ManageStore' - Not required for production var manageClaim = info.Principal.Claims.Where(c => c.Type == "ManageStore").FirstOrDefault(); if (manageClaim != null) { await UserManager.AddClaimAsync(user, manageClaim); } #endif if (result.Succeeded) { result = await UserManager.AddLoginAsync(user, info); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent: false); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return View(model); } // // POST: /Account/LogOff [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> LogOff() { var userName = HttpContext.User.Identity.Name; // clear all items from the cart HttpContext.Session.Clear(); await SignInManager.SignOutAsync(); // TODO: Currently SignInManager.SignOut does not sign out OpenIdc and does not have a way to pass in a specific // AuthType to sign out. var appEnv = HttpContext.RequestServices.GetService<IHostingEnvironment>(); if (appEnv.EnvironmentName.StartsWith("OpenIdConnect")) { return new SignOutResult("OpenIdConnect", new AuthenticationProperties { RedirectUri = Url.Action("Index", "Home") }); } _logger.LogInformation("{userName} logged out.", userName); return RedirectToAction("Index", "Home"); } // // GET: /Account/ExternalLoginFailure [AllowAnonymous] public ActionResult ExternalLoginFailure() { return View(); } #region Helpers private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError("", error.Description); _logger.LogWarning("Error in creating user: {error}", error.Description); } } private Task<ApplicationUser> GetCurrentUserAsync() { return UserManager.GetUserAsync(HttpContext.User); } private ActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return RedirectToAction("Index", "Home"); } } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Diagnostics; using System.IO; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Ipc; using System.Runtime.Serialization.Formatters; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Interactive { /// <summary> /// Represents a process that hosts an interactive session. /// </summary> /// <remarks> /// Handles spawning of the host process and communication between the local callers and the remote session. /// </remarks> internal sealed partial class InteractiveHost : MarshalByRefObject { private readonly Type _replType; private readonly string _hostPath; private readonly string _initialWorkingDirectory; // adjustable for testing purposes private readonly int _millisecondsTimeout; private const int MaxAttemptsToCreateProcess = 2; private LazyRemoteService _lazyRemoteService; private int _remoteServiceInstanceId; // Remoting channel to communicate with the remote service. private IpcServerChannel _serverChannel; private TextWriter _output; private TextWriter _errorOutput; internal event Action<InteractiveHostOptions> ProcessStarting; public InteractiveHost( Type replType, string hostPath, string workingDirectory, int millisecondsTimeout = 5000) { _millisecondsTimeout = millisecondsTimeout; _output = TextWriter.Null; _errorOutput = TextWriter.Null; _replType = replType; _hostPath = hostPath; _initialWorkingDirectory = workingDirectory; var serverProvider = new BinaryServerFormatterSinkProvider { TypeFilterLevel = TypeFilterLevel.Full }; _serverChannel = new IpcServerChannel(GenerateUniqueChannelLocalName(), "ReplChannel-" + Guid.NewGuid(), serverProvider); ChannelServices.RegisterChannel(_serverChannel, ensureSecurity: false); } #region Test hooks internal event Action<char[], int> OutputReceived; internal event Action<char[], int> ErrorOutputReceived; internal Process TryGetProcess() { InitializedRemoteService initializedService; return (_lazyRemoteService?.InitializedService != null && _lazyRemoteService.InitializedService.TryGetValue(out initializedService)) ? initializedService.ServiceOpt.Process : null; } internal Service TryGetService() { var initializedService = TryGetOrCreateRemoteServiceAsync().Result; return initializedService.ServiceOpt?.Service; } // Triggered whenever we create a fresh process. // The ProcessExited event is not hooked yet. internal event Action<Process> InteractiveHostProcessCreated; internal IpcServerChannel _ServerChannel { get { return _serverChannel; } } internal void Dispose(bool joinThreads) { Dispose(joinThreads, disposing: true); } #endregion private static string GenerateUniqueChannelLocalName() { return typeof(InteractiveHost).FullName + Guid.NewGuid(); } public override object InitializeLifetimeService() { return null; } private RemoteService TryStartProcess(CancellationToken cancellationToken) { Process newProcess = null; int newProcessId = -1; Semaphore semaphore = null; try { int currentProcessId = Process.GetCurrentProcess().Id; bool semaphoreCreated; string semaphoreName; while (true) { semaphoreName = "InteractiveHostSemaphore-" + Guid.NewGuid(); semaphore = new Semaphore(0, 1, semaphoreName, out semaphoreCreated); if (semaphoreCreated) { break; } semaphore.Close(); cancellationToken.ThrowIfCancellationRequested(); } var remoteServerPort = "InteractiveHostChannel-" + Guid.NewGuid(); var processInfo = new ProcessStartInfo(_hostPath); processInfo.Arguments = remoteServerPort + " " + semaphoreName + " " + currentProcessId; processInfo.WorkingDirectory = _initialWorkingDirectory; processInfo.CreateNoWindow = true; processInfo.UseShellExecute = false; processInfo.RedirectStandardOutput = true; processInfo.RedirectStandardError = true; processInfo.StandardErrorEncoding = Encoding.UTF8; processInfo.StandardOutputEncoding = Encoding.UTF8; newProcess = new Process(); newProcess.StartInfo = processInfo; // enables Process.Exited event to be raised: newProcess.EnableRaisingEvents = true; newProcess.Start(); // test hook: var processCreated = InteractiveHostProcessCreated; if (processCreated != null) { processCreated(newProcess); } cancellationToken.ThrowIfCancellationRequested(); try { newProcessId = newProcess.Id; } catch { newProcessId = 0; } // sync: while (!semaphore.WaitOne(_millisecondsTimeout)) { if (!CheckAlive(newProcess)) { return null; } _output.WriteLine(FeaturesResources.AttemptToConnectToProcess, newProcessId); cancellationToken.ThrowIfCancellationRequested(); } // instantiate remote service: Service newService; try { newService = (Service)Activator.GetObject( typeof(Service), "ipc://" + remoteServerPort + "/" + Service.ServiceName); cancellationToken.ThrowIfCancellationRequested(); newService.Initialize(_replType); } catch (RemotingException) when (!CheckAlive(newProcess)) { return null; } return new RemoteService(this, newProcess, newProcessId, newService); } catch (OperationCanceledException) { if (newProcess != null) { RemoteService.InitiateTermination(newProcess, newProcessId); } return null; } finally { if (semaphore != null) { semaphore.Close(); } } } private bool CheckAlive(Process process) { bool alive = process.IsAlive(); if (!alive) { _errorOutput.WriteLine(FeaturesResources.FailedToLaunchProcess, _hostPath, process.ExitCode); _errorOutput.WriteLine(process.StandardError.ReadToEnd()); } return alive; } ~InteractiveHost() { Dispose(joinThreads: false, disposing: false); } public void Dispose() { Dispose(joinThreads: false, disposing: true); } private void Dispose(bool joinThreads, bool disposing) { if (disposing) { GC.SuppressFinalize(this); DisposeChannel(); } if (_lazyRemoteService != null) { _lazyRemoteService.Dispose(joinThreads); _lazyRemoteService = null; } } private void DisposeChannel() { if (_serverChannel != null) { ChannelServices.UnregisterChannel(_serverChannel); _serverChannel = null; } } public TextWriter Output { get { return _output; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } var oldOutput = Interlocked.Exchange(ref _output, value); oldOutput.Flush(); } } public TextWriter ErrorOutput { get { return _errorOutput; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } var oldOutput = Interlocked.Exchange(ref _errorOutput, value); oldOutput.Flush(); } } internal void OnOutputReceived(bool error, char[] buffer, int count) { var notification = error ? ErrorOutputReceived : OutputReceived; if (notification != null) { notification(buffer, count); } var writer = error ? ErrorOutput : Output; writer.Write(buffer, 0, count); } private LazyRemoteService CreateRemoteService(InteractiveHostOptions options, bool skipInitialization) { return new LazyRemoteService(this, options, Interlocked.Increment(ref _remoteServiceInstanceId), skipInitialization); } private Task OnProcessExited(Process process) { ReportProcessExited(process); return TryGetOrCreateRemoteServiceAsync(); } private void ReportProcessExited(Process process) { int? exitCode; try { exitCode = process.HasExited ? process.ExitCode : (int?)null; } catch { exitCode = null; } if (exitCode.HasValue) { _errorOutput.WriteLine(FeaturesResources.HostingProcessExitedWithExitCode, exitCode.Value); } } private async Task<InitializedRemoteService> TryGetOrCreateRemoteServiceAsync() { try { LazyRemoteService currentRemoteService = _lazyRemoteService; // disposed or not reset: Debug.Assert(currentRemoteService != null); for (int attempt = 0; attempt < MaxAttemptsToCreateProcess; attempt++) { var initializedService = await currentRemoteService.InitializedService.GetValueAsync(currentRemoteService.CancellationSource.Token).ConfigureAwait(false); if (initializedService.ServiceOpt != null && initializedService.ServiceOpt.Process.IsAlive()) { return initializedService; } // Service failed to start or initialize or the process died. var newService = CreateRemoteService(currentRemoteService.Options, skipInitialization: !initializedService.InitializationResult.Success); var previousService = Interlocked.CompareExchange(ref _lazyRemoteService, newService, currentRemoteService); if (previousService == currentRemoteService) { // we replaced the service whose process we know is dead: currentRemoteService.Dispose(joinThreads: false); currentRemoteService = newService; } else { // the process was reset in between our checks, try to use the new service: newService.Dispose(joinThreads: false); currentRemoteService = previousService; } } _errorOutput.WriteLine(FeaturesResources.UnableToCreateHostingProcess); } catch (OperationCanceledException) { // The user reset the process during initialization. // The reset operation will recreate the process. } catch (Exception e) when (FatalError.Report(e)) { throw ExceptionUtilities.Unreachable; } return default(InitializedRemoteService); } private async Task<TResult> Async<TResult>(Action<Service, RemoteAsyncOperation<TResult>> action) { try { var initializedService = await TryGetOrCreateRemoteServiceAsync().ConfigureAwait(false); if (initializedService.ServiceOpt == null) { return default(TResult); } return await new RemoteAsyncOperation<TResult>(initializedService.ServiceOpt).AsyncExecute(action).ConfigureAwait(false); } catch (Exception e) when (FatalError.Report(e)) { throw ExceptionUtilities.Unreachable; } } private static async Task<TResult> Async<TResult>(RemoteService remoteService, Action<Service, RemoteAsyncOperation<TResult>> action) { try { return await new RemoteAsyncOperation<TResult>(remoteService).AsyncExecute(action).ConfigureAwait(false); } catch (Exception e) when (FatalError.Report(e)) { throw ExceptionUtilities.Unreachable; } } #region Operations /// <summary> /// Restarts and reinitializes the host process (or starts a new one if it is not running yet). /// </summary> /// <param name="optionsOpt">The options to initialize the new process with, or null to use the current options (or default options if the process isn't running yet).</param> public async Task<RemoteExecutionResult> ResetAsync(InteractiveHostOptions optionsOpt) { try { // replace the existing service with a new one: var newService = CreateRemoteService(optionsOpt ?? _lazyRemoteService?.Options ?? InteractiveHostOptions.Default, skipInitialization: false); LazyRemoteService oldService = Interlocked.Exchange(ref _lazyRemoteService, newService); if (oldService != null) { oldService.Dispose(joinThreads: false); } var initializedService = await TryGetOrCreateRemoteServiceAsync().ConfigureAwait(false); if (initializedService.ServiceOpt == null) { return default(RemoteExecutionResult); } return initializedService.InitializationResult; } catch (Exception e) when (FatalError.Report(e)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Asynchronously executes given code in the remote interactive session. /// </summary> /// <param name="code">The code to execute.</param> /// <remarks> /// This method is thread safe. References can be added and source code executed in parallel. /// The operations are serialized to UI thread in the remote process in first come first served order. /// </remarks> public Task<RemoteExecutionResult> ExecuteAsync(string code) { Debug.Assert(code != null); return Async<RemoteExecutionResult>((service, operation) => service.ExecuteAsync(operation, code)); } /// <summary> /// Asynchronously executes given code in the remote interactive session. /// </summary> /// <param name="path">The file to execute.</param> /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception> /// <remarks> /// This method is thread safe. All session operations are serialized to UI thread in the remote process in first come first served order. /// </remarks> public Task<RemoteExecutionResult> ExecuteFileAsync(string path) { if (path == null) { throw new ArgumentNullException(nameof(path)); } return Async<RemoteExecutionResult>((service, operation) => service.ExecuteFileAsync(operation, path)); } /// <summary> /// Asynchronously adds a reference to the set of available references for next submission. /// </summary> /// <param name="reference">The reference to add.</param> /// <remarks> /// This method is thread safe. All session operations are serialized to UI thread in the remote process in first come first served order. /// </remarks> public Task<bool> AddReferenceAsync(string reference) { Debug.Assert(reference != null); return Async<bool>((service, operation) => service.AddReferenceAsync(operation, reference)); } /// <summary> /// Sets the current session's search paths and base directory. /// </summary> public Task SetPathsAsync(string[] referenceSearchPaths, string[] sourceSearchPaths, string baseDirectory) { Debug.Assert(referenceSearchPaths != null); Debug.Assert(sourceSearchPaths != null); Debug.Assert(baseDirectory != null); return Async<object>((service, operation) => service.SetPathsAsync(operation, referenceSearchPaths, sourceSearchPaths, baseDirectory)); } #endregion } }
//----------------------------------------------------------------------- // <copyright file="NameValueListBase.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://cslanet.com // </copyright> // <summary>This is the base class from which readonly name/value</summary> //----------------------------------------------------------------------- using System; using System.ComponentModel; using Csla.Properties; using Csla.Core; using Csla.Serialization.Mobile; namespace Csla { /// <summary> /// This is the base class from which readonly name/value /// collections should be derived. /// </summary> /// <typeparam name="K">Type of the key values.</typeparam> /// <typeparam name="V">Type of the values.</typeparam> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [Serializable] public abstract class NameValueListBase<K, V> : Core.ReadOnlyBindingList<NameValueListBase<K, V>.NameValuePair>, ICloneable, Core.IBusinessObject, Server.IDataPortalTarget { #region Core Implementation /// <summary> /// Returns the value corresponding to the /// specified key. /// </summary> /// <param name="key">Key value for which to retrieve a value.</param> public V Value(K key) { foreach (NameValuePair item in this) if (item.Key.Equals(key)) return item.Value; return default(V); } /// <summary> /// Returns the key corresponding to the /// first occurance of the specified value /// in the list. /// </summary> /// <param name="value">Value for which to retrieve the key.</param> public K Key(V value) { foreach (NameValuePair item in this) if (item.Value.Equals(value)) return item.Key; return default(K); } /// <summary> /// Gets a value indicating whether the list contains the /// specified key. /// </summary> /// <param name="key">Key value for which to search.</param> public bool ContainsKey(K key) { foreach (NameValuePair item in this) if (item.Key.Equals(key)) return true; return false; } /// <summary> /// Gets a value indicating whether the list contains the /// specified value. /// </summary> /// <param name="value">Value for which to search.</param> public bool ContainsValue(V value) { foreach (NameValuePair item in this) if (item.Value.Equals(value)) return true; return false; } /// <summary> /// Get the item for the first matching /// value in the collection. /// </summary> /// <param name="value"> /// Value to search for in the list. /// </param> /// <returns>Item from the list.</returns> public NameValuePair GetItemByValue(V value) { foreach (NameValuePair item in this) { if (item != null && item.Value.Equals(value)) { return item; } } return null; } /// <summary> /// Get the item for the first matching /// key in the collection. /// </summary> /// <param name="key"> /// Key to search for in the list. /// </param> /// <returns>Item from the list.</returns> public NameValuePair GetItemByKey(K key) { foreach (NameValuePair item in this) { if (item != null && item.Key.Equals(key)) { return item; } } return null; } #endregion #region Constructors /// <summary> /// Creates an instance of the object. /// </summary> protected NameValueListBase() { Initialize(); } #endregion #region Initialize /// <summary> /// Override this method to set up event handlers so user /// code in a partial class can respond to events raised by /// generated code. /// </summary> protected virtual void Initialize() { /* allows subclass to initialize events before any other activity occurs */ } #endregion #region NameValuePair class /// <summary> /// Contains a key and value pair. /// </summary> [Serializable()] public class NameValuePair : MobileObject { private K _key; private V _value; #if (ANDROID || IOS) || NETFX_CORE /// <summary> /// Creates an instance of the object. /// </summary> public NameValuePair() { } #else private NameValuePair() { } #endif /// <summary> /// The Key or Name value. /// </summary> public K Key { get { return _key; } } /// <summary> /// The Value corresponding to the key/name. /// </summary> public V Value { get { return _value; } } /// <summary> /// Creates an instance of the object. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public NameValuePair(K key, V value) { _key = key; _value = value; } /// <summary> /// Returns a string representation of the /// value for this item. /// </summary> public override string ToString() { return _value.ToString(); } /// <summary> /// Override this method to manually get custom field /// values from the serialization stream. /// </summary> /// <param name="info">Serialization info.</param> /// <param name="mode">Serialization mode.</param> protected override void OnGetState(SerializationInfo info, StateMode mode) { base.OnGetState(info, mode); info.AddValue("NameValuePair._key", _key); info.AddValue("NameValuePair._value", _value); } /// <summary> /// Override this method to manually set custom field /// values into the serialization stream. /// </summary> /// <param name="info">Serialization info.</param> /// <param name="mode">Serialization mode.</param> protected override void OnSetState(SerializationInfo info, StateMode mode) { base.OnSetState(info, mode); _key = info.GetValue<K>("NameValuePair._key"); _value = info.GetValue<V>("NameValuePair._value"); } } #endregion #region ICloneable object ICloneable.Clone() { return GetClone(); } /// <summary> /// Creates a clone of the object. /// </summary> /// <returns>A new object containing the exact data of the original object.</returns> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual object GetClone() { return Core.ObjectCloner.Clone(this); } /// <summary> /// Creates a clone of the object. /// </summary> public NameValueListBase<K, V> Clone() { return (NameValueListBase<K, V>)GetClone(); } #endregion #region Data Access [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "criteria")] private void DataPortal_Create(object criteria) { throw new NotSupportedException(Resources.CreateNotSupportedException); } /// <summary> /// Override this method to allow retrieval of an existing business /// object based on data in the database. /// </summary> /// <param name="criteria">An object containing criteria values to identify the object.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")] protected virtual void DataPortal_Fetch(object criteria) { throw new NotSupportedException(Resources.FetchNotSupportedException); } private void DataPortal_Update() { throw new NotSupportedException(Resources.UpdateNotSupportedException); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "criteria")] private void DataPortal_Delete(object criteria) { throw new NotSupportedException(Resources.DeleteNotSupportedException); } /// <summary> /// Called by the server-side DataPortal prior to calling the /// requested DataPortal_XYZ method. /// </summary> /// <param name="e">The DataPortalContext object passed to the DataPortal.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")] [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void DataPortal_OnDataPortalInvoke(DataPortalEventArgs e) { } /// <summary> /// Called by the server-side DataPortal after calling the /// requested DataPortal_XYZ method. /// </summary> /// <param name="e">The DataPortalContext object passed to the DataPortal.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")] [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void DataPortal_OnDataPortalInvokeComplete(DataPortalEventArgs e) { } /// <summary> /// Called by the server-side DataPortal if an exception /// occurs during data access. /// </summary> /// <param name="e">The DataPortalContext object passed to the DataPortal.</param> /// <param name="ex">The Exception thrown during data access.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")] [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void DataPortal_OnDataPortalException(DataPortalEventArgs e, Exception ex) { } #endregion #region IDataPortalTarget Members void Csla.Server.IDataPortalTarget.CheckRules() { } void Csla.Server.IDataPortalTarget.MarkAsChild() { } void Csla.Server.IDataPortalTarget.MarkNew() { } void Csla.Server.IDataPortalTarget.MarkOld() { } void Csla.Server.IDataPortalTarget.DataPortal_OnDataPortalInvoke(DataPortalEventArgs e) { this.DataPortal_OnDataPortalInvoke(e); } void Csla.Server.IDataPortalTarget.DataPortal_OnDataPortalInvokeComplete(DataPortalEventArgs e) { this.DataPortal_OnDataPortalInvokeComplete(e); } void Csla.Server.IDataPortalTarget.DataPortal_OnDataPortalException(DataPortalEventArgs e, Exception ex) { this.DataPortal_OnDataPortalException(e, ex); } void Csla.Server.IDataPortalTarget.Child_OnDataPortalInvoke(DataPortalEventArgs e) { } void Csla.Server.IDataPortalTarget.Child_OnDataPortalInvokeComplete(DataPortalEventArgs e) { } void Csla.Server.IDataPortalTarget.Child_OnDataPortalException(DataPortalEventArgs e, Exception ex) { } #endregion } }
namespace AngleSharp.Css.Tests.Styling { using AngleSharp.Css.Dom; using AngleSharp.Css.Tests.Mocks; using AngleSharp.Dom; using AngleSharp.Html.Dom; using NUnit.Framework; using System; using System.Threading.Tasks; using static CssConstructionFunctions; [TestFixture] public class BasicStylingTests { private static Task<IDocument> CreateDocumentWithOptions(String source) { var mockRequester = new MockRequester(); mockRequester.BuildResponse(request => { if (request.Address.Path.EndsWith("a.css")) { return "div#A { color: blue; }"; } else if (request.Address.Path.EndsWith("b.css")) { return "div#B { color: red; }"; } return null; }); var config = Configuration.Default.WithCss().WithMockRequester(mockRequester); var context = BrowsingContext.New(config); return context.OpenAsync(m => m.Content(source)); } [Test] public async Task ExternalStyleSheetIsPreferred() { var source = @"<!doctype html> <html> <head> <link rel=""stylesheet"" media=""screen"" type=""text/css"" title=""A"" href=""a.css"" /> <link rel=""stylesheet alternate"" media=""screen"" type=""text/css"" title=""B"" href=""b.css"" /> </head> </html>"; var document = await CreateDocumentWithOptions(source); var link = document.QuerySelector<IHtmlLinkElement>("link"); Assert.AreEqual(2, document.StyleSheets.Length); Assert.AreEqual(2, document.StyleSheetSets.Length); Assert.IsTrue(link.IsPreferred()); Assert.IsFalse(link.IsAlternate()); Assert.IsFalse(link.IsPersistent()); } [Test] public async Task ExternalStyleSheetIsPersistent() { var source = @"<!doctype html> <html> <head> <link rel=""stylesheet"" media=""screen"" type=""text/css"" href=""a.css"" /> <link rel=""stylesheet alternate"" media=""screen"" type=""text/css"" title=""B"" href=""b.css"" /> </head> </html>"; var document = await CreateDocumentWithOptions(source); var link = document.QuerySelector<IHtmlLinkElement>("link"); Assert.AreEqual(2, document.StyleSheets.Length); Assert.AreEqual(1, document.StyleSheetSets.Length); Assert.IsFalse(link.IsPreferred()); Assert.IsFalse(link.IsAlternate()); Assert.IsTrue(link.IsPersistent()); } [Test] public async Task ExternalStyleSheetIsAlternate() { var source = @"<!doctype html> <html> <head> <link rel=""stylesheet alternate"" media=""screen"" type=""text/css"" title=""A"" href=""a.css"" /> <link rel=""stylesheet"" media=""screen"" type=""text/css"" title=""B"" href=""b.css"" /> </head> </html>"; var document = await CreateDocumentWithOptions(source); var link = document.QuerySelector<IHtmlLinkElement>("link"); Assert.AreEqual(2, document.StyleSheets.Length); Assert.AreEqual(2, document.StyleSheetSets.Length); Assert.IsFalse(link.IsPreferred()); Assert.IsTrue(link.IsAlternate()); Assert.IsFalse(link.IsPersistent()); } [Test] public async Task GetComputedStyleFromHelperShouldBeOkay() { var source = "<!doctype html><head><style>p > span { color: blue; } span.bold { font-weight: bold; }</style></head><body><div><p><span class='bold'>Bold text"; var document = await CreateDocumentWithOptions(source); var element = document.QuerySelector("span.bold"); Assert.AreEqual("span", element.LocalName); Assert.AreEqual("bold", element.ClassName); var style = element.ComputeCurrentStyle(); Assert.IsNotNull(style); Assert.AreEqual(2, style.Length); } [Test] public void CssStyleDeclarationEmpty() { var css = ParseDeclarations(String.Empty); Assert.AreEqual("", css.CssText); Assert.AreEqual(0, css.Length); } [Test] public void CssStyleDeclarationUnbound() { var css = ParseDeclarations(String.Empty); css.CssText = "background-color: rgb(255, 0, 0); color: rgb(0, 0, 0)"; Assert.AreEqual("background-color: rgba(255, 0, 0, 1); color: rgba(0, 0, 0, 1)", css.CssText); Assert.AreEqual(2, css.Length); } [Test] public void CssStyleDeclarationBoundOutboundDirectionIndirect() { var document = ParseDocument(String.Empty); var element = document.CreateElement<IHtmlSpanElement>(); element.SetAttribute("style", "background-color: rgb(255, 0, 0); color: rgb(0, 0, 0)"); Assert.AreEqual("background-color: rgba(255, 0, 0, 1); color: rgba(0, 0, 0, 1)", element.GetStyle().CssText); Assert.AreEqual(2, element.GetStyle().Length); } [Test] public void CssStyleDeclarationBoundOutboundDirectionDirect() { var document = ParseDocument(String.Empty); var element = document.CreateElement<IHtmlSpanElement>(); element.SetAttribute("style", String.Empty); Assert.AreEqual(String.Empty, element.GetStyle().CssText); element.SetAttribute("style", "background-color: rgb(255, 0, 0); color: rgb(0, 0, 0)"); Assert.AreEqual("background-color: rgba(255, 0, 0, 1); color: rgba(0, 0, 0, 1)", element.GetStyle().CssText); Assert.AreEqual(2, element.GetStyle().Length); } [Test] public void CssStyleDeclarationBoundInboundDirection() { var document = ParseDocument(String.Empty); var element = document.CreateElement<IHtmlSpanElement>(); element.SetStyle("background-color: rgb(255, 0, 0); color: rgb(0, 0, 0)"); Assert.AreEqual("background-color: rgb(255, 0, 0); color: rgb(0, 0, 0)", element.GetAttribute("style")); Assert.AreEqual(2, element.GetStyle().Length); } [Test] public void MinifyRemovesComment() { var sheet = ParseStyleSheet("h1 /* this is a comment */ { color: red; /*another comment*/ }"); var result = sheet.ToCss(new MinifyStyleFormatter()); Assert.AreEqual("h1{color:rgba(255, 0, 0, 1)}", result); } [Test] public void MinifyRemovesEmptyStyleRule() { var sheet = ParseStyleSheet("h1 { }"); var result = sheet.ToCss(new MinifyStyleFormatter()); Assert.AreEqual("", result); } [Test] public void MinifyRemovesEmptyStyleRuleKeepsOtherRule() { var sheet = ParseStyleSheet("h1 { } h2 { font-size:0; }"); var result = sheet.ToCss(new MinifyStyleFormatter()); Assert.AreEqual("h2{font-size:0}", result); } [Test] public void MinifyRemovesEmptyMediaRule() { var sheet = ParseStyleSheet("@media screen { h1 { } }"); var result = sheet.ToCss(new MinifyStyleFormatter()); Assert.AreEqual("", result); } [Test] public void MinifyDoesNotRemovesMediaRuleIfOneStyleIsInThere() { var sheet = ParseStyleSheet("@media screen { h1 { } h2 { top:0} }"); var result = sheet.ToCss(new MinifyStyleFormatter()); Assert.AreEqual("@media screen{h2{top:0}}", result); } [Test] public void MinifyWorksWithNestedMediaRules() { var sheet = ParseStyleSheet("@media screen { @media screen{h1{}}div{border-top : none} }"); var result = sheet.ToCss(new MinifyStyleFormatter()); Assert.AreEqual("@media screen{div{border-top:none}}", result); } [Test] public void MinifyWithMultipleDeclarations() { var sheet = ParseStyleSheet("h1 { top:0 ; left: 2px; border: none; } h2 { border: 1px solid red;} h3{}"); var result = sheet.ToCss(new MinifyStyleFormatter()); Assert.AreEqual("h1{top:0;left:2px;border:none}h2{border:1px solid rgba(255, 0, 0, 1)}", 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; using System.Security; using System.Threading; using System.Globalization; using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Text { [Serializable] public abstract class DecoderFallback { internal bool bIsMicrosoftBestFitFallback = false; private static volatile DecoderFallback replacementFallback; // Default fallback, uses no best fit & "?" private static volatile DecoderFallback exceptionFallback; // Private object for locking instead of locking on a internal type for SQL reliability work. private static Object s_InternalSyncObject; private static Object InternalSyncObject { get { if (s_InternalSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null); } return s_InternalSyncObject; } } // Get each of our generic fallbacks. public static DecoderFallback ReplacementFallback { get { if (replacementFallback == null) lock (InternalSyncObject) if (replacementFallback == null) replacementFallback = new DecoderReplacementFallback(); return replacementFallback; } } public static DecoderFallback ExceptionFallback { get { if (exceptionFallback == null) lock (InternalSyncObject) if (exceptionFallback == null) exceptionFallback = new DecoderExceptionFallback(); return exceptionFallback; } } // Fallback // // Return the appropriate unicode string alternative to the character that need to fall back. // Most implimentations will be: // return new MyCustomDecoderFallbackBuffer(this); public abstract DecoderFallbackBuffer CreateFallbackBuffer(); // Maximum number of characters that this instance of this fallback could return public abstract int MaxCharCount { get; } } public abstract class DecoderFallbackBuffer { // Most implimentations will probably need an implimenation-specific constructor // internal methods that cannot be overriden that let us do our fallback thing // These wrap the internal methods so that we can check for people doing stuff that's incorrect public abstract bool Fallback(byte[] bytesUnknown, int index); // Get next character public abstract char GetNextChar(); // Back up a character public abstract bool MovePrevious(); // How many chars left in this fallback? public abstract int Remaining { get; } // Clear the buffer public virtual void Reset() { while (GetNextChar() != (char)0) ; } // Internal items to help us figure out what we're doing as far as error messages, etc. // These help us with our performance and messages internally internal unsafe byte* byteStart; internal unsafe char* charEnd; // Internal Reset internal unsafe void InternalReset() { byteStart = null; Reset(); } // Set the above values // This can't be part of the constructor because DecoderFallbacks would have to know how to impliment these. internal unsafe void InternalInitialize(byte* byteStart, char* charEnd) { this.byteStart = byteStart; this.charEnd = charEnd; } // Fallback the current byte by sticking it into the remaining char buffer. // This can only be called by our encodings (other have to use the public fallback methods), so // we can use our DecoderNLS here too (except we don't). // Returns true if we are successful, false if we can't fallback the character (no buffer space) // So caller needs to throw buffer space if return false. // Right now this has both bytes and bytes[], since we might have extra bytes, hence the // array, and we might need the index, hence the byte* // Don't touch ref chars unless we succeed internal unsafe virtual bool InternalFallback(byte[] bytes, byte* pBytes, ref char* chars) { // Copy bytes to array (slow, but right now that's what we get to do. // byte[] bytesUnknown = new byte[count]; // for (int i = 0; i < count; i++) // bytesUnknown[i] = *(bytes++); Debug.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize"); // See if there's a fallback character and we have an output buffer then copy our string. if (this.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length))) { // Copy the chars to our output char ch; char* charTemp = chars; bool bHighSurrogate = false; while ((ch = GetNextChar()) != 0) { // Make sure no mixed up surrogates if (Char.IsSurrogate(ch)) { if (Char.IsHighSurrogate(ch)) { // High Surrogate if (bHighSurrogate) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex")); bHighSurrogate = true; } else { // Low surrogate if (bHighSurrogate == false) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex")); bHighSurrogate = false; } } if (charTemp >= charEnd) { // No buffer space return false; } *(charTemp++) = ch; } // Need to make sure that bHighSurrogate isn't true if (bHighSurrogate) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex")); // Now we aren't going to be false, so its OK to update chars chars = charTemp; } return true; } // This version just counts the fallback and doesn't actually copy anything. internal unsafe virtual int InternalFallback(byte[] bytes, byte* pBytes) // Right now this has both bytes and bytes[], since we might have extra bytes, hence the // array, and we might need the index, hence the byte* { // Copy bytes to array (slow, but right now that's what we get to do. // byte[] bytesUnknown = new byte[count]; // for (int i = 0; i < count; i++) // bytesUnknown[i] = *(bytes++); Debug.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize"); // See if there's a fallback character and we have an output buffer then copy our string. if (this.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length))) { int count = 0; char ch; bool bHighSurrogate = false; while ((ch = GetNextChar()) != 0) { // Make sure no mixed up surrogates if (Char.IsSurrogate(ch)) { if (Char.IsHighSurrogate(ch)) { // High Surrogate if (bHighSurrogate) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex")); bHighSurrogate = true; } else { // Low surrogate if (bHighSurrogate == false) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex")); bHighSurrogate = false; } } count++; } // Need to make sure that bHighSurrogate isn't true if (bHighSurrogate) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex")); return count; } // If no fallback return 0 return 0; } // private helper methods internal void ThrowLastBytesRecursive(byte[] bytesUnknown) { // Create a string representation of our bytes. StringBuilder strBytes = new StringBuilder(bytesUnknown.Length * 3); int i; for (i = 0; i < bytesUnknown.Length && i < 20; i++) { if (strBytes.Length > 0) strBytes.Append(" "); strBytes.Append(String.Format(CultureInfo.InvariantCulture, "\\x{0:X2}", bytesUnknown[i])); } // In case the string's really long if (i == 20) strBytes.Append(" ..."); // Throw it, using our complete bytes throw new ArgumentException( Environment.GetResourceString("Argument_RecursiveFallbackBytes", strBytes.ToString()), nameof(bytesUnknown)); } } }
namespace ERY.EMath { partial class frmAxisEditor { /// <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.label1 = new System.Windows.Forms.Label(); this.txtLabel = new System.Windows.Forms.TextBox(); this.chkDrawAxis = new System.Windows.Forms.CheckBox(); this.chkShowLabel = new System.Windows.Forms.CheckBox(); this.txtMajorTick = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.nudMinorTicks = new System.Windows.Forms.NumericUpDown(); this.label3 = new System.Windows.Forms.Label(); this.chkLog = new System.Windows.Forms.CheckBox(); this.chkAutoMinimum = new System.Windows.Forms.CheckBox(); this.chkAutoMaximum = new System.Windows.Forms.CheckBox(); this.txtMinimum = new System.Windows.Forms.TextBox(); this.txtMaximum = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.btnCancel = new System.Windows.Forms.Button(); this.btnOK = new System.Windows.Forms.Button(); this.btnApply = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.nudMinorTicks)).BeginInit(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(12, 15); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(55, 13); this.label1.TabIndex = 0; this.label1.Text = "Axis Label"; // // txtLabel // this.txtLabel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtLabel.Location = new System.Drawing.Point(93, 12); this.txtLabel.Name = "txtLabel"; this.txtLabel.Size = new System.Drawing.Size(195, 20); this.txtLabel.TabIndex = 0; this.txtLabel.Enter += new System.EventHandler(this.textBox_Enter); // // chkDrawAxis // this.chkDrawAxis.AutoSize = true; this.chkDrawAxis.Location = new System.Drawing.Point(93, 206); this.chkDrawAxis.Name = "chkDrawAxis"; this.chkDrawAxis.Size = new System.Drawing.Size(81, 17); this.chkDrawAxis.TabIndex = 1; this.chkDrawAxis.Text = "Draw Origin"; this.chkDrawAxis.UseVisualStyleBackColor = true; // // chkShowLabel // this.chkShowLabel.AutoSize = true; this.chkShowLabel.Location = new System.Drawing.Point(93, 38); this.chkShowLabel.Name = "chkShowLabel"; this.chkShowLabel.Size = new System.Drawing.Size(82, 17); this.chkShowLabel.TabIndex = 2; this.chkShowLabel.Text = "Show Label"; this.chkShowLabel.UseVisualStyleBackColor = true; // // txtMajorTick // this.txtMajorTick.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtMajorTick.Location = new System.Drawing.Point(93, 122); this.txtMajorTick.Name = "txtMajorTick"; this.txtMajorTick.Size = new System.Drawing.Size(105, 20); this.txtMajorTick.TabIndex = 7; this.txtMajorTick.Enter += new System.EventHandler(this.textBox_Enter); this.txtMajorTick.TextChanged += new System.EventHandler(this.txtMajorTick_TextChanged); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(12, 116); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(57, 26); this.label2.TabIndex = 5; this.label2.Text = "Major Tick\r\nSpacing\r\n"; // // nudMinorTicks // this.nudMinorTicks.Location = new System.Drawing.Point(93, 157); this.nudMinorTicks.Name = "nudMinorTicks"; this.nudMinorTicks.Size = new System.Drawing.Size(73, 20); this.nudMinorTicks.TabIndex = 8; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(12, 159); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(62, 13); this.label3.TabIndex = 7; this.label3.Text = "Minor Ticks"; // // chkLog // this.chkLog.AutoSize = true; this.chkLog.Location = new System.Drawing.Point(93, 183); this.chkLog.Name = "chkLog"; this.chkLog.Size = new System.Drawing.Size(80, 17); this.chkLog.TabIndex = 9; this.chkLog.Text = "Logarithmic"; this.chkLog.UseVisualStyleBackColor = true; // // chkAutoMinimum // this.chkAutoMinimum.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.chkAutoMinimum.AutoSize = true; this.chkAutoMinimum.Location = new System.Drawing.Point(211, 63); this.chkAutoMinimum.Name = "chkAutoMinimum"; this.chkAutoMinimum.Size = new System.Drawing.Size(48, 17); this.chkAutoMinimum.TabIndex = 4; this.chkAutoMinimum.Text = "Auto"; this.chkAutoMinimum.UseVisualStyleBackColor = true; // // chkAutoMaximum // this.chkAutoMaximum.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.chkAutoMaximum.AutoSize = true; this.chkAutoMaximum.Location = new System.Drawing.Point(211, 89); this.chkAutoMaximum.Name = "chkAutoMaximum"; this.chkAutoMaximum.Size = new System.Drawing.Size(48, 17); this.chkAutoMaximum.TabIndex = 6; this.chkAutoMaximum.Text = "Auto"; this.chkAutoMaximum.UseVisualStyleBackColor = true; // // txtMinimum // this.txtMinimum.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtMinimum.Location = new System.Drawing.Point(93, 61); this.txtMinimum.Name = "txtMinimum"; this.txtMinimum.Size = new System.Drawing.Size(105, 20); this.txtMinimum.TabIndex = 3; this.txtMinimum.Enter += new System.EventHandler(this.textBox_Enter); this.txtMinimum.TextChanged += new System.EventHandler(this.txtMinimum_TextChanged); // // txtMaximum // this.txtMaximum.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtMaximum.Location = new System.Drawing.Point(93, 87); this.txtMaximum.Name = "txtMaximum"; this.txtMaximum.Size = new System.Drawing.Size(105, 20); this.txtMaximum.TabIndex = 5; this.txtMaximum.Enter += new System.EventHandler(this.textBox_Enter); this.txtMaximum.TextChanged += new System.EventHandler(this.txtMaximum_TextChanged); // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(12, 64); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(48, 13); this.label4.TabIndex = 13; this.label4.Text = "Minimum"; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(12, 90); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(51, 13); this.label5.TabIndex = 14; this.label5.Text = "Maximum"; // // btnCancel // this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Location = new System.Drawing.Point(204, 231); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(55, 23); this.btnCancel.TabIndex = 11; this.btnCancel.Text = "Cancel"; this.btnCancel.UseVisualStyleBackColor = true; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // btnOK // this.btnOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK; this.btnOK.Location = new System.Drawing.Point(143, 231); this.btnOK.Name = "btnOK"; this.btnOK.Size = new System.Drawing.Size(55, 23); this.btnOK.TabIndex = 10; this.btnOK.Text = "OK"; this.btnOK.UseVisualStyleBackColor = true; this.btnOK.Click += new System.EventHandler(this.btnOK_Click); // // btnApply // this.btnApply.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnApply.Location = new System.Drawing.Point(265, 231); this.btnApply.Name = "btnApply"; this.btnApply.Size = new System.Drawing.Size(55, 23); this.btnApply.TabIndex = 12; this.btnApply.Text = "Apply"; this.btnApply.UseVisualStyleBackColor = true; this.btnApply.Click += new System.EventHandler(this.btnApply_Click); // // frmAxisEditor // this.AcceptButton = this.btnOK; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.btnCancel; this.ClientSize = new System.Drawing.Size(332, 266); this.Controls.Add(this.btnApply); this.Controls.Add(this.btnOK); this.Controls.Add(this.btnCancel); this.Controls.Add(this.label5); this.Controls.Add(this.label4); this.Controls.Add(this.txtMaximum); this.Controls.Add(this.txtMinimum); this.Controls.Add(this.chkAutoMaximum); this.Controls.Add(this.chkAutoMinimum); this.Controls.Add(this.chkLog); this.Controls.Add(this.label3); this.Controls.Add(this.nudMinorTicks); this.Controls.Add(this.label2); this.Controls.Add(this.txtMajorTick); this.Controls.Add(this.chkShowLabel); this.Controls.Add(this.chkDrawAxis); this.Controls.Add(this.txtLabel); this.Controls.Add(this.label1); this.Name = "frmAxisEditor"; this.Text = "Axis Editor"; ((System.ComponentModel.ISupportInitialize)(this.nudMinorTicks)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox txtLabel; private System.Windows.Forms.CheckBox chkDrawAxis; private System.Windows.Forms.CheckBox chkShowLabel; private System.Windows.Forms.TextBox txtMajorTick; private System.Windows.Forms.Label label2; private System.Windows.Forms.NumericUpDown nudMinorTicks; private System.Windows.Forms.Label label3; private System.Windows.Forms.CheckBox chkLog; private System.Windows.Forms.CheckBox chkAutoMinimum; private System.Windows.Forms.CheckBox chkAutoMaximum; private System.Windows.Forms.TextBox txtMinimum; private System.Windows.Forms.TextBox txtMaximum; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Button btnOK; private System.Windows.Forms.Button btnApply; } }
// 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; class r4NaNmul { //user-defined class that overloads operator * public class numHolder { float f_num; public numHolder(float f_num) { this.f_num = Convert.ToSingle(f_num); } public static float operator *(numHolder a, float b) { return a.f_num * b; } public static float operator *(numHolder a, numHolder b) { return a.f_num * b.f_num; } } static float f_s_test1_op1 = Single.PositiveInfinity; static float f_s_test1_op2 = 0; static float f_s_test2_op1 = Single.NegativeInfinity; static float f_s_test2_op2 = 0; static float f_s_test3_op1 = 3; static float f_s_test3_op2 = Single.NaN; public static float f_test1_f(String s) { if (s == "test1_op1") return Single.PositiveInfinity; else return 0; } public static float f_test2_f(String s) { if (s == "test2_op1") return Single.NegativeInfinity; else return 0; } public static float f_test3_f(String s) { if (s == "test3_op1") return 3; else return Single.NaN; } class CL { public float f_cl_test1_op1 = Single.PositiveInfinity; public float f_cl_test1_op2 = 0; public float f_cl_test2_op1 = Single.NegativeInfinity; public float f_cl_test2_op2 = 0; public float f_cl_test3_op1 = 3; public float f_cl_test3_op2 = Single.NaN; } struct VT { public float f_vt_test1_op1; public float f_vt_test1_op2; public float f_vt_test2_op1; public float f_vt_test2_op2; public float f_vt_test3_op1; public float f_vt_test3_op2; } public static int Main() { bool passed = true; //initialize class CL cl1 = new CL(); //initialize struct VT vt1; vt1.f_vt_test1_op1 = Single.PositiveInfinity; vt1.f_vt_test1_op2 = 0; vt1.f_vt_test2_op1 = Single.NegativeInfinity; vt1.f_vt_test2_op2 = 0; vt1.f_vt_test3_op1 = 3; vt1.f_vt_test3_op2 = Single.NaN; float[] f_arr1d_test1_op1 = { 0, Single.PositiveInfinity }; float[,] f_arr2d_test1_op1 = { { 0, Single.PositiveInfinity }, { 1, 1 } }; float[, ,] f_arr3d_test1_op1 = { { { 0, Single.PositiveInfinity }, { 1, 1 } } }; float[] f_arr1d_test1_op2 = { 0, 0, 1 }; float[,] f_arr2d_test1_op2 = { { 0, 0 }, { 1, 1 } }; float[, ,] f_arr3d_test1_op2 = { { { 0, 0 }, { 1, 1 } } }; float[] f_arr1d_test2_op1 = { 0, Single.NegativeInfinity }; float[,] f_arr2d_test2_op1 = { { 0, Single.NegativeInfinity }, { 1, 1 } }; float[, ,] f_arr3d_test2_op1 = { { { 0, Single.NegativeInfinity }, { 1, 1 } } }; float[] f_arr1d_test2_op2 = { 0, 0, 1 }; float[,] f_arr2d_test2_op2 = { { 0, 0 }, { 1, 1 } }; float[, ,] f_arr3d_test2_op2 = { { { 0, 0 }, { 1, 1 } } }; float[] f_arr1d_test3_op1 = { 0, 3 }; float[,] f_arr2d_test3_op1 = { { 0, 3 }, { 1, 1 } }; float[, ,] f_arr3d_test3_op1 = { { { 0, 3 }, { 1, 1 } } }; float[] f_arr1d_test3_op2 = { Single.NaN, 0, 1 }; float[,] f_arr2d_test3_op2 = { { 0, Single.NaN }, { 1, 1 } }; float[, ,] f_arr3d_test3_op2 = { { { 0, Single.NaN }, { 1, 1 } } }; int[,] index = { { 0, 0 }, { 1, 1 } }; { float f_l_test1_op1 = Single.PositiveInfinity; float f_l_test1_op2 = 0; if (!Single.IsNaN(f_l_test1_op1 * f_l_test1_op2)) { Console.WriteLine("Test1_testcase 1 failed"); passed = false; } if (!Single.IsNaN(f_l_test1_op1 * f_s_test1_op2)) { Console.WriteLine("Test1_testcase 2 failed"); passed = false; } if (!Single.IsNaN(f_l_test1_op1 * f_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 3 failed"); passed = false; } if (!Single.IsNaN(f_l_test1_op1 * cl1.f_cl_test1_op2)) { Console.WriteLine("Test1_testcase 4 failed"); passed = false; } if (!Single.IsNaN(f_l_test1_op1 * vt1.f_vt_test1_op2)) { Console.WriteLine("Test1_testcase 5 failed"); passed = false; } if (!Single.IsNaN(f_l_test1_op1 * f_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 6 failed"); passed = false; } if (!Single.IsNaN(f_l_test1_op1 * f_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 7 failed"); passed = false; } if (!Single.IsNaN(f_l_test1_op1 * f_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 8 failed"); passed = false; } if (!Single.IsNaN(f_s_test1_op1 * f_l_test1_op2)) { Console.WriteLine("Test1_testcase 9 failed"); passed = false; } if (!Single.IsNaN(f_s_test1_op1 * f_s_test1_op2)) { Console.WriteLine("Test1_testcase 10 failed"); passed = false; } if (!Single.IsNaN(f_s_test1_op1 * f_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 11 failed"); passed = false; } if (!Single.IsNaN(f_s_test1_op1 * cl1.f_cl_test1_op2)) { Console.WriteLine("Test1_testcase 12 failed"); passed = false; } if (!Single.IsNaN(f_s_test1_op1 * vt1.f_vt_test1_op2)) { Console.WriteLine("Test1_testcase 13 failed"); passed = false; } if (!Single.IsNaN(f_s_test1_op1 * f_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 14 failed"); passed = false; } if (!Single.IsNaN(f_s_test1_op1 * f_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 15 failed"); passed = false; } if (!Single.IsNaN(f_s_test1_op1 * f_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 16 failed"); passed = false; } if (!Single.IsNaN(f_test1_f("test1_op1") * f_l_test1_op2)) { Console.WriteLine("Test1_testcase 17 failed"); passed = false; } if (!Single.IsNaN(f_test1_f("test1_op1") * f_s_test1_op2)) { Console.WriteLine("Test1_testcase 18 failed"); passed = false; } if (!Single.IsNaN(f_test1_f("test1_op1") * f_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 19 failed"); passed = false; } if (!Single.IsNaN(f_test1_f("test1_op1") * cl1.f_cl_test1_op2)) { Console.WriteLine("Test1_testcase 20 failed"); passed = false; } if (!Single.IsNaN(f_test1_f("test1_op1") * vt1.f_vt_test1_op2)) { Console.WriteLine("Test1_testcase 21 failed"); passed = false; } if (!Single.IsNaN(f_test1_f("test1_op1") * f_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 22 failed"); passed = false; } if (!Single.IsNaN(f_test1_f("test1_op1") * f_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 23 failed"); passed = false; } if (!Single.IsNaN(f_test1_f("test1_op1") * f_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 24 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test1_op1 * f_l_test1_op2)) { Console.WriteLine("Test1_testcase 25 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test1_op1 * f_s_test1_op2)) { Console.WriteLine("Test1_testcase 26 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test1_op1 * f_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 27 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test1_op1 * cl1.f_cl_test1_op2)) { Console.WriteLine("Test1_testcase 28 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test1_op1 * vt1.f_vt_test1_op2)) { Console.WriteLine("Test1_testcase 29 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test1_op1 * f_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 30 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test1_op1 * f_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 31 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test1_op1 * f_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 32 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test1_op1 * f_l_test1_op2)) { Console.WriteLine("Test1_testcase 33 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test1_op1 * f_s_test1_op2)) { Console.WriteLine("Test1_testcase 34 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test1_op1 * f_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 35 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test1_op1 * cl1.f_cl_test1_op2)) { Console.WriteLine("Test1_testcase 36 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test1_op1 * vt1.f_vt_test1_op2)) { Console.WriteLine("Test1_testcase 37 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test1_op1 * f_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 38 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test1_op1 * f_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 39 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test1_op1 * f_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 40 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test1_op1[1] * f_l_test1_op2)) { Console.WriteLine("Test1_testcase 41 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test1_op1[1] * f_s_test1_op2)) { Console.WriteLine("Test1_testcase 42 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test1_op1[1] * f_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 43 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test1_op1[1] * cl1.f_cl_test1_op2)) { Console.WriteLine("Test1_testcase 44 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test1_op1[1] * vt1.f_vt_test1_op2)) { Console.WriteLine("Test1_testcase 45 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test1_op1[1] * f_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 46 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test1_op1[1] * f_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 47 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test1_op1[1] * f_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 48 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test1_op1[index[0, 1], index[1, 0]] * f_l_test1_op2)) { Console.WriteLine("Test1_testcase 49 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test1_op1[index[0, 1], index[1, 0]] * f_s_test1_op2)) { Console.WriteLine("Test1_testcase 50 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test1_op1[index[0, 1], index[1, 0]] * f_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 51 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test1_op1[index[0, 1], index[1, 0]] * cl1.f_cl_test1_op2)) { Console.WriteLine("Test1_testcase 52 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test1_op1[index[0, 1], index[1, 0]] * vt1.f_vt_test1_op2)) { Console.WriteLine("Test1_testcase 53 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test1_op1[index[0, 1], index[1, 0]] * f_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 54 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test1_op1[index[0, 1], index[1, 0]] * f_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 55 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test1_op1[index[0, 1], index[1, 0]] * f_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 56 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] * f_l_test1_op2)) { Console.WriteLine("Test1_testcase 57 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] * f_s_test1_op2)) { Console.WriteLine("Test1_testcase 58 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] * f_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 59 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] * cl1.f_cl_test1_op2)) { Console.WriteLine("Test1_testcase 60 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] * vt1.f_vt_test1_op2)) { Console.WriteLine("Test1_testcase 61 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] * f_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 62 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] * f_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 63 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] * f_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 64 failed"); passed = false; } } { float f_l_test2_op1 = Single.NegativeInfinity; float f_l_test2_op2 = 0; if (!Single.IsNaN(f_l_test2_op1 * f_l_test2_op2)) { Console.WriteLine("Test2_testcase 1 failed"); passed = false; } if (!Single.IsNaN(f_l_test2_op1 * f_s_test2_op2)) { Console.WriteLine("Test2_testcase 2 failed"); passed = false; } if (!Single.IsNaN(f_l_test2_op1 * f_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 3 failed"); passed = false; } if (!Single.IsNaN(f_l_test2_op1 * cl1.f_cl_test2_op2)) { Console.WriteLine("Test2_testcase 4 failed"); passed = false; } if (!Single.IsNaN(f_l_test2_op1 * vt1.f_vt_test2_op2)) { Console.WriteLine("Test2_testcase 5 failed"); passed = false; } if (!Single.IsNaN(f_l_test2_op1 * f_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 6 failed"); passed = false; } if (!Single.IsNaN(f_l_test2_op1 * f_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 7 failed"); passed = false; } if (!Single.IsNaN(f_l_test2_op1 * f_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 8 failed"); passed = false; } if (!Single.IsNaN(f_s_test2_op1 * f_l_test2_op2)) { Console.WriteLine("Test2_testcase 9 failed"); passed = false; } if (!Single.IsNaN(f_s_test2_op1 * f_s_test2_op2)) { Console.WriteLine("Test2_testcase 10 failed"); passed = false; } if (!Single.IsNaN(f_s_test2_op1 * f_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 11 failed"); passed = false; } if (!Single.IsNaN(f_s_test2_op1 * cl1.f_cl_test2_op2)) { Console.WriteLine("Test2_testcase 12 failed"); passed = false; } if (!Single.IsNaN(f_s_test2_op1 * vt1.f_vt_test2_op2)) { Console.WriteLine("Test2_testcase 13 failed"); passed = false; } if (!Single.IsNaN(f_s_test2_op1 * f_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 14 failed"); passed = false; } if (!Single.IsNaN(f_s_test2_op1 * f_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 15 failed"); passed = false; } if (!Single.IsNaN(f_s_test2_op1 * f_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 16 failed"); passed = false; } if (!Single.IsNaN(f_test2_f("test2_op1") * f_l_test2_op2)) { Console.WriteLine("Test2_testcase 17 failed"); passed = false; } if (!Single.IsNaN(f_test2_f("test2_op1") * f_s_test2_op2)) { Console.WriteLine("Test2_testcase 18 failed"); passed = false; } if (!Single.IsNaN(f_test2_f("test2_op1") * f_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 19 failed"); passed = false; } if (!Single.IsNaN(f_test2_f("test2_op1") * cl1.f_cl_test2_op2)) { Console.WriteLine("Test2_testcase 20 failed"); passed = false; } if (!Single.IsNaN(f_test2_f("test2_op1") * vt1.f_vt_test2_op2)) { Console.WriteLine("Test2_testcase 21 failed"); passed = false; } if (!Single.IsNaN(f_test2_f("test2_op1") * f_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 22 failed"); passed = false; } if (!Single.IsNaN(f_test2_f("test2_op1") * f_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 23 failed"); passed = false; } if (!Single.IsNaN(f_test2_f("test2_op1") * f_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 24 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test2_op1 * f_l_test2_op2)) { Console.WriteLine("Test2_testcase 25 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test2_op1 * f_s_test2_op2)) { Console.WriteLine("Test2_testcase 26 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test2_op1 * f_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 27 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test2_op1 * cl1.f_cl_test2_op2)) { Console.WriteLine("Test2_testcase 28 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test2_op1 * vt1.f_vt_test2_op2)) { Console.WriteLine("Test2_testcase 29 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test2_op1 * f_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 30 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test2_op1 * f_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 31 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test2_op1 * f_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 32 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test2_op1 * f_l_test2_op2)) { Console.WriteLine("Test2_testcase 33 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test2_op1 * f_s_test2_op2)) { Console.WriteLine("Test2_testcase 34 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test2_op1 * f_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 35 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test2_op1 * cl1.f_cl_test2_op2)) { Console.WriteLine("Test2_testcase 36 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test2_op1 * vt1.f_vt_test2_op2)) { Console.WriteLine("Test2_testcase 37 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test2_op1 * f_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 38 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test2_op1 * f_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 39 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test2_op1 * f_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 40 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test2_op1[1] * f_l_test2_op2)) { Console.WriteLine("Test2_testcase 41 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test2_op1[1] * f_s_test2_op2)) { Console.WriteLine("Test2_testcase 42 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test2_op1[1] * f_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 43 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test2_op1[1] * cl1.f_cl_test2_op2)) { Console.WriteLine("Test2_testcase 44 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test2_op1[1] * vt1.f_vt_test2_op2)) { Console.WriteLine("Test2_testcase 45 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test2_op1[1] * f_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 46 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test2_op1[1] * f_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 47 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test2_op1[1] * f_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 48 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test2_op1[index[0, 1], index[1, 0]] * f_l_test2_op2)) { Console.WriteLine("Test2_testcase 49 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test2_op1[index[0, 1], index[1, 0]] * f_s_test2_op2)) { Console.WriteLine("Test2_testcase 50 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test2_op1[index[0, 1], index[1, 0]] * f_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 51 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test2_op1[index[0, 1], index[1, 0]] * cl1.f_cl_test2_op2)) { Console.WriteLine("Test2_testcase 52 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test2_op1[index[0, 1], index[1, 0]] * vt1.f_vt_test2_op2)) { Console.WriteLine("Test2_testcase 53 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test2_op1[index[0, 1], index[1, 0]] * f_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 54 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test2_op1[index[0, 1], index[1, 0]] * f_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 55 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test2_op1[index[0, 1], index[1, 0]] * f_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 56 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] * f_l_test2_op2)) { Console.WriteLine("Test2_testcase 57 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] * f_s_test2_op2)) { Console.WriteLine("Test2_testcase 58 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] * f_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 59 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] * cl1.f_cl_test2_op2)) { Console.WriteLine("Test2_testcase 60 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] * vt1.f_vt_test2_op2)) { Console.WriteLine("Test2_testcase 61 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] * f_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 62 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] * f_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 63 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] * f_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 64 failed"); passed = false; } } { float f_l_test3_op1 = 3; float f_l_test3_op2 = Single.NaN; if (!Single.IsNaN(f_l_test3_op1 * f_l_test3_op2)) { Console.WriteLine("Test3_testcase 1 failed"); passed = false; } if (!Single.IsNaN(f_l_test3_op1 * f_s_test3_op2)) { Console.WriteLine("Test3_testcase 2 failed"); passed = false; } if (!Single.IsNaN(f_l_test3_op1 * f_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 3 failed"); passed = false; } if (!Single.IsNaN(f_l_test3_op1 * cl1.f_cl_test3_op2)) { Console.WriteLine("Test3_testcase 4 failed"); passed = false; } if (!Single.IsNaN(f_l_test3_op1 * vt1.f_vt_test3_op2)) { Console.WriteLine("Test3_testcase 5 failed"); passed = false; } if (!Single.IsNaN(f_l_test3_op1 * f_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 6 failed"); passed = false; } if (!Single.IsNaN(f_l_test3_op1 * f_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 7 failed"); passed = false; } if (!Single.IsNaN(f_l_test3_op1 * f_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 8 failed"); passed = false; } if (!Single.IsNaN(f_s_test3_op1 * f_l_test3_op2)) { Console.WriteLine("Test3_testcase 9 failed"); passed = false; } if (!Single.IsNaN(f_s_test3_op1 * f_s_test3_op2)) { Console.WriteLine("Test3_testcase 10 failed"); passed = false; } if (!Single.IsNaN(f_s_test3_op1 * f_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 11 failed"); passed = false; } if (!Single.IsNaN(f_s_test3_op1 * cl1.f_cl_test3_op2)) { Console.WriteLine("Test3_testcase 12 failed"); passed = false; } if (!Single.IsNaN(f_s_test3_op1 * vt1.f_vt_test3_op2)) { Console.WriteLine("Test3_testcase 13 failed"); passed = false; } if (!Single.IsNaN(f_s_test3_op1 * f_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 14 failed"); passed = false; } if (!Single.IsNaN(f_s_test3_op1 * f_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 15 failed"); passed = false; } if (!Single.IsNaN(f_s_test3_op1 * f_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 16 failed"); passed = false; } if (!Single.IsNaN(f_test3_f("test3_op1") * f_l_test3_op2)) { Console.WriteLine("Test3_testcase 17 failed"); passed = false; } if (!Single.IsNaN(f_test3_f("test3_op1") * f_s_test3_op2)) { Console.WriteLine("Test3_testcase 18 failed"); passed = false; } if (!Single.IsNaN(f_test3_f("test3_op1") * f_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 19 failed"); passed = false; } if (!Single.IsNaN(f_test3_f("test3_op1") * cl1.f_cl_test3_op2)) { Console.WriteLine("Test3_testcase 20 failed"); passed = false; } if (!Single.IsNaN(f_test3_f("test3_op1") * vt1.f_vt_test3_op2)) { Console.WriteLine("Test3_testcase 21 failed"); passed = false; } if (!Single.IsNaN(f_test3_f("test3_op1") * f_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 22 failed"); passed = false; } if (!Single.IsNaN(f_test3_f("test3_op1") * f_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 23 failed"); passed = false; } if (!Single.IsNaN(f_test3_f("test3_op1") * f_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 24 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test3_op1 * f_l_test3_op2)) { Console.WriteLine("Test3_testcase 25 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test3_op1 * f_s_test3_op2)) { Console.WriteLine("Test3_testcase 26 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test3_op1 * f_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 27 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test3_op1 * cl1.f_cl_test3_op2)) { Console.WriteLine("Test3_testcase 28 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test3_op1 * vt1.f_vt_test3_op2)) { Console.WriteLine("Test3_testcase 29 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test3_op1 * f_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 30 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test3_op1 * f_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 31 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test3_op1 * f_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 32 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test3_op1 * f_l_test3_op2)) { Console.WriteLine("Test3_testcase 33 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test3_op1 * f_s_test3_op2)) { Console.WriteLine("Test3_testcase 34 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test3_op1 * f_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 35 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test3_op1 * cl1.f_cl_test3_op2)) { Console.WriteLine("Test3_testcase 36 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test3_op1 * vt1.f_vt_test3_op2)) { Console.WriteLine("Test3_testcase 37 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test3_op1 * f_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 38 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test3_op1 * f_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 39 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test3_op1 * f_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 40 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test3_op1[1] * f_l_test3_op2)) { Console.WriteLine("Test3_testcase 41 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test3_op1[1] * f_s_test3_op2)) { Console.WriteLine("Test3_testcase 42 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test3_op1[1] * f_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 43 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test3_op1[1] * cl1.f_cl_test3_op2)) { Console.WriteLine("Test3_testcase 44 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test3_op1[1] * vt1.f_vt_test3_op2)) { Console.WriteLine("Test3_testcase 45 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test3_op1[1] * f_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 46 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test3_op1[1] * f_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 47 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test3_op1[1] * f_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 48 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test3_op1[index[0, 1], index[1, 0]] * f_l_test3_op2)) { Console.WriteLine("Test3_testcase 49 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test3_op1[index[0, 1], index[1, 0]] * f_s_test3_op2)) { Console.WriteLine("Test3_testcase 50 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test3_op1[index[0, 1], index[1, 0]] * f_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 51 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test3_op1[index[0, 1], index[1, 0]] * cl1.f_cl_test3_op2)) { Console.WriteLine("Test3_testcase 52 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test3_op1[index[0, 1], index[1, 0]] * vt1.f_vt_test3_op2)) { Console.WriteLine("Test3_testcase 53 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test3_op1[index[0, 1], index[1, 0]] * f_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 54 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test3_op1[index[0, 1], index[1, 0]] * f_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 55 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test3_op1[index[0, 1], index[1, 0]] * f_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 56 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] * f_l_test3_op2)) { Console.WriteLine("Test3_testcase 57 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] * f_s_test3_op2)) { Console.WriteLine("Test3_testcase 58 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] * f_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 59 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] * cl1.f_cl_test3_op2)) { Console.WriteLine("Test3_testcase 60 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] * vt1.f_vt_test3_op2)) { Console.WriteLine("Test3_testcase 61 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] * f_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 62 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] * f_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 63 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] * f_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 64 failed"); passed = false; } } if (!passed) { Console.WriteLine("FAILED"); return 1; } else { Console.WriteLine("PASSED"); return 100; } } }
// 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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ // These types were moved down to System.Runtime [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Reflection.CallingConventions))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Reflection.EventAttributes))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Reflection.FieldAttributes))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Reflection.GenericParameterAttributes))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Reflection.MethodAttributes))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Reflection.MethodImplAttributes))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Reflection.ParameterAttributes))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Reflection.PropertyAttributes))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Reflection.TypeAttributes))] namespace System.Reflection.Emit { public enum FlowControl { Branch = 0, Break = 1, Call = 2, Cond_Branch = 3, Meta = 4, Next = 5, Return = 7, Throw = 8, } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct OpCode { public System.Reflection.Emit.FlowControl FlowControl { get { return default(System.Reflection.Emit.FlowControl); } } public string Name { get { return default(string); } } public System.Reflection.Emit.OpCodeType OpCodeType { get { return default(System.Reflection.Emit.OpCodeType); } } public System.Reflection.Emit.OperandType OperandType { get { return default(System.Reflection.Emit.OperandType); } } public int Size { get { return default(int); } } public System.Reflection.Emit.StackBehaviour StackBehaviourPop { get { return default(System.Reflection.Emit.StackBehaviour); } } public System.Reflection.Emit.StackBehaviour StackBehaviourPush { get { return default(System.Reflection.Emit.StackBehaviour); } } public short Value { get { return default(short); } } public override bool Equals(object obj) { return default(bool); } public bool Equals(System.Reflection.Emit.OpCode obj) { return default(bool); } public override int GetHashCode() { return default(int); } public static bool operator ==(System.Reflection.Emit.OpCode a, System.Reflection.Emit.OpCode b) { return default(bool); } public static bool operator !=(System.Reflection.Emit.OpCode a, System.Reflection.Emit.OpCode b) { return default(bool); } public override string ToString() { return default(string); } } public partial class OpCodes { internal OpCodes() { } public static readonly System.Reflection.Emit.OpCode Add; public static readonly System.Reflection.Emit.OpCode Add_Ovf; public static readonly System.Reflection.Emit.OpCode Add_Ovf_Un; public static readonly System.Reflection.Emit.OpCode And; public static readonly System.Reflection.Emit.OpCode Arglist; public static readonly System.Reflection.Emit.OpCode Beq; public static readonly System.Reflection.Emit.OpCode Beq_S; public static readonly System.Reflection.Emit.OpCode Bge; public static readonly System.Reflection.Emit.OpCode Bge_S; public static readonly System.Reflection.Emit.OpCode Bge_Un; public static readonly System.Reflection.Emit.OpCode Bge_Un_S; public static readonly System.Reflection.Emit.OpCode Bgt; public static readonly System.Reflection.Emit.OpCode Bgt_S; public static readonly System.Reflection.Emit.OpCode Bgt_Un; public static readonly System.Reflection.Emit.OpCode Bgt_Un_S; public static readonly System.Reflection.Emit.OpCode Ble; public static readonly System.Reflection.Emit.OpCode Ble_S; public static readonly System.Reflection.Emit.OpCode Ble_Un; public static readonly System.Reflection.Emit.OpCode Ble_Un_S; public static readonly System.Reflection.Emit.OpCode Blt; public static readonly System.Reflection.Emit.OpCode Blt_S; public static readonly System.Reflection.Emit.OpCode Blt_Un; public static readonly System.Reflection.Emit.OpCode Blt_Un_S; public static readonly System.Reflection.Emit.OpCode Bne_Un; public static readonly System.Reflection.Emit.OpCode Bne_Un_S; public static readonly System.Reflection.Emit.OpCode Box; public static readonly System.Reflection.Emit.OpCode Br; public static readonly System.Reflection.Emit.OpCode Br_S; public static readonly System.Reflection.Emit.OpCode Break; public static readonly System.Reflection.Emit.OpCode Brfalse; public static readonly System.Reflection.Emit.OpCode Brfalse_S; public static readonly System.Reflection.Emit.OpCode Brtrue; public static readonly System.Reflection.Emit.OpCode Brtrue_S; public static readonly System.Reflection.Emit.OpCode Call; public static readonly System.Reflection.Emit.OpCode Calli; public static readonly System.Reflection.Emit.OpCode Callvirt; public static readonly System.Reflection.Emit.OpCode Castclass; public static readonly System.Reflection.Emit.OpCode Ceq; public static readonly System.Reflection.Emit.OpCode Cgt; public static readonly System.Reflection.Emit.OpCode Cgt_Un; public static readonly System.Reflection.Emit.OpCode Ckfinite; public static readonly System.Reflection.Emit.OpCode Clt; public static readonly System.Reflection.Emit.OpCode Clt_Un; public static readonly System.Reflection.Emit.OpCode Constrained; public static readonly System.Reflection.Emit.OpCode Conv_I; public static readonly System.Reflection.Emit.OpCode Conv_I1; public static readonly System.Reflection.Emit.OpCode Conv_I2; public static readonly System.Reflection.Emit.OpCode Conv_I4; public static readonly System.Reflection.Emit.OpCode Conv_I8; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I_Un; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I1; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I1_Un; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I2; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I2_Un; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I4; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I4_Un; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I8; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I8_Un; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U_Un; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U1; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U1_Un; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U2; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U2_Un; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U4; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U4_Un; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U8; public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U8_Un; public static readonly System.Reflection.Emit.OpCode Conv_R_Un; public static readonly System.Reflection.Emit.OpCode Conv_R4; public static readonly System.Reflection.Emit.OpCode Conv_R8; public static readonly System.Reflection.Emit.OpCode Conv_U; public static readonly System.Reflection.Emit.OpCode Conv_U1; public static readonly System.Reflection.Emit.OpCode Conv_U2; public static readonly System.Reflection.Emit.OpCode Conv_U4; public static readonly System.Reflection.Emit.OpCode Conv_U8; public static readonly System.Reflection.Emit.OpCode Cpblk; public static readonly System.Reflection.Emit.OpCode Cpobj; public static readonly System.Reflection.Emit.OpCode Div; public static readonly System.Reflection.Emit.OpCode Div_Un; public static readonly System.Reflection.Emit.OpCode Dup; public static readonly System.Reflection.Emit.OpCode Endfilter; public static readonly System.Reflection.Emit.OpCode Endfinally; public static readonly System.Reflection.Emit.OpCode Initblk; public static readonly System.Reflection.Emit.OpCode Initobj; public static readonly System.Reflection.Emit.OpCode Isinst; public static readonly System.Reflection.Emit.OpCode Jmp; public static readonly System.Reflection.Emit.OpCode Ldarg; public static readonly System.Reflection.Emit.OpCode Ldarg_0; public static readonly System.Reflection.Emit.OpCode Ldarg_1; public static readonly System.Reflection.Emit.OpCode Ldarg_2; public static readonly System.Reflection.Emit.OpCode Ldarg_3; public static readonly System.Reflection.Emit.OpCode Ldarg_S; public static readonly System.Reflection.Emit.OpCode Ldarga; public static readonly System.Reflection.Emit.OpCode Ldarga_S; public static readonly System.Reflection.Emit.OpCode Ldc_I4; public static readonly System.Reflection.Emit.OpCode Ldc_I4_0; public static readonly System.Reflection.Emit.OpCode Ldc_I4_1; public static readonly System.Reflection.Emit.OpCode Ldc_I4_2; public static readonly System.Reflection.Emit.OpCode Ldc_I4_3; public static readonly System.Reflection.Emit.OpCode Ldc_I4_4; public static readonly System.Reflection.Emit.OpCode Ldc_I4_5; public static readonly System.Reflection.Emit.OpCode Ldc_I4_6; public static readonly System.Reflection.Emit.OpCode Ldc_I4_7; public static readonly System.Reflection.Emit.OpCode Ldc_I4_8; public static readonly System.Reflection.Emit.OpCode Ldc_I4_M1; public static readonly System.Reflection.Emit.OpCode Ldc_I4_S; public static readonly System.Reflection.Emit.OpCode Ldc_I8; public static readonly System.Reflection.Emit.OpCode Ldc_R4; public static readonly System.Reflection.Emit.OpCode Ldc_R8; public static readonly System.Reflection.Emit.OpCode Ldelem; public static readonly System.Reflection.Emit.OpCode Ldelem_I; public static readonly System.Reflection.Emit.OpCode Ldelem_I1; public static readonly System.Reflection.Emit.OpCode Ldelem_I2; public static readonly System.Reflection.Emit.OpCode Ldelem_I4; public static readonly System.Reflection.Emit.OpCode Ldelem_I8; public static readonly System.Reflection.Emit.OpCode Ldelem_R4; public static readonly System.Reflection.Emit.OpCode Ldelem_R8; public static readonly System.Reflection.Emit.OpCode Ldelem_Ref; public static readonly System.Reflection.Emit.OpCode Ldelem_U1; public static readonly System.Reflection.Emit.OpCode Ldelem_U2; public static readonly System.Reflection.Emit.OpCode Ldelem_U4; public static readonly System.Reflection.Emit.OpCode Ldelema; public static readonly System.Reflection.Emit.OpCode Ldfld; public static readonly System.Reflection.Emit.OpCode Ldflda; public static readonly System.Reflection.Emit.OpCode Ldftn; public static readonly System.Reflection.Emit.OpCode Ldind_I; public static readonly System.Reflection.Emit.OpCode Ldind_I1; public static readonly System.Reflection.Emit.OpCode Ldind_I2; public static readonly System.Reflection.Emit.OpCode Ldind_I4; public static readonly System.Reflection.Emit.OpCode Ldind_I8; public static readonly System.Reflection.Emit.OpCode Ldind_R4; public static readonly System.Reflection.Emit.OpCode Ldind_R8; public static readonly System.Reflection.Emit.OpCode Ldind_Ref; public static readonly System.Reflection.Emit.OpCode Ldind_U1; public static readonly System.Reflection.Emit.OpCode Ldind_U2; public static readonly System.Reflection.Emit.OpCode Ldind_U4; public static readonly System.Reflection.Emit.OpCode Ldlen; public static readonly System.Reflection.Emit.OpCode Ldloc; public static readonly System.Reflection.Emit.OpCode Ldloc_0; public static readonly System.Reflection.Emit.OpCode Ldloc_1; public static readonly System.Reflection.Emit.OpCode Ldloc_2; public static readonly System.Reflection.Emit.OpCode Ldloc_3; public static readonly System.Reflection.Emit.OpCode Ldloc_S; public static readonly System.Reflection.Emit.OpCode Ldloca; public static readonly System.Reflection.Emit.OpCode Ldloca_S; public static readonly System.Reflection.Emit.OpCode Ldnull; public static readonly System.Reflection.Emit.OpCode Ldobj; public static readonly System.Reflection.Emit.OpCode Ldsfld; public static readonly System.Reflection.Emit.OpCode Ldsflda; public static readonly System.Reflection.Emit.OpCode Ldstr; public static readonly System.Reflection.Emit.OpCode Ldtoken; public static readonly System.Reflection.Emit.OpCode Ldvirtftn; public static readonly System.Reflection.Emit.OpCode Leave; public static readonly System.Reflection.Emit.OpCode Leave_S; public static readonly System.Reflection.Emit.OpCode Localloc; public static readonly System.Reflection.Emit.OpCode Mkrefany; public static readonly System.Reflection.Emit.OpCode Mul; public static readonly System.Reflection.Emit.OpCode Mul_Ovf; public static readonly System.Reflection.Emit.OpCode Mul_Ovf_Un; public static readonly System.Reflection.Emit.OpCode Neg; public static readonly System.Reflection.Emit.OpCode Newarr; public static readonly System.Reflection.Emit.OpCode Newobj; public static readonly System.Reflection.Emit.OpCode Nop; public static readonly System.Reflection.Emit.OpCode Not; public static readonly System.Reflection.Emit.OpCode Or; public static readonly System.Reflection.Emit.OpCode Pop; public static readonly System.Reflection.Emit.OpCode Prefix1; public static readonly System.Reflection.Emit.OpCode Prefix2; public static readonly System.Reflection.Emit.OpCode Prefix3; public static readonly System.Reflection.Emit.OpCode Prefix4; public static readonly System.Reflection.Emit.OpCode Prefix5; public static readonly System.Reflection.Emit.OpCode Prefix6; public static readonly System.Reflection.Emit.OpCode Prefix7; public static readonly System.Reflection.Emit.OpCode Prefixref; public static readonly System.Reflection.Emit.OpCode Readonly; public static readonly System.Reflection.Emit.OpCode Refanytype; public static readonly System.Reflection.Emit.OpCode Refanyval; public static readonly System.Reflection.Emit.OpCode Rem; public static readonly System.Reflection.Emit.OpCode Rem_Un; public static readonly System.Reflection.Emit.OpCode Ret; public static readonly System.Reflection.Emit.OpCode Rethrow; public static readonly System.Reflection.Emit.OpCode Shl; public static readonly System.Reflection.Emit.OpCode Shr; public static readonly System.Reflection.Emit.OpCode Shr_Un; public static readonly System.Reflection.Emit.OpCode Sizeof; public static readonly System.Reflection.Emit.OpCode Starg; public static readonly System.Reflection.Emit.OpCode Starg_S; public static readonly System.Reflection.Emit.OpCode Stelem; public static readonly System.Reflection.Emit.OpCode Stelem_I; public static readonly System.Reflection.Emit.OpCode Stelem_I1; public static readonly System.Reflection.Emit.OpCode Stelem_I2; public static readonly System.Reflection.Emit.OpCode Stelem_I4; public static readonly System.Reflection.Emit.OpCode Stelem_I8; public static readonly System.Reflection.Emit.OpCode Stelem_R4; public static readonly System.Reflection.Emit.OpCode Stelem_R8; public static readonly System.Reflection.Emit.OpCode Stelem_Ref; public static readonly System.Reflection.Emit.OpCode Stfld; public static readonly System.Reflection.Emit.OpCode Stind_I; public static readonly System.Reflection.Emit.OpCode Stind_I1; public static readonly System.Reflection.Emit.OpCode Stind_I2; public static readonly System.Reflection.Emit.OpCode Stind_I4; public static readonly System.Reflection.Emit.OpCode Stind_I8; public static readonly System.Reflection.Emit.OpCode Stind_R4; public static readonly System.Reflection.Emit.OpCode Stind_R8; public static readonly System.Reflection.Emit.OpCode Stind_Ref; public static readonly System.Reflection.Emit.OpCode Stloc; public static readonly System.Reflection.Emit.OpCode Stloc_0; public static readonly System.Reflection.Emit.OpCode Stloc_1; public static readonly System.Reflection.Emit.OpCode Stloc_2; public static readonly System.Reflection.Emit.OpCode Stloc_3; public static readonly System.Reflection.Emit.OpCode Stloc_S; public static readonly System.Reflection.Emit.OpCode Stobj; public static readonly System.Reflection.Emit.OpCode Stsfld; public static readonly System.Reflection.Emit.OpCode Sub; public static readonly System.Reflection.Emit.OpCode Sub_Ovf; public static readonly System.Reflection.Emit.OpCode Sub_Ovf_Un; public static readonly System.Reflection.Emit.OpCode Switch; public static readonly System.Reflection.Emit.OpCode Tailcall; public static readonly System.Reflection.Emit.OpCode Throw; public static readonly System.Reflection.Emit.OpCode Unaligned; public static readonly System.Reflection.Emit.OpCode Unbox; public static readonly System.Reflection.Emit.OpCode Unbox_Any; public static readonly System.Reflection.Emit.OpCode Volatile; public static readonly System.Reflection.Emit.OpCode Xor; public static bool TakesSingleByteArgument(System.Reflection.Emit.OpCode inst) { return default(bool); } } public enum OpCodeType { Macro = 1, Nternal = 2, Objmodel = 3, Prefix = 4, Primitive = 5, } public enum OperandType { InlineBrTarget = 0, InlineField = 1, InlineI = 2, InlineI8 = 3, InlineMethod = 4, InlineNone = 5, InlineR = 7, InlineSig = 9, InlineString = 10, InlineSwitch = 11, InlineTok = 12, InlineType = 13, InlineVar = 14, ShortInlineBrTarget = 15, ShortInlineI = 16, ShortInlineR = 17, ShortInlineVar = 18, } public enum PackingSize { Size1 = 1, Size128 = 128, Size16 = 16, Size2 = 2, Size32 = 32, Size4 = 4, Size64 = 64, Size8 = 8, Unspecified = 0, } public enum StackBehaviour { Pop0 = 0, Pop1 = 1, Pop1_pop1 = 2, Popi = 3, Popi_pop1 = 4, Popi_popi = 5, Popi_popi_popi = 7, Popi_popi8 = 6, Popi_popr4 = 8, Popi_popr8 = 9, Popref = 10, Popref_pop1 = 11, Popref_popi = 12, Popref_popi_pop1 = 28, Popref_popi_popi = 13, Popref_popi_popi8 = 14, Popref_popi_popr4 = 15, Popref_popi_popr8 = 16, Popref_popi_popref = 17, Push0 = 18, Push1 = 19, Push1_push1 = 20, Pushi = 21, Pushi8 = 22, Pushr4 = 23, Pushr8 = 24, Pushref = 25, Varpop = 26, Varpush = 27, } }
/******************************************************************************* * Copyright 2011, 2012 Chris Banes. * * 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. *******************************************************************************/ //package com.handmark.pulltorefresh.library; //import android.annotation.TargetApi; //import android.content.Context; //import android.os.Build.VERSION; //import android.os.Build.VERSION_CODES; //import android.os.Bundle; //import android.util.AttributeSet; //import android.util.FloatMath; //import android.webkit.WebChromeClient; //import android.webkit.WebView; using Android.Content; using Android.Util; using Android.Webkit; using WebChromeClient=Android.Webkit.WebChromeClient; using PTROrientation = Com.Handmark.PullToRefresh.Library.PtrOrientation; using Mode = Com.Handmark.PullToRefresh.Library.PtrMode; using Android.OS; using System; using Android.Annotation; namespace Com.Handmark.PullToRefresh.Library { public class PullToRefreshWebView : PullToRefreshBase<WebView> { //private static OnRefreshListener<WebView> defaultOnRefreshListener = new OnRefreshListener<WebView>() ; //{ // //@Override // public override void onRefresh(PullToRefreshBase<WebView> refreshView) { // refreshView.getRefreshableView().Reload(); // } //}; class OnRefreshListenerImpl : OnRefreshListener<WebView> { public void onRefresh(PullToRefreshBase<WebView> refreshView) { refreshView.getRefreshableView().Reload(); } } private OnRefreshListener<WebView> defaultOnRefreshListener = new OnRefreshListenerImpl(); class WebChromeClientImpl : WebChromeClient { PullToRefreshWebView inst; public WebChromeClientImpl(PullToRefreshWebView instance) : base() { inst = instance; } public override void OnProgressChanged(WebView view, int newProgress) { if (newProgress == 100) { inst.onRefreshComplete(); } base.OnProgressChanged(view, newProgress); } } private WebChromeClient defaultWebChromeClient; //{ // //@Override // public override void onProgressChanged(WebView view, int newProgress) { // if (newProgress == 100) { // onRefreshComplete(); // } // } //}; private void SetClient() { setOnRefreshListener(defaultOnRefreshListener); if (defaultWebChromeClient == null) { defaultWebChromeClient = new WebChromeClientImpl(this); } mRefreshableView.SetWebChromeClient(defaultWebChromeClient); } public PullToRefreshWebView(Context context) : base(context) { //super(context); /** * Added so that by default, Pull-to-Refresh refreshes the page */ SetClient(); } public PullToRefreshWebView(Context context, IAttributeSet attrs) : base(context, attrs) { //super(context, attrs); /** * Added so that by default, Pull-to-Refresh refreshes the page */ SetClient(); } public PullToRefreshWebView(Context context, Mode mode) : base(context, mode) { /** * Added so that by default, Pull-to-Refresh refreshes the page */ SetClient(); } public PullToRefreshWebView(Context context, Mode mode, AnimationStyle style) : base(context, mode, style) { /** * Added so that by default, Pull-to-Refresh refreshes the page */ SetClient(); } //@Overrize public override PTROrientation getPullToRefreshScrollDirection() { return PTROrientation.VERTICAL; } //@Override protected override WebView createRefreshableView(Context context, IAttributeSet attrs) { WebView webView; if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Gingerbread) { webView = new InternalWebViewSDK9(context, attrs, this); } else { webView = new WebView(context, attrs); } webView.Id = Resource.Id.webview; return webView; } //@Override protected override bool isReadyForPullStart() { return mRefreshableView.ScrollY == 0; } //@Override protected override bool isReadyForPullEnd() { float exactContentHeight = FloatMath.Floor(mRefreshableView.ContentHeight * mRefreshableView.Scale); return mRefreshableView.ScrollY >= (exactContentHeight - mRefreshableView.Height); } //@Override protected override void onPtrRestoreInstanceState(Bundle savedInstanceState) { base.onPtrRestoreInstanceState(savedInstanceState); mRefreshableView.RestoreState(savedInstanceState); } //@Override protected override void onPtrSaveInstanceState(Bundle saveState) { base.onPtrSaveInstanceState(saveState); mRefreshableView.SaveState(saveState); } [TargetApi(Value=9)] class InternalWebViewSDK9 : WebView { // WebView doesn't always scroll back to it's edge so we add some // fuzziness static readonly int OVERSCROLL_FUZZY_THRESHOLD = 2; // WebView seems quite reluctant to overscroll so we use the scale // factor to scale it's value static readonly float OVERSCROLL_SCALE_FACTOR = 1.5f; PullToRefreshWebView inst; public InternalWebViewSDK9(Context context, IAttributeSet attrs, PullToRefreshWebView instance) : base(context, attrs) { inst = instance; } //@Override protected override bool OverScrollBy(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX, int scrollRangeY, int maxOverScrollX, int maxOverScrollY, bool isTouchEvent) { bool returnValue = base.OverScrollBy(deltaX, deltaY, scrollX, scrollY, scrollRangeX, scrollRangeY, maxOverScrollX, maxOverScrollY, isTouchEvent); // Does all of the hard work... OverscrollHelper.overScrollBy(inst, deltaX, scrollX, deltaY, scrollY, getScrollRange(), OVERSCROLL_FUZZY_THRESHOLD, OVERSCROLL_SCALE_FACTOR, isTouchEvent); return returnValue; } private int getScrollRange() { return (int)Math.Max(0, FloatMath.Floor(inst.mRefreshableView.ContentHeight * inst.mRefreshableView.Scale) - (Height - PaddingBottom - PaddingTop)); } } } }
using System; using System.Collections; using System.Threading; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Input; using System.Windows.Media; using System.Windows.Threading; namespace AutoCompleteTextBox.Editors { [TemplatePart(Name = PartEditor, Type = typeof(TextBox))] [TemplatePart(Name = PartPopup, Type = typeof(Popup))] [TemplatePart(Name = PartSelector, Type = typeof(Selector))] [TemplatePart(Name = PartExpander, Type = typeof(Expander))] public class AutoCompleteComboBox : Control { #region "Fields" public const string PartEditor = "PART_Editor"; public const string PartPopup = "PART_Popup"; public const string PartSelector = "PART_Selector"; public const string PartExpander = "PART_Expander"; public static readonly DependencyProperty DelayProperty = DependencyProperty.Register("Delay", typeof(int), typeof(AutoCompleteComboBox), new FrameworkPropertyMetadata(200)); public static readonly DependencyProperty DisplayMemberProperty = DependencyProperty.Register("DisplayMember", typeof(string), typeof(AutoCompleteComboBox), new FrameworkPropertyMetadata(string.Empty)); public static readonly DependencyProperty IconPlacementProperty = DependencyProperty.Register("IconPlacement", typeof(IconPlacement), typeof(AutoCompleteComboBox), new FrameworkPropertyMetadata(IconPlacement.Left)); public static readonly DependencyProperty IconProperty = DependencyProperty.Register("Icon", typeof(object), typeof(AutoCompleteComboBox), new FrameworkPropertyMetadata(null)); public static readonly DependencyProperty IconVisibilityProperty = DependencyProperty.Register("IconVisibility", typeof(Visibility), typeof(AutoCompleteComboBox), new FrameworkPropertyMetadata(Visibility.Visible)); public static readonly DependencyProperty IsDropDownOpenProperty = DependencyProperty.Register("IsDropDownOpen", typeof(bool), typeof(AutoCompleteComboBox), new FrameworkPropertyMetadata(false)); public static readonly DependencyProperty IsLoadingProperty = DependencyProperty.Register("IsLoading", typeof(bool), typeof(AutoCompleteComboBox), new FrameworkPropertyMetadata(false)); public static readonly DependencyProperty IsReadOnlyProperty = DependencyProperty.Register("IsReadOnly", typeof(bool), typeof(AutoCompleteComboBox), new FrameworkPropertyMetadata(false)); public static readonly DependencyProperty ItemTemplateProperty = DependencyProperty.Register("ItemTemplate", typeof(DataTemplate), typeof(AutoCompleteComboBox), new FrameworkPropertyMetadata(null)); public static readonly DependencyProperty ItemTemplateSelectorProperty = DependencyProperty.Register("ItemTemplateSelector", typeof(DataTemplateSelector), typeof(AutoCompleteComboBox)); public static readonly DependencyProperty LoadingContentProperty = DependencyProperty.Register("LoadingContent", typeof(object), typeof(AutoCompleteComboBox), new FrameworkPropertyMetadata(null)); public static readonly DependencyProperty ProviderProperty = DependencyProperty.Register("Provider", typeof(IComboSuggestionProvider), typeof(AutoCompleteComboBox), new FrameworkPropertyMetadata(null)); public static readonly DependencyProperty SelectedItemProperty = DependencyProperty.Register("SelectedItem", typeof(object), typeof(AutoCompleteComboBox), new FrameworkPropertyMetadata(null, OnSelectedItemChanged)); public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(AutoCompleteComboBox), new FrameworkPropertyMetadata(string.Empty, propertyChangedCallback: null, coerceValueCallback: null, isAnimationProhibited: false, defaultUpdateSourceTrigger: UpdateSourceTrigger.LostFocus, flags: FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); public static readonly DependencyProperty FilterProperty = DependencyProperty.Register("Filter", typeof(string), typeof(AutoCompleteComboBox), new FrameworkPropertyMetadata(string.Empty)); public static readonly DependencyProperty MaxLengthProperty = DependencyProperty.Register("MaxLength", typeof(int), typeof(AutoCompleteComboBox), new FrameworkPropertyMetadata(0)); public static readonly DependencyProperty CharacterCasingProperty = DependencyProperty.Register("CharacterCasing", typeof(CharacterCasing), typeof(AutoCompleteComboBox), new FrameworkPropertyMetadata(CharacterCasing.Normal)); public static readonly DependencyProperty MaxPopUpHeightProperty = DependencyProperty.Register("MaxPopUpHeight", typeof(int), typeof(AutoCompleteComboBox), new FrameworkPropertyMetadata(600)); public static readonly DependencyProperty MaxPopUpWidthProperty = DependencyProperty.Register("MaxPopUpWidth", typeof(int), typeof(AutoCompleteComboBox), new FrameworkPropertyMetadata(2000)); public static readonly DependencyProperty WatermarkProperty = DependencyProperty.Register("Watermark", typeof(string), typeof(AutoCompleteComboBox), new FrameworkPropertyMetadata(string.Empty)); public static readonly DependencyProperty SuggestionBackgroundProperty = DependencyProperty.Register("SuggestionBackground", typeof(Brush), typeof(AutoCompleteComboBox), new FrameworkPropertyMetadata(Brushes.White)); private bool _isUpdatingText; private bool _selectionCancelled; private SuggestionsAdapter _suggestionsAdapter; #endregion #region "Constructors" static AutoCompleteComboBox() { DefaultStyleKeyProperty.OverrideMetadata(typeof(AutoCompleteComboBox), new FrameworkPropertyMetadata(typeof(AutoCompleteComboBox))); } #endregion #region "Properties" public int MaxPopupHeight { get => (int)GetValue(MaxPopUpHeightProperty); set => SetValue(MaxPopUpHeightProperty, value); } public int MaxPopupWidth { get => (int)GetValue(MaxPopUpWidthProperty); set => SetValue(MaxPopUpWidthProperty, value); } public BindingEvaluator BindingEvaluator { get; set; } public CharacterCasing CharacterCasing { get => (CharacterCasing)GetValue(CharacterCasingProperty); set => SetValue(CharacterCasingProperty, value); } public int MaxLength { get => (int)GetValue(MaxLengthProperty); set => SetValue(MaxLengthProperty, value); } public int Delay { get => (int)GetValue(DelayProperty); set => SetValue(DelayProperty, value); } public string DisplayMember { get => (string)GetValue(DisplayMemberProperty); set => SetValue(DisplayMemberProperty, value); } public TextBox Editor { get; set; } public Expander Expander { get; set; } public DispatcherTimer FetchTimer { get; set; } public string Filter { get => (string)GetValue(FilterProperty); set => SetValue(FilterProperty, value); } public object Icon { get => GetValue(IconProperty); set => SetValue(IconProperty, value); } public IconPlacement IconPlacement { get => (IconPlacement)GetValue(IconPlacementProperty); set => SetValue(IconPlacementProperty, value); } public Visibility IconVisibility { get => (Visibility)GetValue(IconVisibilityProperty); set => SetValue(IconVisibilityProperty, value); } public bool IsDropDownOpen { get => (bool)GetValue(IsDropDownOpenProperty); set { this.Expander.IsExpanded = value; SetValue(IsDropDownOpenProperty, value); } } public bool IsLoading { get => (bool)GetValue(IsLoadingProperty); set => SetValue(IsLoadingProperty, value); } public bool IsReadOnly { get => (bool)GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } public Selector ItemsSelector { get; set; } public DataTemplate ItemTemplate { get => (DataTemplate)GetValue(ItemTemplateProperty); set => SetValue(ItemTemplateProperty, value); } public DataTemplateSelector ItemTemplateSelector { get => ((DataTemplateSelector)(GetValue(ItemTemplateSelectorProperty))); set => SetValue(ItemTemplateSelectorProperty, value); } public object LoadingContent { get => GetValue(LoadingContentProperty); set => SetValue(LoadingContentProperty, value); } public Popup Popup { get; set; } public IComboSuggestionProvider Provider { get => (IComboSuggestionProvider)GetValue(ProviderProperty); set => SetValue(ProviderProperty, value); } public object SelectedItem { get => GetValue(SelectedItemProperty); set => SetValue(SelectedItemProperty, value); } public SelectionAdapter SelectionAdapter { get; set; } public string Text { get => (string)GetValue(TextProperty); set => SetValue(TextProperty, value); } public string Watermark { get => (string)GetValue(WatermarkProperty); set => SetValue(WatermarkProperty, value); } public Brush SuggestionBackground { get => (Brush)GetValue(SuggestionBackgroundProperty); set => SetValue(SuggestionBackgroundProperty, value); } #endregion #region "Methods" public static void OnSelectedItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { AutoCompleteComboBox act = null; act = d as AutoCompleteComboBox; if (act != null) { if (act.Editor != null & !act._isUpdatingText) { act._isUpdatingText = true; act.Editor.Text = act.BindingEvaluator.Evaluate(e.NewValue); act._isUpdatingText = false; } } } private void ScrollToSelectedItem() { if (ItemsSelector is ListBox listBox && listBox.SelectedItem != null) listBox.ScrollIntoView(listBox.SelectedItem); } public new BindingExpressionBase SetBinding(DependencyProperty dp, BindingBase binding){ var res = base.SetBinding(dp, binding); CheckForParentTextBindingChange(); return res; } public new BindingExpressionBase SetBinding(DependencyProperty dp, String path) { var res = base.SetBinding(dp, path); CheckForParentTextBindingChange(); return res; } public new void ClearValue(DependencyPropertyKey key) { base.ClearValue(key); CheckForParentTextBindingChange(); } public new void ClearValue(DependencyProperty dp) { base.ClearValue(dp); CheckForParentTextBindingChange(); } private void CheckForParentTextBindingChange(bool force=false) { var CurrentBindingMode = BindingOperations.GetBinding(this, TextProperty)?.UpdateSourceTrigger ?? UpdateSourceTrigger.Default; if (CurrentBindingMode != UpdateSourceTrigger.PropertyChanged)//preventing going any less frequent than property changed CurrentBindingMode = UpdateSourceTrigger.Default; if (CurrentBindingMode == CurrentTextboxTextBindingUpdateMode && force == false) return; var binding = new Binding { Mode = BindingMode.TwoWay, UpdateSourceTrigger = CurrentBindingMode, Path = new PropertyPath(nameof(Text)), RelativeSource = new RelativeSource(RelativeSourceMode.TemplatedParent), }; CurrentTextboxTextBindingUpdateMode = CurrentBindingMode; Editor?.SetBinding(TextBox.TextProperty, binding); } private UpdateSourceTrigger CurrentTextboxTextBindingUpdateMode; public override void OnApplyTemplate() { base.OnApplyTemplate(); Editor = Template.FindName(PartEditor, this) as TextBox; Popup = Template.FindName(PartPopup, this) as Popup; ItemsSelector = Template.FindName(PartSelector, this) as Selector; Expander = Template.FindName(PartExpander, this) as Expander; BindingEvaluator = new BindingEvaluator(new Binding(DisplayMember)); if (Editor != null) { Editor.TextChanged += OnEditorTextChanged; Editor.PreviewKeyDown += OnEditorKeyDown; Editor.LostFocus += OnEditorLostFocus; CheckForParentTextBindingChange(true); if (SelectedItem != null) { _isUpdatingText = true; Editor.Text = BindingEvaluator.Evaluate(SelectedItem); _isUpdatingText = false; } } if (Expander != null) { Expander.IsExpanded = false; Expander.Collapsed += Expander_Expanded; Expander.Expanded += Expander_Expanded; } GotFocus += AutoCompleteComboBox_GotFocus; if (Popup != null) { Popup.StaysOpen = false; Popup.Opened += OnPopupOpened; Popup.Closed += OnPopupClosed; } if (ItemsSelector != null) { SelectionAdapter = new SelectionAdapter(ItemsSelector); SelectionAdapter.Commit += OnSelectionAdapterCommit; SelectionAdapter.Cancel += OnSelectionAdapterCancel; SelectionAdapter.SelectionChanged += OnSelectionAdapterSelectionChanged; ItemsSelector.PreviewMouseDown += ItemsSelector_PreviewMouseDown; } } private void Expander_Expanded(object sender, RoutedEventArgs e) { this.IsDropDownOpen = Expander.IsExpanded; if (!this.IsDropDownOpen) { return; } if (_suggestionsAdapter == null) { _suggestionsAdapter = new SuggestionsAdapter(this); } if (SelectedItem != null || String.IsNullOrWhiteSpace(Editor.Text)) _suggestionsAdapter.ShowFullCollection(); } private void ItemsSelector_PreviewMouseDown(object sender, MouseButtonEventArgs e) { if ((e.OriginalSource as FrameworkElement)?.DataContext == null) return; if (!ItemsSelector.Items.Contains(((FrameworkElement)e.OriginalSource)?.DataContext)) return; ItemsSelector.SelectedItem = ((FrameworkElement)e.OriginalSource)?.DataContext; OnSelectionAdapterCommit(SelectionAdapter.EventCause.ItemClicked); e.Handled = true; } private void AutoCompleteComboBox_GotFocus(object sender, RoutedEventArgs e) { Editor?.Focus(); } private string GetDisplayText(object dataItem) { if (BindingEvaluator == null) { BindingEvaluator = new BindingEvaluator(new Binding(DisplayMember)); } if (dataItem == null) { return string.Empty; } if (string.IsNullOrEmpty(DisplayMember)) { return dataItem.ToString(); } return BindingEvaluator.Evaluate(dataItem); } private void OnEditorKeyDown(object sender, KeyEventArgs e) { if (SelectionAdapter != null) { if (IsDropDownOpen) SelectionAdapter.HandleKeyDown(e); else IsDropDownOpen = e.Key == Key.Down || e.Key == Key.Up; } } private void OnEditorLostFocus(object sender, RoutedEventArgs e) { if (!IsKeyboardFocusWithin) { IsDropDownOpen = false; } } private void OnEditorTextChanged(object sender, TextChangedEventArgs e) { Text = Editor.Text; if (_isUpdatingText) return; if (FetchTimer == null) { FetchTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(Delay) }; FetchTimer.Tick += OnFetchTimerTick; } FetchTimer.IsEnabled = false; FetchTimer.Stop(); SetSelectedItem(null); if (Editor.Text.Length > 0) { FetchTimer.IsEnabled = true; FetchTimer.Start(); } else { IsDropDownOpen = false; } } private void OnFetchTimerTick(object sender, EventArgs e) { FetchTimer.IsEnabled = false; FetchTimer.Stop(); if (Provider != null && ItemsSelector != null) { Filter = Editor.Text; if (_suggestionsAdapter == null) { _suggestionsAdapter = new SuggestionsAdapter(this); } _suggestionsAdapter.GetSuggestions(Filter); } } private void OnPopupClosed(object sender, EventArgs e) { if (!_selectionCancelled) { OnSelectionAdapterCommit(SelectionAdapter.EventCause.PopupClosed); } } private void OnPopupOpened(object sender, EventArgs e) { _selectionCancelled = false; ItemsSelector.SelectedItem = SelectedItem; } public event EventHandler<SelectionAdapter.PreSelectionAdapterFinishArgs> PreSelectionAdapterFinish; private bool PreSelectionEventSomeoneHandled(SelectionAdapter.EventCause cause, bool is_cancel) { if (PreSelectionAdapterFinish == null) return false; var args = new SelectionAdapter.PreSelectionAdapterFinishArgs { cause = cause, is_cancel = is_cancel }; PreSelectionAdapterFinish?.Invoke(this, args); return args.handled; } private void OnSelectionAdapterCancel(SelectionAdapter.EventCause cause) { if (PreSelectionEventSomeoneHandled(cause, true)) return; _isUpdatingText = true; Editor.Text = SelectedItem == null ? Filter : GetDisplayText(SelectedItem); Editor.SelectionStart = Editor.Text.Length; Editor.SelectionLength = 0; _isUpdatingText = false; IsDropDownOpen = false; _selectionCancelled = true; } private void OnSelectionAdapterCommit(SelectionAdapter.EventCause cause) { if (PreSelectionEventSomeoneHandled(cause, false)) return; if (ItemsSelector.SelectedItem != null) { SelectedItem = ItemsSelector.SelectedItem; _isUpdatingText = true; Editor.Text = GetDisplayText(ItemsSelector.SelectedItem); SetSelectedItem(ItemsSelector.SelectedItem); _isUpdatingText = false; IsDropDownOpen = false; } } private void OnSelectionAdapterSelectionChanged() { _isUpdatingText = true; Editor.Text = ItemsSelector.SelectedItem == null ? Filter : GetDisplayText(ItemsSelector.SelectedItem); Editor.SelectionStart = Editor.Text.Length; Editor.SelectionLength = 0; ScrollToSelectedItem(); _isUpdatingText = false; } private void SetSelectedItem(object item) { _isUpdatingText = true; SelectedItem = item; _isUpdatingText = false; } #endregion #region "Nested Types" private class SuggestionsAdapter { #region "Fields" private readonly AutoCompleteComboBox _actb; private string _filter; #endregion #region "Constructors" public SuggestionsAdapter(AutoCompleteComboBox actb) { _actb = actb; } #endregion #region "Methods" public void GetSuggestions(string searchText) { _actb.IsLoading = true; // Do not open drop down if control is not focused if (_actb.IsKeyboardFocusWithin) _actb.IsDropDownOpen = true; _actb.ItemsSelector.ItemsSource = null; ParameterizedThreadStart thInfo = GetSuggestionsAsync; Thread th = new Thread(thInfo); _filter = searchText; th.Start(new object[] { searchText, _actb.Provider }); } public void ShowFullCollection() { _filter = string.Empty; _actb.IsLoading = true; // Do not open drop down if control is not focused if (_actb.IsKeyboardFocusWithin) _actb.IsDropDownOpen = true; _actb.ItemsSelector.ItemsSource = null; ParameterizedThreadStart thInfo = GetFullCollectionAsync; Thread th = new Thread(thInfo); th.Start(_actb.Provider); } private void DisplaySuggestions(IEnumerable suggestions, string filter) { if (_filter != filter) { return; } _actb.IsLoading = false; _actb.ItemsSelector.ItemsSource = suggestions; // Close drop down if there are no items if (_actb.IsDropDownOpen) { _actb.IsDropDownOpen = _actb.ItemsSelector.HasItems; } } private void GetSuggestionsAsync(object param) { if (param is object[] args) { string searchText = Convert.ToString(args[0]); if (args[1] is IComboSuggestionProvider provider) { IEnumerable list = provider.GetSuggestions(searchText); _actb.Dispatcher.BeginInvoke(new Action<IEnumerable, string>(DisplaySuggestions), DispatcherPriority.Background, list, searchText); } } } private void GetFullCollectionAsync(object param) { if (param is IComboSuggestionProvider provider) { IEnumerable list = provider.GetFullCollection(); _actb.Dispatcher.BeginInvoke(new Action<IEnumerable, string>(DisplaySuggestions), DispatcherPriority.Background, list, string.Empty); } } #endregion } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Text; using System.Xml.Schema; using System.Collections; using System.Diagnostics; using System.Globalization; using System.Collections.Generic; using System.Runtime.Versioning; namespace System.Xml { internal sealed partial class XmlValidatingReaderImpl : XmlReader, IXmlLineInfo, IXmlNamespaceResolver { // // Private helper types // // ParsingFunction = what should the reader do when the next Read() is called private enum ParsingFunction { Read = 0, Init, ParseDtdFromContext, ResolveEntityInternally, InReadBinaryContent, ReaderClosed, Error, None, } internal class ValidationEventHandling : IValidationEventHandling { // Fields private XmlValidatingReaderImpl _reader; private ValidationEventHandler _eventHandler; // Constructor internal ValidationEventHandling(XmlValidatingReaderImpl reader) { _reader = reader; } // IValidationEventHandling interface #region IValidationEventHandling interface object IValidationEventHandling.EventHandler { get { return _eventHandler; } } void IValidationEventHandling.SendEvent(Exception /*XmlSchemaException*/ exception, XmlSeverityType severity) { if (_eventHandler != null) { _eventHandler(_reader, new ValidationEventArgs((XmlSchemaException)exception, severity)); } else if (_reader._validationType != ValidationType.None && severity == XmlSeverityType.Error) { throw exception; } } #endregion // XmlValidatingReaderImpl helper methods internal void AddHandler(ValidationEventHandler handler) { _eventHandler += handler; } internal void RemoveHandler(ValidationEventHandler handler) { _eventHandler -= handler; } } // // Fields // // core text reader private XmlReader _coreReader; private XmlTextReaderImpl _coreReaderImpl; private IXmlNamespaceResolver _coreReaderNSResolver; // validation private ValidationType _validationType; private BaseValidator _validator; #pragma warning disable 618 private XmlSchemaCollection _schemaCollection; #pragma warning restore 618 private bool _processIdentityConstraints; // parsing function (state) private ParsingFunction _parsingFunction = ParsingFunction.Init; // event handling private ValidationEventHandling _eventHandling; // misc private XmlParserContext _parserContext; // helper for Read[Element]ContentAs{Base64,BinHex} methods private ReadContentAsBinaryHelper _readBinaryHelper; // Outer XmlReader exposed to the user - either XmlValidatingReader or XmlValidatingReaderImpl (when created via XmlReader.Create). // Virtual methods called from within XmlValidatingReaderImpl must be called on the outer reader so in case the user overrides // some of the XmlValidatingReader methods we will call the overriden version. private XmlReader _outerReader; // // Constructors // // Initializes a new instance of XmlValidatingReaderImpl class with the specified XmlReader. // This constructor is used when creating XmlValidatingReaderImpl for V1 XmlValidatingReader internal XmlValidatingReaderImpl(XmlReader reader) { XmlAsyncCheckReader asyncCheckReader = reader as XmlAsyncCheckReader; if (asyncCheckReader != null) { reader = asyncCheckReader.CoreReader; } _outerReader = this; _coreReader = reader; _coreReaderNSResolver = reader as IXmlNamespaceResolver; _coreReaderImpl = reader as XmlTextReaderImpl; if (_coreReaderImpl == null) { XmlTextReader tr = reader as XmlTextReader; if (tr != null) { _coreReaderImpl = tr.Impl; } } if (_coreReaderImpl == null) { throw new ArgumentException(SR.Arg_ExpectingXmlTextReader, nameof(reader)); } _coreReaderImpl.EntityHandling = EntityHandling.ExpandEntities; _coreReaderImpl.XmlValidatingReaderCompatibilityMode = true; _processIdentityConstraints = true; #pragma warning disable 618 _schemaCollection = new XmlSchemaCollection(_coreReader.NameTable); _schemaCollection.XmlResolver = GetResolver(); _eventHandling = new ValidationEventHandling(this); _coreReaderImpl.ValidationEventHandling = _eventHandling; _coreReaderImpl.OnDefaultAttributeUse = new XmlTextReaderImpl.OnDefaultAttributeUseDelegate(ValidateDefaultAttributeOnUse); _validationType = ValidationType.Auto; SetupValidation(ValidationType.Auto); #pragma warning restore 618 } // Initializes a new instance of XmlValidatingReaderImpl class for parsing fragments with the specified string, fragment type and parser context // This constructor is used when creating XmlValidatingReaderImpl for V1 XmlValidatingReader // SxS: This method resolves an Uri but does not expose it to the caller. It's OK to suppress the SxS warning. internal XmlValidatingReaderImpl(string xmlFragment, XmlNodeType fragType, XmlParserContext context) : this(new XmlTextReader(xmlFragment, fragType, context)) { if (_coreReader.BaseURI.Length > 0) { _validator.BaseUri = GetResolver().ResolveUri(null, _coreReader.BaseURI); } if (context != null) { _parsingFunction = ParsingFunction.ParseDtdFromContext; _parserContext = context; } } // Initializes a new instance of XmlValidatingReaderImpl class for parsing fragments with the specified stream, fragment type and parser context // This constructor is used when creating XmlValidatingReaderImpl for V1 XmlValidatingReader // SxS: This method resolves an Uri but does not expose it to the caller. It's OK to suppress the SxS warning. internal XmlValidatingReaderImpl(Stream xmlFragment, XmlNodeType fragType, XmlParserContext context) : this(new XmlTextReader(xmlFragment, fragType, context)) { if (_coreReader.BaseURI.Length > 0) { _validator.BaseUri = GetResolver().ResolveUri(null, _coreReader.BaseURI); } if (context != null) { _parsingFunction = ParsingFunction.ParseDtdFromContext; _parserContext = context; } } // Initializes a new instance of XmlValidatingReaderImpl class with the specified arguments. // This constructor is used when creating XmlValidatingReaderImpl reader via "XmlReader.Create(..)" internal XmlValidatingReaderImpl(XmlReader reader, ValidationEventHandler settingsEventHandler, bool processIdentityConstraints) { XmlAsyncCheckReader asyncCheckReader = reader as XmlAsyncCheckReader; if (asyncCheckReader != null) { reader = asyncCheckReader.CoreReader; } _outerReader = this; _coreReader = reader; _coreReaderImpl = reader as XmlTextReaderImpl; if (_coreReaderImpl == null) { XmlTextReader tr = reader as XmlTextReader; if (tr != null) { _coreReaderImpl = tr.Impl; } } if (_coreReaderImpl == null) { throw new ArgumentException(SR.Arg_ExpectingXmlTextReader, nameof(reader)); } _coreReaderImpl.XmlValidatingReaderCompatibilityMode = true; _coreReaderNSResolver = reader as IXmlNamespaceResolver; _processIdentityConstraints = processIdentityConstraints; #pragma warning disable 618 _schemaCollection = new XmlSchemaCollection(_coreReader.NameTable); #pragma warning restore 618 _schemaCollection.XmlResolver = GetResolver(); _eventHandling = new ValidationEventHandling(this); if (settingsEventHandler != null) { _eventHandling.AddHandler(settingsEventHandler); } _coreReaderImpl.ValidationEventHandling = _eventHandling; _coreReaderImpl.OnDefaultAttributeUse = new XmlTextReaderImpl.OnDefaultAttributeUseDelegate(ValidateDefaultAttributeOnUse); _validationType = ValidationType.DTD; SetupValidation(ValidationType.DTD); } // // XmlReader members // // Returns the current settings of the reader public override XmlReaderSettings Settings { get { XmlReaderSettings settings; if (_coreReaderImpl.V1Compat) { settings = null; } else { settings = _coreReader.Settings; } if (settings != null) { settings = settings.Clone(); } else { settings = new XmlReaderSettings(); } settings.ValidationType = ValidationType.DTD; if (!_processIdentityConstraints) { settings.ValidationFlags &= ~XmlSchemaValidationFlags.ProcessIdentityConstraints; } settings.ReadOnly = true; return settings; } } // Returns the type of the current node. public override XmlNodeType NodeType { get { return _coreReader.NodeType; } } // Returns the name of the current node, including prefix. public override string Name { get { return _coreReader.Name; } } // Returns local name of the current node (without prefix) public override string LocalName { get { return _coreReader.LocalName; } } // Returns namespace name of the current node. public override string NamespaceURI { get { return _coreReader.NamespaceURI; } } // Returns prefix associated with the current node. public override string Prefix { get { return _coreReader.Prefix; } } // Returns true if the current node can have Value property != string.Empty. public override bool HasValue { get { return _coreReader.HasValue; } } // Returns the text value of the current node. public override string Value { get { return _coreReader.Value; } } // Returns the depth of the current node in the XML element stack public override int Depth { get { return _coreReader.Depth; } } // Returns the base URI of the current node. public override string BaseURI { get { return _coreReader.BaseURI; } } // Returns true if the current node is an empty element (for example, <MyElement/>). public override bool IsEmptyElement { get { return _coreReader.IsEmptyElement; } } // Returns true of the current node is a default attribute declared in DTD. public override bool IsDefault { get { return _coreReader.IsDefault; } } // Returns the quote character used in the current attribute declaration public override char QuoteChar { get { return _coreReader.QuoteChar; } } // Returns the current xml:space scope. public override XmlSpace XmlSpace { get { return _coreReader.XmlSpace; } } // Returns the current xml:lang scope.</para> public override string XmlLang { get { return _coreReader.XmlLang; } } // Returns the current read state of the reader public override ReadState ReadState { get { return (_parsingFunction == ParsingFunction.Init) ? ReadState.Initial : _coreReader.ReadState; } } // Returns true if the reader reached end of the input data public override bool EOF { get { return _coreReader.EOF; } } // Returns the XmlNameTable associated with this XmlReader public override XmlNameTable NameTable { get { return _coreReader.NameTable; } } // Returns encoding of the XML document internal Encoding Encoding { get { return _coreReaderImpl.Encoding; } } // Returns the number of attributes on the current node. public override int AttributeCount { get { return _coreReader.AttributeCount; } } // Returns value of an attribute with the specified Name public override string GetAttribute(string name) { return _coreReader.GetAttribute(name); } // Returns value of an attribute with the specified LocalName and NamespaceURI public override string GetAttribute(string localName, string namespaceURI) { return _coreReader.GetAttribute(localName, namespaceURI); } // Returns value of an attribute at the specified index (position) public override string GetAttribute(int i) { return _coreReader.GetAttribute(i); } // Moves to an attribute with the specified Name public override bool MoveToAttribute(string name) { if (!_coreReader.MoveToAttribute(name)) { return false; } _parsingFunction = ParsingFunction.Read; return true; } // Moves to an attribute with the specified LocalName and NamespceURI public override bool MoveToAttribute(string localName, string namespaceURI) { if (!_coreReader.MoveToAttribute(localName, namespaceURI)) { return false; } _parsingFunction = ParsingFunction.Read; return true; } // Moves to an attribute at the specified index (position) public override void MoveToAttribute(int i) { _coreReader.MoveToAttribute(i); _parsingFunction = ParsingFunction.Read; } // Moves to the first attribute of the current node public override bool MoveToFirstAttribute() { if (!_coreReader.MoveToFirstAttribute()) { return false; } _parsingFunction = ParsingFunction.Read; return true; } // Moves to the next attribute of the current node public override bool MoveToNextAttribute() { if (!_coreReader.MoveToNextAttribute()) { return false; } _parsingFunction = ParsingFunction.Read; return true; } // If on attribute, moves to the element that contains the attribute node public override bool MoveToElement() { if (!_coreReader.MoveToElement()) { return false; } _parsingFunction = ParsingFunction.Read; return true; } // Reads and validated next node from the input data public override bool Read() { switch (_parsingFunction) { case ParsingFunction.Read: if (_coreReader.Read()) { ProcessCoreReaderEvent(); return true; } else { _validator.CompleteValidation(); return false; } case ParsingFunction.ParseDtdFromContext: _parsingFunction = ParsingFunction.Read; ParseDtdFromParserContext(); goto case ParsingFunction.Read; case ParsingFunction.Error: case ParsingFunction.ReaderClosed: return false; case ParsingFunction.Init: _parsingFunction = ParsingFunction.Read; // this changes the value returned by ReadState if (_coreReader.ReadState == ReadState.Interactive) { ProcessCoreReaderEvent(); return true; } else { goto case ParsingFunction.Read; } case ParsingFunction.ResolveEntityInternally: _parsingFunction = ParsingFunction.Read; ResolveEntityInternally(); goto case ParsingFunction.Read; case ParsingFunction.InReadBinaryContent: _parsingFunction = ParsingFunction.Read; _readBinaryHelper.Finish(); goto case ParsingFunction.Read; default: Debug.Assert(false); return false; } } // Closes the input stream ot TextReader, changes the ReadState to Closed and sets all properties to zero/string.Empty public override void Close() { _coreReader.Close(); _parsingFunction = ParsingFunction.ReaderClosed; } // Returns NamespaceURI associated with the specified prefix in the current namespace scope. public override string LookupNamespace(string prefix) { return _coreReaderImpl.LookupNamespace(prefix); } // Iterates through the current attribute value's text and entity references chunks. public override bool ReadAttributeValue() { if (_parsingFunction == ParsingFunction.InReadBinaryContent) { _parsingFunction = ParsingFunction.Read; _readBinaryHelper.Finish(); } if (!_coreReader.ReadAttributeValue()) { return false; } _parsingFunction = ParsingFunction.Read; return true; } public override bool CanReadBinaryContent { get { return true; } } public override int ReadContentAsBase64(byte[] buffer, int index, int count) { if (ReadState != ReadState.Interactive) { return 0; } // init ReadChunkHelper if called the first time if (_parsingFunction != ParsingFunction.InReadBinaryContent) { _readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, _outerReader); } // set parsingFunction to Read state in order to have a normal Read() behavior when called from readBinaryHelper _parsingFunction = ParsingFunction.Read; // call to the helper int readCount = _readBinaryHelper.ReadContentAsBase64(buffer, index, count); // setup parsingFunction _parsingFunction = ParsingFunction.InReadBinaryContent; return readCount; } public override int ReadContentAsBinHex(byte[] buffer, int index, int count) { if (ReadState != ReadState.Interactive) { return 0; } // init ReadChunkHelper when called first time if (_parsingFunction != ParsingFunction.InReadBinaryContent) { _readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, _outerReader); } // set parsingFunction to Read state in order to have a normal Read() behavior when called from readBinaryHelper _parsingFunction = ParsingFunction.Read; // call to the helper int readCount = _readBinaryHelper.ReadContentAsBinHex(buffer, index, count); // setup parsingFunction _parsingFunction = ParsingFunction.InReadBinaryContent; return readCount; } public override int ReadElementContentAsBase64(byte[] buffer, int index, int count) { if (ReadState != ReadState.Interactive) { return 0; } // init ReadChunkHelper if called the first time if (_parsingFunction != ParsingFunction.InReadBinaryContent) { _readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, _outerReader); } // set parsingFunction to Read state in order to have a normal Read() behavior when called from readBinaryHelper _parsingFunction = ParsingFunction.Read; // call to the helper int readCount = _readBinaryHelper.ReadElementContentAsBase64(buffer, index, count); // setup parsingFunction _parsingFunction = ParsingFunction.InReadBinaryContent; return readCount; } public override int ReadElementContentAsBinHex(byte[] buffer, int index, int count) { if (ReadState != ReadState.Interactive) { return 0; } // init ReadChunkHelper when called first time if (_parsingFunction != ParsingFunction.InReadBinaryContent) { _readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, _outerReader); } // set parsingFunction to Read state in order to have a normal Read() behavior when called from readBinaryHelper _parsingFunction = ParsingFunction.Read; // call to the helper int readCount = _readBinaryHelper.ReadElementContentAsBinHex(buffer, index, count); // setup parsingFunction _parsingFunction = ParsingFunction.InReadBinaryContent; return readCount; } // Returns true if the XmlReader knows how to resolve general entities public override bool CanResolveEntity { get { return true; } } // Resolves the current entity reference node public override void ResolveEntity() { if (_parsingFunction == ParsingFunction.ResolveEntityInternally) { _parsingFunction = ParsingFunction.Read; } _coreReader.ResolveEntity(); } internal XmlReader OuterReader { get { return _outerReader; } set { #pragma warning disable 618 Debug.Assert(value is XmlValidatingReader); #pragma warning restore 618 _outerReader = value; } } internal void MoveOffEntityReference() { if (_outerReader.NodeType == XmlNodeType.EntityReference && _parsingFunction != ParsingFunction.ResolveEntityInternally) { if (!_outerReader.Read()) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } } } public override string ReadString() { MoveOffEntityReference(); return base.ReadString(); } // // IXmlLineInfo members // public bool HasLineInfo() { return true; } // Returns the line number of the current node public int LineNumber { get { return ((IXmlLineInfo)_coreReader).LineNumber; } } // Returns the line number of the current node public int LinePosition { get { return ((IXmlLineInfo)_coreReader).LinePosition; } } // // IXmlNamespaceResolver members // IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope(XmlNamespaceScope scope) { return this.GetNamespacesInScope(scope); } string IXmlNamespaceResolver.LookupNamespace(string prefix) { return this.LookupNamespace(prefix); } string IXmlNamespaceResolver.LookupPrefix(string namespaceName) { return this.LookupPrefix(namespaceName); } // Internal IXmlNamespaceResolver methods internal IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope) { return _coreReaderNSResolver.GetNamespacesInScope(scope); } internal string LookupPrefix(string namespaceName) { return _coreReaderNSResolver.LookupPrefix(namespaceName); } // // XmlValidatingReader members // // Specufies the validation event handler that wil get warnings and errors related to validation internal event ValidationEventHandler ValidationEventHandler { add { _eventHandling.AddHandler(value); } remove { _eventHandling.RemoveHandler(value); ; } } // returns the schema type of the current node internal object SchemaType { get { if (_validationType != ValidationType.None) { XmlSchemaType schemaTypeObj = _coreReaderImpl.InternalSchemaType as XmlSchemaType; if (schemaTypeObj != null && schemaTypeObj.QualifiedName.Namespace == XmlReservedNs.NsXs) { return schemaTypeObj.Datatype; } return _coreReaderImpl.InternalSchemaType; } else return null; } } // returns the underlying XmlTextReader or XmlTextReaderImpl internal XmlReader Reader { get { return (XmlReader)_coreReader; } } // returns the underlying XmlTextReaderImpl internal XmlTextReaderImpl ReaderImpl { get { return _coreReaderImpl; } } // specifies the validation type (None, DDT, XSD, XDR, Auto) internal ValidationType ValidationType { get { return _validationType; } set { if (ReadState != ReadState.Initial) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } _validationType = value; SetupValidation(value); } } // current schema collection used for validationg #pragma warning disable 618 internal XmlSchemaCollection Schemas { get { return _schemaCollection; } } #pragma warning restore 618 // Spefifies whether general entities should be automatically expanded or not internal EntityHandling EntityHandling { get { return _coreReaderImpl.EntityHandling; } set { _coreReaderImpl.EntityHandling = value; } } // Specifies XmlResolver used for opening the XML document and other external references internal XmlResolver XmlResolver { set { _coreReaderImpl.XmlResolver = value; _validator.XmlResolver = value; _schemaCollection.XmlResolver = value; } } // Disables or enables support of W3C XML 1.0 Namespaces internal bool Namespaces { get { return _coreReaderImpl.Namespaces; } set { _coreReaderImpl.Namespaces = value; } } // Returns typed value of the current node (based on the type specified by schema) public object ReadTypedValue() { if (_validationType == ValidationType.None) { return null; } switch (_outerReader.NodeType) { case XmlNodeType.Attribute: return _coreReaderImpl.InternalTypedValue; case XmlNodeType.Element: if (SchemaType == null) { return null; } XmlSchemaDatatype dtype = (SchemaType is XmlSchemaDatatype) ? (XmlSchemaDatatype)SchemaType : ((XmlSchemaType)SchemaType).Datatype; if (dtype != null) { if (!_outerReader.IsEmptyElement) { for (;;) { if (!_outerReader.Read()) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } XmlNodeType type = _outerReader.NodeType; if (type != XmlNodeType.CDATA && type != XmlNodeType.Text && type != XmlNodeType.Whitespace && type != XmlNodeType.SignificantWhitespace && type != XmlNodeType.Comment && type != XmlNodeType.ProcessingInstruction) { break; } } if (_outerReader.NodeType != XmlNodeType.EndElement) { throw new XmlException(SR.Xml_InvalidNodeType, _outerReader.NodeType.ToString()); } } return _coreReaderImpl.InternalTypedValue; } return null; case XmlNodeType.EndElement: return null; default: if (_coreReaderImpl.V1Compat) { //If v1 XmlValidatingReader return null return null; } else { return Value; } } } // // Private implementation methods // private void ParseDtdFromParserContext() { Debug.Assert(_parserContext != null); Debug.Assert(_coreReaderImpl.DtdInfo == null); if (_parserContext.DocTypeName == null || _parserContext.DocTypeName.Length == 0) { return; } IDtdParser dtdParser = DtdParser.Create(); XmlTextReaderImpl.DtdParserProxy proxy = new XmlTextReaderImpl.DtdParserProxy(_coreReaderImpl); IDtdInfo dtdInfo = dtdParser.ParseFreeFloatingDtd(_parserContext.BaseURI, _parserContext.DocTypeName, _parserContext.PublicId, _parserContext.SystemId, _parserContext.InternalSubset, proxy); _coreReaderImpl.SetDtdInfo(dtdInfo); ValidateDtd(); } private void ValidateDtd() { IDtdInfo dtdInfo = _coreReaderImpl.DtdInfo; if (dtdInfo != null) { switch (_validationType) { #pragma warning disable 618 case ValidationType.Auto: SetupValidation(ValidationType.DTD); goto case ValidationType.DTD; #pragma warning restore 618 case ValidationType.DTD: case ValidationType.None: _validator.DtdInfo = dtdInfo; break; } } } private void ResolveEntityInternally() { Debug.Assert(_coreReader.NodeType == XmlNodeType.EntityReference); int initialDepth = _coreReader.Depth; _outerReader.ResolveEntity(); while (_outerReader.Read() && _coreReader.Depth > initialDepth) ; } // SxS: This method resolves an Uri but does not expose it to caller. It's OK to suppress the SxS warning. private void SetupValidation(ValidationType valType) { _validator = BaseValidator.CreateInstance(valType, this, _schemaCollection, _eventHandling, _processIdentityConstraints); XmlResolver resolver = GetResolver(); _validator.XmlResolver = resolver; if (_outerReader.BaseURI.Length > 0) { _validator.BaseUri = (resolver == null) ? new Uri(_outerReader.BaseURI, UriKind.RelativeOrAbsolute) : resolver.ResolveUri(null, _outerReader.BaseURI); } _coreReaderImpl.ValidationEventHandling = (_validationType == ValidationType.None) ? null : _eventHandling; } private static XmlResolver s_tempResolver; // This is needed because we can't have the setter for XmlResolver public and with internal getter. private XmlResolver GetResolver() { XmlResolver tempResolver = _coreReaderImpl.GetResolver(); if (tempResolver == null && !_coreReaderImpl.IsResolverSet) { // it is safe to return valid resolver as it'll be used in the schema validation if (s_tempResolver == null) s_tempResolver = new XmlUrlResolver(); return s_tempResolver; } return tempResolver; } // // Internal methods for validators, DOM, XPathDocument etc. // private void ProcessCoreReaderEvent() { switch (_coreReader.NodeType) { case XmlNodeType.Whitespace: if (_coreReader.Depth > 0 || _coreReaderImpl.FragmentType != XmlNodeType.Document) { if (_validator.PreserveWhitespace) { _coreReaderImpl.ChangeCurrentNodeType(XmlNodeType.SignificantWhitespace); } } goto default; case XmlNodeType.DocumentType: ValidateDtd(); break; case XmlNodeType.EntityReference: _parsingFunction = ParsingFunction.ResolveEntityInternally; goto default; default: _coreReaderImpl.InternalSchemaType = null; _coreReaderImpl.InternalTypedValue = null; _validator.Validate(); break; } } internal BaseValidator Validator { get { return _validator; } set { _validator = value; } } internal override XmlNamespaceManager NamespaceManager { get { return _coreReaderImpl.NamespaceManager; } } internal bool StandAlone { get { return _coreReaderImpl.StandAlone; } } internal object SchemaTypeObject { set { _coreReaderImpl.InternalSchemaType = value; } } internal object TypedValueObject { get { return _coreReaderImpl.InternalTypedValue; } set { _coreReaderImpl.InternalTypedValue = value; } } internal bool AddDefaultAttribute(SchemaAttDef attdef) { return _coreReaderImpl.AddDefaultAttributeNonDtd(attdef); } internal override IDtdInfo DtdInfo { get { return _coreReaderImpl.DtdInfo; } } internal void ValidateDefaultAttributeOnUse(IDtdDefaultAttributeInfo defaultAttribute, XmlTextReaderImpl coreReader) { SchemaAttDef attdef = defaultAttribute as SchemaAttDef; if (attdef == null) { return; } if (!attdef.DefaultValueChecked) { SchemaInfo schemaInfo = coreReader.DtdInfo as SchemaInfo; if (schemaInfo == null) { return; } DtdValidator.CheckDefaultValue(attdef, schemaInfo, _eventHandling, coreReader.BaseURI); } } } }
#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 System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.Reflection; using Newtonsoft.Json.Utilities; using System.Collections; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json.Serialization { /// <summary> /// Contract details for a <see cref="System.Type"/> used by the <see cref="JsonSerializer"/>. /// </summary> public class JsonArrayContract : JsonContainerContract { /// <summary> /// Gets the <see cref="System.Type"/> of the collection items. /// </summary> /// <value>The <see cref="System.Type"/> of the collection items.</value> public Type CollectionItemType { get; private set; } /// <summary> /// Gets a value indicating whether the collection type is a multidimensional array. /// </summary> /// <value><c>true</c> if the collection type is a multidimensional array; otherwise, <c>false</c>.</value> public bool IsMultidimensionalArray { get; private set; } private readonly Type _genericCollectionDefinitionType; private Type _genericWrapperType; private ObjectConstructor<object> _genericWrapperCreator; private Func<object> _genericTemporaryCollectionCreator; internal bool IsArray { get; private set; } internal bool ShouldCreateWrapper { get; private set; } internal bool CanDeserialize { get; private set; } private readonly ConstructorInfo _parameterizedConstructor; private ObjectConstructor<object> _parameterizedCreator; private ObjectConstructor<object> _overrideCreator; internal ObjectConstructor<object> ParameterizedCreator { get { if (_parameterizedCreator == null) { _parameterizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(_parameterizedConstructor); } return _parameterizedCreator; } } /// <summary> /// Gets or sets the function used to create the object. When set this function will override <see cref="JsonContract.DefaultCreator"/>. /// </summary> /// <value>The function used to create the object.</value> public ObjectConstructor<object> OverrideCreator { get { return _overrideCreator; } set { _overrideCreator = value; // hacky CanDeserialize = true; } } /// <summary> /// Gets a value indicating whether the creator has a parameter with the collection values. /// </summary> /// <value><c>true</c> if the creator has a parameter with the collection values; otherwise, <c>false</c>.</value> public bool HasParameterizedCreator { get; set; } internal bool HasParameterizedCreatorInternal { get { return (HasParameterizedCreator || _parameterizedCreator != null || _parameterizedConstructor != null); } } /// <summary> /// Initializes a new instance of the <see cref="JsonArrayContract"/> class. /// </summary> /// <param name="underlyingType">The underlying type for the contract.</param> public JsonArrayContract(Type underlyingType) : base(underlyingType) { ContractType = JsonContractType.Array; IsArray = CreatedType.IsArray; bool canDeserialize; Type tempCollectionType; if (IsArray) { CollectionItemType = ReflectionUtils.GetCollectionItemType(UnderlyingType); IsReadOnlyOrFixedSize = true; _genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType); canDeserialize = true; IsMultidimensionalArray = (IsArray && UnderlyingType.GetArrayRank() > 1); } else if (typeof(IList).IsAssignableFrom(underlyingType)) { if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType)) { CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0]; } else { CollectionItemType = ReflectionUtils.GetCollectionItemType(underlyingType); } if (underlyingType == typeof(IList)) { CreatedType = typeof(List<object>); } if (CollectionItemType != null) { _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType); } IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(underlyingType, typeof(ReadOnlyCollection<>)); canDeserialize = true; } else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType)) { CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0]; if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ICollection<>)) || ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IList<>))) { CreatedType = typeof(List<>).MakeGenericType(CollectionItemType); } #if !(NET20 || NET35) if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ISet<>))) { CreatedType = typeof(HashSet<>).MakeGenericType(CollectionItemType); } #endif _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType); canDeserialize = true; ShouldCreateWrapper = true; } #if !(NET40 || NET35 || NET20 || PORTABLE40) else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IReadOnlyCollection<>), out tempCollectionType)) { CollectionItemType = tempCollectionType.GetGenericArguments()[0]; if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IReadOnlyCollection<>)) || ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IReadOnlyList<>))) { CreatedType = typeof(ReadOnlyCollection<>).MakeGenericType(CollectionItemType); } _genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType); _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(CreatedType, CollectionItemType); IsReadOnlyOrFixedSize = true; canDeserialize = HasParameterizedCreatorInternal; } #endif else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IEnumerable<>), out tempCollectionType)) { CollectionItemType = tempCollectionType.GetGenericArguments()[0]; if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IEnumerable<>))) { CreatedType = typeof(List<>).MakeGenericType(CollectionItemType); } _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType); #if !(NET35 || NET20) if (!HasParameterizedCreatorInternal && underlyingType.Name == FSharpUtils.FSharpListTypeName) { FSharpUtils.EnsureInitialized(underlyingType.Assembly()); _parameterizedCreator = FSharpUtils.CreateSeq(CollectionItemType); } #endif if (underlyingType.IsGenericType() && underlyingType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) { _genericCollectionDefinitionType = tempCollectionType; IsReadOnlyOrFixedSize = false; ShouldCreateWrapper = false; canDeserialize = true; } else { _genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType); IsReadOnlyOrFixedSize = true; ShouldCreateWrapper = true; canDeserialize = HasParameterizedCreatorInternal; } } else { // types that implement IEnumerable and nothing else canDeserialize = false; ShouldCreateWrapper = true; } CanDeserialize = canDeserialize; #if (NET20 || NET35) if (CollectionItemType != null && ReflectionUtils.IsNullableType(CollectionItemType)) { // bug in .NET 2.0 & 3.5 that List<Nullable<T>> throws an error when adding null via IList.Add(object) // wrapper will handle calling Add(T) instead if (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(List<>), out tempCollectionType) || (IsArray && !IsMultidimensionalArray)) { ShouldCreateWrapper = true; } } #endif #if !(NET20 || NET35 || NET40) Type immutableCreatedType; ObjectConstructor<object> immutableParameterizedCreator; if (ImmutableCollectionsUtils.TryBuildImmutableForArrayContract(underlyingType, CollectionItemType, out immutableCreatedType, out immutableParameterizedCreator)) { CreatedType = immutableCreatedType; _parameterizedCreator = immutableParameterizedCreator; IsReadOnlyOrFixedSize = true; CanDeserialize = true; } #endif } internal IWrappedCollection CreateWrapper(object list) { if (_genericWrapperCreator == null) { _genericWrapperType = typeof(CollectionWrapper<>).MakeGenericType(CollectionItemType); Type constructorArgument; if (ReflectionUtils.InheritsGenericDefinition(_genericCollectionDefinitionType, typeof(List<>)) || _genericCollectionDefinitionType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) { constructorArgument = typeof(ICollection<>).MakeGenericType(CollectionItemType); } else { constructorArgument = _genericCollectionDefinitionType; } ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { constructorArgument }); _genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(genericWrapperConstructor); } return (IWrappedCollection)_genericWrapperCreator(list); } internal IList CreateTemporaryCollection() { if (_genericTemporaryCollectionCreator == null) { // multidimensional array will also have array instances in it Type collectionItemType = (IsMultidimensionalArray || CollectionItemType == null) ? typeof(object) : CollectionItemType; Type temporaryListType = typeof(List<>).MakeGenericType(collectionItemType); _genericTemporaryCollectionCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor<object>(temporaryListType); } return (IList)_genericTemporaryCollectionCreator(); } } }
using System; using System.Data; using Csla; using Csla.Data; using ParentLoadSoftDelete.DataAccess; using ParentLoadSoftDelete.DataAccess.ERLevel; namespace ParentLoadSoftDelete.Business.ERLevel { /// <summary> /// E10_City (editable child object).<br/> /// This is a generated base class of <see cref="E10_City"/> business object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="E11_CityRoadObjects"/> of type <see cref="E11_CityRoadColl"/> (1:M relation to <see cref="E12_CityRoad"/>)<br/> /// This class is an item of <see cref="E09_CityColl"/> collection. /// </remarks> [Serializable] public partial class E10_City : BusinessBase<E10_City> { #region Static Fields private static int _lastID; #endregion #region State Fields [NotUndoable] [NonSerialized] internal int parent_Region_ID = 0; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="City_ID"/> property. /// </summary> public static readonly PropertyInfo<int> City_IDProperty = RegisterProperty<int>(p => p.City_ID, "Cities ID"); /// <summary> /// Gets the Cities ID. /// </summary> /// <value>The Cities ID.</value> public int City_ID { get { return GetProperty(City_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="City_Name"/> property. /// </summary> public static readonly PropertyInfo<string> City_NameProperty = RegisterProperty<string>(p => p.City_Name, "Cities Name"); /// <summary> /// Gets or sets the Cities Name. /// </summary> /// <value>The Cities Name.</value> public string City_Name { get { return GetProperty(City_NameProperty); } set { SetProperty(City_NameProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="E11_City_SingleObject"/> property. /// </summary> public static readonly PropertyInfo<E11_City_Child> E11_City_SingleObjectProperty = RegisterProperty<E11_City_Child>(p => p.E11_City_SingleObject, "E11 City Single Object", RelationshipTypes.Child); /// <summary> /// Gets the E11 City Single Object ("parent load" child property). /// </summary> /// <value>The E11 City Single Object.</value> public E11_City_Child E11_City_SingleObject { get { return GetProperty(E11_City_SingleObjectProperty); } private set { LoadProperty(E11_City_SingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="E11_City_ASingleObject"/> property. /// </summary> public static readonly PropertyInfo<E11_City_ReChild> E11_City_ASingleObjectProperty = RegisterProperty<E11_City_ReChild>(p => p.E11_City_ASingleObject, "E11 City ASingle Object", RelationshipTypes.Child); /// <summary> /// Gets the E11 City ASingle Object ("parent load" child property). /// </summary> /// <value>The E11 City ASingle Object.</value> public E11_City_ReChild E11_City_ASingleObject { get { return GetProperty(E11_City_ASingleObjectProperty); } private set { LoadProperty(E11_City_ASingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="E11_CityRoadObjects"/> property. /// </summary> public static readonly PropertyInfo<E11_CityRoadColl> E11_CityRoadObjectsProperty = RegisterProperty<E11_CityRoadColl>(p => p.E11_CityRoadObjects, "E11 CityRoad Objects", RelationshipTypes.Child); /// <summary> /// Gets the E11 City Road Objects ("parent load" child property). /// </summary> /// <value>The E11 City Road Objects.</value> public E11_CityRoadColl E11_CityRoadObjects { get { return GetProperty(E11_CityRoadObjectsProperty); } private set { LoadProperty(E11_CityRoadObjectsProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="E10_City"/> object. /// </summary> /// <returns>A reference to the created <see cref="E10_City"/> object.</returns> internal static E10_City NewE10_City() { return DataPortal.CreateChild<E10_City>(); } /// <summary> /// Factory method. Loads a <see cref="E10_City"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="E10_City"/> object.</returns> internal static E10_City GetE10_City(SafeDataReader dr) { E10_City obj = new E10_City(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.LoadProperty(E11_CityRoadObjectsProperty, E11_CityRoadColl.NewE11_CityRoadColl()); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="E10_City"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public E10_City() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="E10_City"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { LoadProperty(City_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID)); LoadProperty(E11_City_SingleObjectProperty, DataPortal.CreateChild<E11_City_Child>()); LoadProperty(E11_City_ASingleObjectProperty, DataPortal.CreateChild<E11_City_ReChild>()); LoadProperty(E11_CityRoadObjectsProperty, DataPortal.CreateChild<E11_CityRoadColl>()); var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="E10_City"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(City_IDProperty, dr.GetInt32("City_ID")); LoadProperty(City_NameProperty, dr.GetString("City_Name")); // parent properties parent_Region_ID = dr.GetInt32("Parent_Region_ID"); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Loads child <see cref="E11_City_Child"/> object. /// </summary> /// <param name="child">The child object to load.</param> internal void LoadChild(E11_City_Child child) { LoadProperty(E11_City_SingleObjectProperty, child); } /// <summary> /// Loads child <see cref="E11_City_ReChild"/> object. /// </summary> /// <param name="child">The child object to load.</param> internal void LoadChild(E11_City_ReChild child) { LoadProperty(E11_City_ASingleObjectProperty, child); } /// <summary> /// Inserts a new <see cref="E10_City"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(E08_Region parent) { using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnInsertPre(args); var dal = dalManager.GetProvider<IE10_CityDal>(); using (BypassPropertyChecks) { int city_ID = -1; dal.Insert( parent.Region_ID, out city_ID, City_Name ); LoadProperty(City_IDProperty, city_ID); } OnInsertPost(args); // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Updates in the database all changes made to the <see cref="E10_City"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update() { if (!IsDirty) return; using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnUpdatePre(args); var dal = dalManager.GetProvider<IE10_CityDal>(); using (BypassPropertyChecks) { dal.Update( City_ID, City_Name ); } OnUpdatePost(args); // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Self deletes the <see cref="E10_City"/> object from database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf() { using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); // flushes all pending data operations FieldManager.UpdateChildren(this); OnDeletePre(args); var dal = dalManager.GetProvider<IE10_CityDal>(); using (BypassPropertyChecks) { dal.Delete(ReadProperty(City_IDProperty)); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvc = Google.Ads.GoogleAds.V8.Common; using gagve = Google.Ads.GoogleAds.V8.Enums; using gagvr = Google.Ads.GoogleAds.V8.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using gr = Google.Rpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V8.Services; namespace Google.Ads.GoogleAds.Tests.V8.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedAssetServiceClientTest { [Category("Autogenerated")][Test] public void GetAssetRequestObject() { moq::Mock<AssetService.AssetServiceClient> mockGrpcClient = new moq::Mock<AssetService.AssetServiceClient>(moq::MockBehavior.Strict); GetAssetRequest request = new GetAssetRequest { ResourceNameAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"), }; gagvr::Asset expectedResponse = new gagvr::Asset { ResourceNameAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"), Type = gagve::AssetTypeEnum.Types.AssetType.MediaBundle, YoutubeVideoAsset = new gagvc::YoutubeVideoAsset(), MediaBundleAsset = new gagvc::MediaBundleAsset(), ImageAsset = new gagvc::ImageAsset(), TextAsset = new gagvc::TextAsset(), LeadFormAsset = new gagvc::LeadFormAsset(), BookOnGoogleAsset = new gagvc::BookOnGoogleAsset(), Id = -6774108720365892680L, AssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"), PolicySummary = new gagvr::AssetPolicySummary(), FinalUrls = { "final_urls3ed0b71b", }, PromotionAsset = new gagvc::PromotionAsset(), FinalMobileUrls = { "final_mobile_urlsf4131aa0", }, TrackingUrlTemplate = "tracking_url_template157f152a", UrlCustomParameters = { new gagvc::CustomParameter(), }, FinalUrlSuffix = "final_url_suffix046ed37a", CalloutAsset = new gagvc::CalloutAsset(), StructuredSnippetAsset = new gagvc::StructuredSnippetAsset(), SitelinkAsset = new gagvc::SitelinkAsset(), }; mockGrpcClient.Setup(x => x.GetAsset(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AssetServiceClient client = new AssetServiceClientImpl(mockGrpcClient.Object, null); gagvr::Asset response = client.GetAsset(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAssetRequestObjectAsync() { moq::Mock<AssetService.AssetServiceClient> mockGrpcClient = new moq::Mock<AssetService.AssetServiceClient>(moq::MockBehavior.Strict); GetAssetRequest request = new GetAssetRequest { ResourceNameAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"), }; gagvr::Asset expectedResponse = new gagvr::Asset { ResourceNameAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"), Type = gagve::AssetTypeEnum.Types.AssetType.MediaBundle, YoutubeVideoAsset = new gagvc::YoutubeVideoAsset(), MediaBundleAsset = new gagvc::MediaBundleAsset(), ImageAsset = new gagvc::ImageAsset(), TextAsset = new gagvc::TextAsset(), LeadFormAsset = new gagvc::LeadFormAsset(), BookOnGoogleAsset = new gagvc::BookOnGoogleAsset(), Id = -6774108720365892680L, AssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"), PolicySummary = new gagvr::AssetPolicySummary(), FinalUrls = { "final_urls3ed0b71b", }, PromotionAsset = new gagvc::PromotionAsset(), FinalMobileUrls = { "final_mobile_urlsf4131aa0", }, TrackingUrlTemplate = "tracking_url_template157f152a", UrlCustomParameters = { new gagvc::CustomParameter(), }, FinalUrlSuffix = "final_url_suffix046ed37a", CalloutAsset = new gagvc::CalloutAsset(), StructuredSnippetAsset = new gagvc::StructuredSnippetAsset(), SitelinkAsset = new gagvc::SitelinkAsset(), }; mockGrpcClient.Setup(x => x.GetAssetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::Asset>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AssetServiceClient client = new AssetServiceClientImpl(mockGrpcClient.Object, null); gagvr::Asset responseCallSettings = await client.GetAssetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::Asset responseCancellationToken = await client.GetAssetAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetAsset() { moq::Mock<AssetService.AssetServiceClient> mockGrpcClient = new moq::Mock<AssetService.AssetServiceClient>(moq::MockBehavior.Strict); GetAssetRequest request = new GetAssetRequest { ResourceNameAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"), }; gagvr::Asset expectedResponse = new gagvr::Asset { ResourceNameAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"), Type = gagve::AssetTypeEnum.Types.AssetType.MediaBundle, YoutubeVideoAsset = new gagvc::YoutubeVideoAsset(), MediaBundleAsset = new gagvc::MediaBundleAsset(), ImageAsset = new gagvc::ImageAsset(), TextAsset = new gagvc::TextAsset(), LeadFormAsset = new gagvc::LeadFormAsset(), BookOnGoogleAsset = new gagvc::BookOnGoogleAsset(), Id = -6774108720365892680L, AssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"), PolicySummary = new gagvr::AssetPolicySummary(), FinalUrls = { "final_urls3ed0b71b", }, PromotionAsset = new gagvc::PromotionAsset(), FinalMobileUrls = { "final_mobile_urlsf4131aa0", }, TrackingUrlTemplate = "tracking_url_template157f152a", UrlCustomParameters = { new gagvc::CustomParameter(), }, FinalUrlSuffix = "final_url_suffix046ed37a", CalloutAsset = new gagvc::CalloutAsset(), StructuredSnippetAsset = new gagvc::StructuredSnippetAsset(), SitelinkAsset = new gagvc::SitelinkAsset(), }; mockGrpcClient.Setup(x => x.GetAsset(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AssetServiceClient client = new AssetServiceClientImpl(mockGrpcClient.Object, null); gagvr::Asset response = client.GetAsset(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAssetAsync() { moq::Mock<AssetService.AssetServiceClient> mockGrpcClient = new moq::Mock<AssetService.AssetServiceClient>(moq::MockBehavior.Strict); GetAssetRequest request = new GetAssetRequest { ResourceNameAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"), }; gagvr::Asset expectedResponse = new gagvr::Asset { ResourceNameAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"), Type = gagve::AssetTypeEnum.Types.AssetType.MediaBundle, YoutubeVideoAsset = new gagvc::YoutubeVideoAsset(), MediaBundleAsset = new gagvc::MediaBundleAsset(), ImageAsset = new gagvc::ImageAsset(), TextAsset = new gagvc::TextAsset(), LeadFormAsset = new gagvc::LeadFormAsset(), BookOnGoogleAsset = new gagvc::BookOnGoogleAsset(), Id = -6774108720365892680L, AssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"), PolicySummary = new gagvr::AssetPolicySummary(), FinalUrls = { "final_urls3ed0b71b", }, PromotionAsset = new gagvc::PromotionAsset(), FinalMobileUrls = { "final_mobile_urlsf4131aa0", }, TrackingUrlTemplate = "tracking_url_template157f152a", UrlCustomParameters = { new gagvc::CustomParameter(), }, FinalUrlSuffix = "final_url_suffix046ed37a", CalloutAsset = new gagvc::CalloutAsset(), StructuredSnippetAsset = new gagvc::StructuredSnippetAsset(), SitelinkAsset = new gagvc::SitelinkAsset(), }; mockGrpcClient.Setup(x => x.GetAssetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::Asset>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AssetServiceClient client = new AssetServiceClientImpl(mockGrpcClient.Object, null); gagvr::Asset responseCallSettings = await client.GetAssetAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::Asset responseCancellationToken = await client.GetAssetAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetAssetResourceNames() { moq::Mock<AssetService.AssetServiceClient> mockGrpcClient = new moq::Mock<AssetService.AssetServiceClient>(moq::MockBehavior.Strict); GetAssetRequest request = new GetAssetRequest { ResourceNameAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"), }; gagvr::Asset expectedResponse = new gagvr::Asset { ResourceNameAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"), Type = gagve::AssetTypeEnum.Types.AssetType.MediaBundle, YoutubeVideoAsset = new gagvc::YoutubeVideoAsset(), MediaBundleAsset = new gagvc::MediaBundleAsset(), ImageAsset = new gagvc::ImageAsset(), TextAsset = new gagvc::TextAsset(), LeadFormAsset = new gagvc::LeadFormAsset(), BookOnGoogleAsset = new gagvc::BookOnGoogleAsset(), Id = -6774108720365892680L, AssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"), PolicySummary = new gagvr::AssetPolicySummary(), FinalUrls = { "final_urls3ed0b71b", }, PromotionAsset = new gagvc::PromotionAsset(), FinalMobileUrls = { "final_mobile_urlsf4131aa0", }, TrackingUrlTemplate = "tracking_url_template157f152a", UrlCustomParameters = { new gagvc::CustomParameter(), }, FinalUrlSuffix = "final_url_suffix046ed37a", CalloutAsset = new gagvc::CalloutAsset(), StructuredSnippetAsset = new gagvc::StructuredSnippetAsset(), SitelinkAsset = new gagvc::SitelinkAsset(), }; mockGrpcClient.Setup(x => x.GetAsset(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AssetServiceClient client = new AssetServiceClientImpl(mockGrpcClient.Object, null); gagvr::Asset response = client.GetAsset(request.ResourceNameAsAssetName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAssetResourceNamesAsync() { moq::Mock<AssetService.AssetServiceClient> mockGrpcClient = new moq::Mock<AssetService.AssetServiceClient>(moq::MockBehavior.Strict); GetAssetRequest request = new GetAssetRequest { ResourceNameAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"), }; gagvr::Asset expectedResponse = new gagvr::Asset { ResourceNameAsAssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"), Type = gagve::AssetTypeEnum.Types.AssetType.MediaBundle, YoutubeVideoAsset = new gagvc::YoutubeVideoAsset(), MediaBundleAsset = new gagvc::MediaBundleAsset(), ImageAsset = new gagvc::ImageAsset(), TextAsset = new gagvc::TextAsset(), LeadFormAsset = new gagvc::LeadFormAsset(), BookOnGoogleAsset = new gagvc::BookOnGoogleAsset(), Id = -6774108720365892680L, AssetName = gagvr::AssetName.FromCustomerAsset("[CUSTOMER_ID]", "[ASSET_ID]"), PolicySummary = new gagvr::AssetPolicySummary(), FinalUrls = { "final_urls3ed0b71b", }, PromotionAsset = new gagvc::PromotionAsset(), FinalMobileUrls = { "final_mobile_urlsf4131aa0", }, TrackingUrlTemplate = "tracking_url_template157f152a", UrlCustomParameters = { new gagvc::CustomParameter(), }, FinalUrlSuffix = "final_url_suffix046ed37a", CalloutAsset = new gagvc::CalloutAsset(), StructuredSnippetAsset = new gagvc::StructuredSnippetAsset(), SitelinkAsset = new gagvc::SitelinkAsset(), }; mockGrpcClient.Setup(x => x.GetAssetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::Asset>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AssetServiceClient client = new AssetServiceClientImpl(mockGrpcClient.Object, null); gagvr::Asset responseCallSettings = await client.GetAssetAsync(request.ResourceNameAsAssetName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::Asset responseCancellationToken = await client.GetAssetAsync(request.ResourceNameAsAssetName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateAssetsRequestObject() { moq::Mock<AssetService.AssetServiceClient> mockGrpcClient = new moq::Mock<AssetService.AssetServiceClient>(moq::MockBehavior.Strict); MutateAssetsRequest request = new MutateAssetsRequest { CustomerId = "customer_id3b3724cb", Operations = { new AssetOperation(), }, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, ValidateOnly = true, PartialFailure = false, }; MutateAssetsResponse expectedResponse = new MutateAssetsResponse { Results = { new MutateAssetResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateAssets(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AssetServiceClient client = new AssetServiceClientImpl(mockGrpcClient.Object, null); MutateAssetsResponse response = client.MutateAssets(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateAssetsRequestObjectAsync() { moq::Mock<AssetService.AssetServiceClient> mockGrpcClient = new moq::Mock<AssetService.AssetServiceClient>(moq::MockBehavior.Strict); MutateAssetsRequest request = new MutateAssetsRequest { CustomerId = "customer_id3b3724cb", Operations = { new AssetOperation(), }, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, ValidateOnly = true, PartialFailure = false, }; MutateAssetsResponse expectedResponse = new MutateAssetsResponse { Results = { new MutateAssetResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateAssetsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateAssetsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AssetServiceClient client = new AssetServiceClientImpl(mockGrpcClient.Object, null); MutateAssetsResponse responseCallSettings = await client.MutateAssetsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateAssetsResponse responseCancellationToken = await client.MutateAssetsAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateAssets() { moq::Mock<AssetService.AssetServiceClient> mockGrpcClient = new moq::Mock<AssetService.AssetServiceClient>(moq::MockBehavior.Strict); MutateAssetsRequest request = new MutateAssetsRequest { CustomerId = "customer_id3b3724cb", Operations = { new AssetOperation(), }, }; MutateAssetsResponse expectedResponse = new MutateAssetsResponse { Results = { new MutateAssetResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateAssets(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AssetServiceClient client = new AssetServiceClientImpl(mockGrpcClient.Object, null); MutateAssetsResponse response = client.MutateAssets(request.CustomerId, request.Operations); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateAssetsAsync() { moq::Mock<AssetService.AssetServiceClient> mockGrpcClient = new moq::Mock<AssetService.AssetServiceClient>(moq::MockBehavior.Strict); MutateAssetsRequest request = new MutateAssetsRequest { CustomerId = "customer_id3b3724cb", Operations = { new AssetOperation(), }, }; MutateAssetsResponse expectedResponse = new MutateAssetsResponse { Results = { new MutateAssetResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateAssetsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateAssetsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AssetServiceClient client = new AssetServiceClientImpl(mockGrpcClient.Object, null); MutateAssetsResponse responseCallSettings = await client.MutateAssetsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateAssetsResponse responseCancellationToken = await client.MutateAssetsAsync(request.CustomerId, request.Operations, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Numerics; using System.Text; using ValveResourceFormat.Serialization; using ValveResourceFormat.Utils; namespace ValveResourceFormat.ResourceTypes { public class EntityLump : KeyValuesOrNTRO { public class Entity { public Dictionary<uint, EntityProperty> Properties { get; } = new Dictionary<uint, EntityProperty>(); public T GetProperty<T>(string name) => GetProperty<T>(EntityLumpKeyLookup.Get(name)); public EntityProperty GetProperty(string name) => GetProperty(EntityLumpKeyLookup.Get(name)); public T GetProperty<T>(uint hash) { if (Properties.TryGetValue(hash, out var property)) { return (T)property.Data; } return default; } public EntityProperty GetProperty(uint hash) { if (Properties.TryGetValue(hash, out var property)) { return property; } return default; } } public class EntityProperty { public uint Type { get; set; } public string Name { get; set; } public object Data { get; set; } } public IEnumerable<string> GetChildEntityNames() { return Data.GetArray<string>("m_childLumps"); } public IEnumerable<Entity> GetEntities() => Data.GetArray("m_entityKeyValues") .Select(entity => ParseEntityProperties(entity.GetArray<byte>("m_keyValuesData"))) .ToList(); private static Entity ParseEntityProperties(byte[] bytes) { using (var dataStream = new MemoryStream(bytes)) using (var dataReader = new BinaryReader(dataStream)) { var a = dataReader.ReadUInt32(); // always 1? if (a != 1) { throw new NotImplementedException($"First field in entity lump is not 1"); } var hashedFieldsCount = dataReader.ReadUInt32(); var stringFieldsCount = dataReader.ReadUInt32(); var entity = new Entity(); void ReadTypedValue(uint keyHash, string keyName) { var type = dataReader.ReadUInt32(); var entityProperty = new EntityProperty { Type = type, Name = keyName, }; switch (type) { case 0x06: // boolean entityProperty.Data = dataReader.ReadBoolean(); // 1 break; case 0x01: // float entityProperty.Data = dataReader.ReadSingle(); // 4 break; case 0x09: // color255 entityProperty.Data = dataReader.ReadBytes(4); // 4 break; case 0x05: // node_id case 0x25: // flags entityProperty.Data = dataReader.ReadUInt32(); // 4 break; case 0x1a: // integer entityProperty.Data = dataReader.ReadUInt64(); // 8 break; case 0x03: // vector case 0x27: // angle entityProperty.Data = new Vector3(dataReader.ReadSingle(), dataReader.ReadSingle(), dataReader.ReadSingle()); // 12 break; case 0x1e: // string entityProperty.Data = dataReader.ReadNullTermString(Encoding.UTF8); // null term variable break; default: throw new NotImplementedException($"Unknown type {type}"); } entity.Properties.Add(keyHash, entityProperty); } for (var i = 0; i < hashedFieldsCount; i++) { // murmur2 hashed field name (see EntityLumpKeyLookup) var keyHash = dataReader.ReadUInt32(); ReadTypedValue(keyHash, null); } for (var i = 0; i < stringFieldsCount; i++) { var keyHash = dataReader.ReadUInt32(); var keyName = dataReader.ReadNullTermString(Encoding.UTF8); ReadTypedValue(keyHash, keyName); } return entity; } } public override string ToString() { var knownKeys = new EntityLumpKnownKeys().Fields; var builder = new StringBuilder(); var unknownKeys = new Dictionary<uint, uint>(); var types = new Dictionary<uint, string> { { 0x01, "float" }, { 0x03, "vector" }, { 0x05, "node_id" }, { 0x06, "boolean" }, { 0x09, "color255" }, { 0x1a, "integer" }, { 0x1e, "string" }, { 0x25, "flags" }, { 0x27, "angle" }, }; var index = 0; foreach (var entity in GetEntities()) { builder.AppendLine($"===={index++}===="); foreach (var property in entity.Properties) { var value = property.Value.Data; if (value.GetType() == typeof(byte[])) { var tmp = value as byte[]; value = $"Array [{string.Join(", ", tmp.Select(p => p.ToString()).ToArray())}]"; } string key; if (knownKeys.ContainsKey(property.Key)) { key = knownKeys[property.Key]; } else if (property.Value.Name != null) { key = property.Value.Name; } else { key = $"key={property.Key}"; if (!unknownKeys.ContainsKey(property.Key)) { unknownKeys.Add(property.Key, 1); } else { unknownKeys[property.Key]++; } } builder.AppendLine($"{key,-30} {types[property.Value.Type],-10} {value}"); } builder.AppendLine(); } if (unknownKeys.Count > 0) { builder.AppendLine($"@@@@@ UNKNOWN KEY LOOKUPS:"); builder.AppendLine($"If you know what these are, add them to EntityLumpKnownKeys.cs"); foreach (var unknownKey in unknownKeys) { builder.AppendLine($"key={unknownKey.Key} hits={unknownKey.Value}"); } } return builder.ToString(); } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Threading.Tasks; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Effects; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; using osu.Framework.Input.Events; using osu.Framework.Localisation; using osu.Game.Beatmaps; using osu.Game.Graphics; using osu.Game.Graphics.Containers; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osu.Game.Localisation; using osu.Game.Overlays.Music; using osuTK; using osuTK.Graphics; namespace osu.Game.Overlays { public class NowPlayingOverlay : OsuFocusedOverlayContainer, INamedOverlayComponent { public string IconTexture => "Icons/Hexacons/music"; public LocalisableString Title => NowPlayingStrings.HeaderTitle; public LocalisableString Description => NowPlayingStrings.HeaderDescription; private const float player_height = 130; private const float transition_length = 800; private const float progress_height = 10; private const float bottom_black_area_height = 55; private Drawable background; private ProgressBar progressBar; private IconButton prevButton; private IconButton playButton; private IconButton nextButton; private IconButton playlistButton; private SpriteText title, artist; private PlaylistOverlay playlist; private Container dragContainer; private Container playerContainer; protected override string PopInSampleName => "UI/now-playing-pop-in"; protected override string PopOutSampleName => "UI/now-playing-pop-out"; [Resolved] private MusicController musicController { get; set; } [Resolved] private Bindable<WorkingBeatmap> beatmap { get; set; } [Resolved] private OsuColour colours { get; set; } public NowPlayingOverlay() { Width = 400; Margin = new MarginPadding(10); } [BackgroundDependencyLoader] private void load() { Children = new Drawable[] { dragContainer = new DragContainer { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Children = new Drawable[] { playerContainer = new Container { RelativeSizeAxes = Axes.X, Height = player_height, Masking = true, CornerRadius = 5, EdgeEffect = new EdgeEffectParameters { Type = EdgeEffectType.Shadow, Colour = Color4.Black.Opacity(40), Radius = 5, }, Children = new[] { background = new Background(), title = new OsuSpriteText { Origin = Anchor.BottomCentre, Anchor = Anchor.TopCentre, Position = new Vector2(0, 40), Font = OsuFont.GetFont(size: 25, italics: true), Colour = Color4.White, Text = @"Nothing to play", }, artist = new OsuSpriteText { Origin = Anchor.TopCentre, Anchor = Anchor.TopCentre, Position = new Vector2(0, 45), Font = OsuFont.GetFont(size: 15, weight: FontWeight.Bold, italics: true), Colour = Color4.White, Text = @"Nothing to play", }, new Container { Padding = new MarginPadding { Bottom = progress_height }, Height = bottom_black_area_height, RelativeSizeAxes = Axes.X, Origin = Anchor.BottomCentre, Anchor = Anchor.BottomCentre, Children = new Drawable[] { new FillFlowContainer<IconButton> { AutoSizeAxes = Axes.Both, Direction = FillDirection.Horizontal, Spacing = new Vector2(5), Origin = Anchor.Centre, Anchor = Anchor.Centre, Children = new[] { prevButton = new MusicIconButton { Anchor = Anchor.Centre, Origin = Anchor.Centre, Action = () => musicController.PreviousTrack(), Icon = FontAwesome.Solid.StepBackward, }, playButton = new MusicIconButton { Anchor = Anchor.Centre, Origin = Anchor.Centre, Scale = new Vector2(1.4f), IconScale = new Vector2(1.4f), Action = () => musicController.TogglePause(), Icon = FontAwesome.Regular.PlayCircle, }, nextButton = new MusicIconButton { Anchor = Anchor.Centre, Origin = Anchor.Centre, Action = () => musicController.NextTrack(), Icon = FontAwesome.Solid.StepForward, }, } }, playlistButton = new MusicIconButton { Origin = Anchor.Centre, Anchor = Anchor.CentreRight, Position = new Vector2(-bottom_black_area_height / 2, 0), Icon = FontAwesome.Solid.Bars, Action = togglePlaylist }, } }, progressBar = new HoverableProgressBar { Origin = Anchor.BottomCentre, Anchor = Anchor.BottomCentre, Height = progress_height / 2, FillColour = colours.Yellow, BackgroundColour = colours.YellowDarker.Opacity(0.5f), OnSeek = musicController.SeekTo } }, }, } } }; } private void togglePlaylist() { if (playlist == null) { LoadComponentAsync(playlist = new PlaylistOverlay { RelativeSizeAxes = Axes.X, Y = player_height + 10, }, _ => { dragContainer.Add(playlist); playlist.BeatmapSets.BindTo(musicController.BeatmapSets); playlist.State.BindValueChanged(s => playlistButton.FadeColour(s.NewValue == Visibility.Visible ? colours.Yellow : Color4.White, 200, Easing.OutQuint), true); togglePlaylist(); }); return; } if (!beatmap.Disabled) playlist.ToggleVisibility(); } protected override void LoadComplete() { base.LoadComplete(); beatmap.BindDisabledChanged(beatmapDisabledChanged, true); musicController.TrackChanged += trackChanged; trackChanged(beatmap.Value); } protected override void PopIn() { base.PopIn(); this.FadeIn(transition_length, Easing.OutQuint); dragContainer.ScaleTo(1, transition_length, Easing.OutElastic); } protected override void PopOut() { base.PopOut(); this.FadeOut(transition_length, Easing.OutQuint); dragContainer.ScaleTo(0.9f, transition_length, Easing.OutQuint); } protected override void UpdateAfterChildren() { base.UpdateAfterChildren(); Height = dragContainer.Height; } protected override void Update() { base.Update(); if (pendingBeatmapSwitch != null) { pendingBeatmapSwitch(); pendingBeatmapSwitch = null; } var track = musicController.CurrentTrack; if (!track.IsDummyDevice) { progressBar.EndTime = track.Length; progressBar.CurrentTime = track.CurrentTime; playButton.Icon = track.IsRunning ? FontAwesome.Regular.PauseCircle : FontAwesome.Regular.PlayCircle; } else { progressBar.CurrentTime = 0; progressBar.EndTime = 1; playButton.Icon = FontAwesome.Regular.PlayCircle; } } private Action pendingBeatmapSwitch; private void trackChanged(WorkingBeatmap beatmap, TrackChangeDirection direction = TrackChangeDirection.None) { // avoid using scheduler as our scheduler may not be run for a long time, holding references to beatmaps. pendingBeatmapSwitch = delegate { // todo: this can likely be replaced with WorkingBeatmap.GetBeatmapAsync() Task.Run(() => { if (beatmap?.Beatmap == null) // this is not needed if a placeholder exists { title.Text = @"Nothing to play"; artist.Text = @"Nothing to play"; } else { BeatmapMetadata metadata = beatmap.Metadata; title.Text = new RomanisableString(metadata.TitleUnicode, metadata.Title); artist.Text = new RomanisableString(metadata.ArtistUnicode, metadata.Artist); } }); LoadComponentAsync(new Background(beatmap) { Depth = float.MaxValue }, newBackground => { switch (direction) { case TrackChangeDirection.Next: newBackground.Position = new Vector2(400, 0); newBackground.MoveToX(0, 500, Easing.OutCubic); background.MoveToX(-400, 500, Easing.OutCubic); break; case TrackChangeDirection.Prev: newBackground.Position = new Vector2(-400, 0); newBackground.MoveToX(0, 500, Easing.OutCubic); background.MoveToX(400, 500, Easing.OutCubic); break; } background.Expire(); background = newBackground; playerContainer.Add(newBackground); }); }; } private void beatmapDisabledChanged(bool disabled) { if (disabled) playlist?.Hide(); prevButton.Enabled.Value = !disabled; nextButton.Enabled.Value = !disabled; playlistButton.Enabled.Value = !disabled; } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); if (musicController != null) musicController.TrackChanged -= trackChanged; } private class MusicIconButton : IconButton { public MusicIconButton() { AutoSizeAxes = Axes.Both; } [BackgroundDependencyLoader] private void load(OsuColour colours) { HoverColour = colours.YellowDark.Opacity(0.6f); FlashColour = colours.Yellow; } protected override void LoadComplete() { base.LoadComplete(); // works with AutoSizeAxes above to make buttons autosize with the scale animation. Content.AutoSizeAxes = Axes.None; Content.Size = new Vector2(DEFAULT_BUTTON_SIZE); } } private class Background : BufferedContainer { private readonly Sprite sprite; private readonly WorkingBeatmap beatmap; public Background(WorkingBeatmap beatmap = null) : base(cachedFrameBuffer: true) { this.beatmap = beatmap; Depth = float.MaxValue; RelativeSizeAxes = Axes.Both; Children = new Drawable[] { sprite = new Sprite { RelativeSizeAxes = Axes.Both, Colour = OsuColour.Gray(150), FillMode = FillMode.Fill, }, new Box { RelativeSizeAxes = Axes.X, Height = bottom_black_area_height, Origin = Anchor.BottomCentre, Anchor = Anchor.BottomCentre, Colour = Color4.Black.Opacity(0.5f) } }; } [BackgroundDependencyLoader] private void load(TextureStore textures) { sprite.Texture = beatmap?.Background ?? textures.Get(@"Backgrounds/bg4"); } } private class DragContainer : Container { protected override bool OnDragStart(DragStartEvent e) { return true; } protected override void OnDrag(DragEvent e) { Vector2 change = e.MousePosition - e.MouseDownPosition; // Diminish the drag distance as we go further to simulate "rubber band" feeling. change *= change.Length <= 0 ? 0 : MathF.Pow(change.Length, 0.7f) / change.Length; this.MoveTo(change); } protected override void OnDragEnd(DragEndEvent e) { this.MoveTo(Vector2.Zero, 800, Easing.OutElastic); base.OnDragEnd(e); } } private class HoverableProgressBar : ProgressBar { public HoverableProgressBar() : base(true) { } protected override bool OnHover(HoverEvent e) { this.ResizeHeightTo(progress_height, 500, Easing.OutQuint); return base.OnHover(e); } protected override void OnHoverLost(HoverLostEvent e) { this.ResizeHeightTo(progress_height / 2, 500, Easing.OutQuint); base.OnHoverLost(e); } } } }
// // ComboBoxEntryBackend.cs // // Author: // Lluis Sanchez <[email protected]> // // Copyright (c) 2012 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 AppKit; using Foundation; using Xwt.Backends; namespace Xwt.Mac { public class ComboBoxEntryBackend: ViewBackend<NSComboBox,IComboBoxEventSink>, IComboBoxEntryBackend { ComboDataSource tsource; TextEntryBackend entryBackend; int textColumn; public ComboBoxEntryBackend () { } public override void Initialize () { base.Initialize (); ViewObject = new MacComboBox (EventSink, ApplicationContext); #if !MONOMAC this.Widget.WillPopUp += (object sender, EventArgs e) => { this.IsDropDownOpen = true; }; this.Widget.WillDismiss += (object sender, EventArgs e) => { this.IsDropDownOpen = false; }; #endif } protected override Size GetNaturalSize () { var s = base.GetNaturalSize (); return new Size (EventSink.GetDefaultNaturalSize ().Width, s.Height); } #region IComboBoxEntryBackend implementation public ITextEntryBackend TextEntryBackend { get { if (entryBackend == null) entryBackend = new Xwt.Mac.TextEntryBackend ((MacComboBox)ViewObject); return entryBackend; } } #endregion #region IComboBoxBackend implementation public bool IsDropDownOpen { get; private set; } public void SetViews (CellViewCollection views) { } public void SetSource (IListDataSource source, IBackend sourceBackend) { tsource = new ComboDataSource (source); tsource.TextColumn = textColumn; Widget.UsesDataSource = true; Widget.DataSource = tsource; } public int SelectedRow { get { return (int) Widget.SelectedIndex; } set { Widget.SelectItem (value); } } public void SetTextColumn (int column) { textColumn = column; if (tsource != null) tsource.TextColumn = column; } #endregion } class MacComboBox : NSComboBox, IViewObject, INSComboBoxDelegate { IComboBoxEventSink eventSink; ITextEntryEventSink entryEventSink; ApplicationContext context; int cacheSelectionStart, cacheSelectionLength; bool checkMouseMovement; public MacComboBox (IComboBoxEventSink eventSink, ApplicationContext context) { this.context = context; this.eventSink = eventSink; Delegate = this; } public void SetEntryEventSink (ITextEntryEventSink entryEventSink) { this.entryEventSink = entryEventSink; } public NSView View { get { return this; } } public ViewBackend Backend { get; set; } [Export ("comboBoxSelectionDidChange:")] public new void SelectionChanged (NSNotification notification) { if (entryEventSink != null) { context.InvokeUserCode (delegate { entryEventSink.OnChanged (); eventSink.OnSelectionChanged (); }); } } public override void DidChange (NSNotification notification) { base.DidChange (notification); if (entryEventSink != null) { context.InvokeUserCode (delegate { entryEventSink.OnChanged (); entryEventSink.OnSelectionChanged (); }); } } public override void KeyUp (NSEvent theEvent) { base.KeyUp (theEvent); HandleSelectionChanged (); } NSTrackingArea trackingArea; public override void UpdateTrackingAreas () { base.UpdateTrackingAreas(); if(trackingArea != null) { RemoveTrackingArea (trackingArea); trackingArea.Dispose (); } var viewBounds = this.Bounds; var options = NSTrackingAreaOptions.MouseMoved | NSTrackingAreaOptions.ActiveInKeyWindow | NSTrackingAreaOptions.MouseEnteredAndExited; trackingArea = new NSTrackingArea (viewBounds, options, this, null); AddTrackingArea (trackingArea); } public override void RightMouseDown (NSEvent theEvent) { base.RightMouseDown (theEvent); var p = ConvertPointFromView (theEvent.LocationInWindow, null); ButtonEventArgs args = new ButtonEventArgs (); args.X = p.X; args.Y = p.Y; args.Button = PointerButton.Right; args.IsContextMenuTrigger = theEvent.TriggersContextMenu (); context.InvokeUserCode (delegate { eventSink.OnButtonPressed (args); }); } public override void RightMouseUp (NSEvent theEvent) { base.RightMouseUp (theEvent); var p = ConvertPointFromView (theEvent.LocationInWindow, null); ButtonEventArgs args = new ButtonEventArgs (); args.X = p.X; args.Y = p.Y; args.Button = PointerButton.Right; context.InvokeUserCode (delegate { eventSink.OnButtonReleased (args); }); } public override void MouseDown (NSEvent theEvent) { base.MouseDown (theEvent); var p = ConvertPointFromView (theEvent.LocationInWindow, null); ButtonEventArgs args = new ButtonEventArgs (); args.X = p.X; args.Y = p.Y; args.Button = PointerButton.Left; args.IsContextMenuTrigger = theEvent.TriggersContextMenu (); context.InvokeUserCode (delegate { eventSink.OnButtonPressed (args); }); } public override void MouseUp (NSEvent theEvent) { base.MouseUp (theEvent); var p = ConvertPointFromView (theEvent.LocationInWindow, null); ButtonEventArgs args = new ButtonEventArgs (); args.X = p.X; args.Y = p.Y; args.Button = (PointerButton) (int)theEvent.ButtonNumber + 1; context.InvokeUserCode (delegate { eventSink.OnButtonReleased (args); }); } public override void MouseEntered (NSEvent theEvent) { base.MouseEntered (theEvent); checkMouseMovement = true; context.InvokeUserCode (eventSink.OnMouseEntered); } public override void MouseExited (NSEvent theEvent) { base.MouseExited (theEvent); context.InvokeUserCode (eventSink.OnMouseExited); checkMouseMovement = false; HandleSelectionChanged (); } public override void MouseMoved (NSEvent theEvent) { base.MouseMoved (theEvent); if (!checkMouseMovement) return; var p = ConvertPointFromView (theEvent.LocationInWindow, null); MouseMovedEventArgs args = new MouseMovedEventArgs ((long) TimeSpan.FromSeconds (theEvent.Timestamp).TotalMilliseconds, p.X, p.Y); context.InvokeUserCode (delegate { eventSink.OnMouseMoved (args); }); if (checkMouseMovement) HandleSelectionChanged (); } void HandleSelectionChanged () { if (entryEventSink == null || CurrentEditor == null) return; if (cacheSelectionStart != CurrentEditor.SelectedRange.Location || cacheSelectionLength != CurrentEditor.SelectedRange.Length) { cacheSelectionStart = (int)CurrentEditor.SelectedRange.Location; cacheSelectionLength = (int)CurrentEditor.SelectedRange.Length; context.InvokeUserCode (entryEventSink.OnSelectionChanged); } } } class ComboDataSource: NSComboBoxDataSource { NSComboBox comboBox; IListDataSource source; public int TextColumn; public ComboDataSource (IListDataSource source) { this.source = source; source.RowChanged += SourceChanged; source.RowDeleted += SourceChanged; source.RowInserted += SourceChanged; source.RowsReordered += SourceChanged; } void SourceChanged (object sender, ListRowEventArgs e) { // FIXME: we need to find a more efficient way comboBox?.ReloadData (); } public override NSObject ObjectValueForItem (NSComboBox comboBox, nint index) { SetComboBox (comboBox); return NSObject.FromObject (source.GetValue ((int) index, TextColumn)); } public override nint ItemCount (NSComboBox comboBox) { SetComboBox (comboBox); return source.RowCount; } void SetComboBox (NSComboBox comboBox) { if (this.comboBox == null) { this.comboBox = comboBox; source.RowChanged += SourceChanged; source.RowDeleted += SourceChanged; source.RowInserted += SourceChanged; source.RowsReordered += SourceChanged; } if (this.comboBox != comboBox) throw new InvalidOperationException ("This ComboDataSource is already bound to an other ComboBox"); } protected override void Dispose (bool disposing) { if (source != null) { source.RowChanged -= SourceChanged; source.RowDeleted -= SourceChanged; source.RowInserted -= SourceChanged; source.RowsReordered -= SourceChanged; source = null; } base.Dispose (disposing); } } }
// // CTTypesetter.cs: Implements the managed CTTypesetter // // Authors: Mono Team // // Copyright 2010 Novell, Inc // Copyright 2011, 2012 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 System.Drawing; using System.Runtime.InteropServices; using MonoMac.ObjCRuntime; using MonoMac.Foundation; using MonoMac.CoreFoundation; using MonoMac.CoreGraphics; namespace MonoMac.CoreText { #region Typesetter Values [Since (3,2)] public static class CTTypesetterOptionKey { [Obsolete ("Deprecated in iOS 6.0")] public static readonly NSString DisableBidiProcessing; public static readonly NSString ForceEmbeddingLevel; static CTTypesetterOptionKey () { var handle = Dlfcn.dlopen (Constants.CoreTextLibrary, 0); if (handle == IntPtr.Zero) return; try { DisableBidiProcessing = Dlfcn.GetStringConstant (handle, "kCTTypesetterOptionDisableBidiProcessing"); ForceEmbeddingLevel = Dlfcn.GetStringConstant (handle, "kCTTypesetterOptionForcedEmbeddingLevel"); } finally { Dlfcn.dlclose (handle); } } } [Since (3,2)] public class CTTypesetterOptions { public CTTypesetterOptions () : this (new NSMutableDictionary ()) { } public CTTypesetterOptions (NSDictionary dictionary) { if (dictionary == null) throw new ArgumentNullException ("dictionary"); Dictionary = dictionary; } public NSDictionary Dictionary {get; private set;} [Obsolete ("Deprecated in iOS 6.0")] public bool DisableBidiProcessing { get { return CFDictionary.GetBooleanValue (Dictionary.Handle, CTTypesetterOptionKey.DisableBidiProcessing.Handle); } set { Adapter.AssertWritable (Dictionary); CFMutableDictionary.SetValue (Dictionary.Handle, CTTypesetterOptionKey.DisableBidiProcessing.Handle, value); } } public int? ForceEmbeddingLevel { get {return Adapter.GetInt32Value (Dictionary, CTTypesetterOptionKey.ForceEmbeddingLevel);} set {Adapter.SetValue (Dictionary, CTTypesetterOptionKey.ForceEmbeddingLevel, value);} } } #endregion [Since (3,2)] public class CTTypesetter : INativeObject, IDisposable { internal IntPtr handle; internal CTTypesetter (IntPtr handle, bool owns) { if (handle == IntPtr.Zero) throw ConstructorError.ArgumentNull (this, "handle"); this.handle = handle; if (!owns) CFObject.CFRetain (handle); } public IntPtr Handle { get {return handle;} } ~CTTypesetter () { Dispose (false); } public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } protected virtual void Dispose (bool disposing) { if (handle != IntPtr.Zero){ CFObject.CFRelease (handle); handle = IntPtr.Zero; } } #region Typesetter Creation [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTTypesetterCreateWithAttributedString (IntPtr @string); public CTTypesetter (NSAttributedString value) { if (value == null) throw ConstructorError.ArgumentNull (this, "value"); handle = CTTypesetterCreateWithAttributedString (value.Handle); if (handle == IntPtr.Zero) throw ConstructorError.Unknown (this); } [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTTypesetterCreateWithAttributedStringAndOptions (IntPtr @string, IntPtr options); public CTTypesetter (NSAttributedString value, CTTypesetterOptions options) { if (value == null) throw ConstructorError.ArgumentNull (this, "value"); handle = CTTypesetterCreateWithAttributedStringAndOptions (value.Handle, options == null ? IntPtr.Zero : options.Dictionary.Handle); if (handle == IntPtr.Zero) throw ConstructorError.Unknown (this); } #endregion #region Typeset Line Creation [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTTypesetterCreateLineWithOffset (IntPtr typesetter, NSRange stringRange, double offset); public CTLine GetLine (NSRange stringRange, double offset) { var h = CTTypesetterCreateLineWithOffset (handle, stringRange, offset); if (h == IntPtr.Zero) return null; return new CTLine (h, true); } [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTTypesetterCreateLine (IntPtr typesetter, NSRange stringRange); public CTLine GetLine (NSRange stringRange) { var h = CTTypesetterCreateLine (handle, stringRange); if (h == IntPtr.Zero) return null; return new CTLine (h, true); } #endregion #region Typeset Line Breaking [DllImport (Constants.CoreTextLibrary)] static extern int CTTypesetterSuggestLineBreakWithOffset (IntPtr typesetter, int startIndex, double width, double offset); public int SuggestLineBreak (int startIndex, double width, double offset) { return CTTypesetterSuggestLineBreakWithOffset (handle, startIndex, width, offset); } [DllImport (Constants.CoreTextLibrary)] static extern int CTTypesetterSuggestLineBreak (IntPtr typesetter, int startIndex, double width); public int SuggestLineBreak (int startIndex, double width) { return CTTypesetterSuggestLineBreak (handle, startIndex, width); } [DllImport (Constants.CoreTextLibrary)] static extern int CTTypesetterSuggestClusterBreakWithOffset (IntPtr typesetter, int startIndex, double width, double offset); public int SuggestClusterBreak (int startIndex, double width, double offset) { return CTTypesetterSuggestClusterBreakWithOffset (handle, startIndex, width, offset); } [DllImport (Constants.CoreTextLibrary)] static extern int CTTypesetterSuggestClusterBreak (IntPtr typesetter, int startIndex, double width); public int SuggestClusterBreak (int startIndex, double width) { return CTTypesetterSuggestClusterBreak (handle, startIndex, width); } #endregion } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- /*++ Abstract: The file contains SafeHandles implementations for SSPI. These handle wrappers do guarantee that OS resources get cleaned up when the app domain dies. All PInvoke declarations that do freeing the OS resources _must_ be in this file All PInvoke declarations that do allocation the OS resources _must_ be in this file Details: The protection from leaking OF the OS resources is based on two technologies 1) SafeHandle class 2) Non interuptible regions using Constrained Execution Region (CER) technology For simple cases SafeHandle class does all the job. The Prerequisites are: - A resource is able to be represented by IntPtr type (32 bits on 32 bits platforms). - There is a PInvoke availble that does the creation of the resource. That PInvoke either returns the handle value or it writes the handle into out/ref parameter. - The above PInvoke as part of the call does NOT free any OS resource. For those "simple" cases we desinged SafeHandle-derived classes that provide static methods to allocate a handle object. Each such derived class provides a handle release method that is run as non-interrupted. For more complicated cases we employ the support for non-interruptible methods (CERs). Each CER is a tree of code rooted at a catch or finally clause for a specially marked exception handler (preceded by the RuntimeHelpers.PrepareConstrainedRegions() marker) or the Dispose or ReleaseHandle method of a SafeHandle derived class. The graph is automatically computed by the runtime (typically at the jit time of the root method), but cannot follow virtual or interface calls (these must be explicitly prepared via RuntimeHelpers.PrepareMethod once the definite target method is known). Also, methods in the graph that must be included in the CER must be marked with a reliability contract stating guarantees about the consistency of the system if an error occurs while they are executing. Look for ReliabilityContract for examples (a full explanation of the semantics of this contract is beyond the scope of this comment). An example of the top-level of a CER: RuntimeHelpers.PrepareConstrainedRegions(); try { // Normal code } finally { // Guaranteed to get here even in low memory scenarios. Thread abort will not interrupt // this clause and we won't fail because of a jit allocation of any method called (modulo // restrictions on interface/virtual calls listed above and further restrictions listed // below). } Another common pattern is an empty-try (where you really just want a region of code the runtime won't interrupt you in): RuntimeHelpers.PrepareConstrainedRegions(); try {} finally { // Non-interruptible code here } This ugly syntax will be supplanted with compiler support at some point. While within a CER region certain restrictions apply in order to avoid having the runtime inject a potential fault point into your code (and of course you're are responsible for ensuring your code doesn't inject any explicit fault points of its own unless you know how to tolerate them). A quick and dirty guide to the possible causes of fault points in CER regions: - Explicit allocations (though allocating a value type only implies allocation on the stack, which may not present an issue). - Boxing a value type (C# does this implicitly for you in many cases, so be careful). - Use of Monitor.Enter or the lock keyword. - Accessing a multi-dimensional array. - Calling any method outside your control that doesn't make a guarantee (e.g. via a ReliabilityAttribute) that it doesn't introduce failure points. - Making P/Invoke calls with non-blittable parameters types. Blittable types are: - SafeHandle when used as an [in] parameter - NON BOXED base types that fit onto a machine word - ref struct with blittable fields - class type with blittable fields - pinned Unicode strings using "fixed" statement - pointers of any kind - IntPtr type - P/Invokes should not have any CharSet attribute on it's declaration. Obvioulsy string types should not appear in the parameters. - String type MUST not appear in a field of a marshaled ref struct or class in a P?Invoke (taken from the NCL classes) --*/ namespace System.IdentityModel { using System.Security; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Threading; using System.Security.Permissions; using System.ComponentModel; using System.Text; using System.ServiceModel.Diagnostics; using Microsoft.Win32.SafeHandles; using System.Runtime.ConstrainedExecution; [StructLayout(LayoutKind.Sequential, Pack = 1)] struct SSPIHandle { IntPtr HandleHi; IntPtr HandleLo; public bool IsZero { get { return HandleHi == IntPtr.Zero && HandleLo == IntPtr.Zero; } } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal void SetToInvalid() { HandleHi = IntPtr.Zero; HandleLo = IntPtr.Zero; } //public static string ToString(ref SSPIHandle obj) //{ // return obj.HandleHi.ToString("x") + ":" + obj.HandleLo.ToString("x"); //} } class SafeDeleteContext : SafeHandle { const string SECURITY = "security.Dll"; const string dummyStr = " "; static readonly byte[] dummyBytes = new byte[] { 0 }; internal SSPIHandle _handle; //should be always used as by ref in PINvokes parameters SafeFreeCredentials _EffectiveCredential; protected SafeDeleteContext() : base(IntPtr.Zero, true) { _handle = new SSPIHandle(); } public override bool IsInvalid { get { return IsClosed || _handle.IsZero; } } //This method should never be called for this type //public new IntPtr DangerousGetHandle() //{ // throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException()); //} //public static string ToString(SafeDeleteContext obj) //{ // { return obj == null ? "null" : SSPIHandle.ToString(ref obj._handle); } //} //------------------------------------------------------------------- internal static unsafe int InitializeSecurityContext( SafeFreeCredentials inCredentials, ref SafeDeleteContext refContext, string targetName, SspiContextFlags inFlags, Endianness endianness, SecurityBuffer inSecBuffer, SecurityBuffer[] inSecBuffers, SecurityBuffer outSecBuffer, ref SspiContextFlags outFlags) { if (inCredentials == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("inCredentials"); } SecurityBufferDescriptor inSecurityBufferDescriptor = null; if (inSecBuffer != null) { inSecurityBufferDescriptor = new SecurityBufferDescriptor(1); } else if (inSecBuffers != null) { inSecurityBufferDescriptor = new SecurityBufferDescriptor(inSecBuffers.Length); } SecurityBufferDescriptor outSecurityBufferDescriptor = new SecurityBufferDescriptor(1); // actually this is returned in outFlags bool isSspiAllocated = (inFlags & SspiContextFlags.AllocateMemory) != 0 ? true : false; int errorCode = -1; SSPIHandle contextHandle = new SSPIHandle(); if (refContext != null) { contextHandle = refContext._handle; } // these are pinned user byte arrays passed along with SecurityBuffers GCHandle[] pinnedInBytes = null; GCHandle pinnedOutBytes = new GCHandle(); // optional output buffer that may need to be freed SafeFreeContextBuffer outFreeContextBuffer = null; try { pinnedOutBytes = GCHandle.Alloc(outSecBuffer.token, GCHandleType.Pinned); SecurityBufferStruct[] inUnmanagedBuffer = new SecurityBufferStruct[inSecurityBufferDescriptor == null ? 1 : inSecurityBufferDescriptor.Count]; fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer) { if (inSecurityBufferDescriptor != null) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers inSecurityBufferDescriptor.UnmanagedPointer = inUnmanagedBufferPtr; pinnedInBytes = new GCHandle[inSecurityBufferDescriptor.Count]; SecurityBuffer securityBuffer; for (int index = 0; index < inSecurityBufferDescriptor.Count; ++index) { securityBuffer = inSecBuffer != null ? inSecBuffer : inSecBuffers[index]; if (securityBuffer != null) { // Copy the SecurityBuffer content into unmanaged place holder inUnmanagedBuffer[index].count = securityBuffer.size; inUnmanagedBuffer[index].type = securityBuffer.type; // use the unmanaged token if it's not null; otherwise use the managed buffer if (securityBuffer.unmanagedToken != null) { inUnmanagedBuffer[index].token = securityBuffer.unmanagedToken.DangerousGetHandle(); } else if (securityBuffer.token == null || securityBuffer.token.Length == 0) { inUnmanagedBuffer[index].token = IntPtr.Zero; } else { pinnedInBytes[index] = GCHandle.Alloc(securityBuffer.token, GCHandleType.Pinned); inUnmanagedBuffer[index].token = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset); } } } } SecurityBufferStruct[] outUnmanagedBuffer = new SecurityBufferStruct[1]; fixed (void* outUnmanagedBufferPtr = outUnmanagedBuffer) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers outSecurityBufferDescriptor.UnmanagedPointer = outUnmanagedBufferPtr; outUnmanagedBuffer[0].count = outSecBuffer.size; outUnmanagedBuffer[0].type = outSecBuffer.type; if (outSecBuffer.token == null || outSecBuffer.token.Length == 0) { outUnmanagedBuffer[0].token = IntPtr.Zero; } else { outUnmanagedBuffer[0].token = Marshal.UnsafeAddrOfPinnedArrayElement(outSecBuffer.token, outSecBuffer.offset); } if (isSspiAllocated) { outFreeContextBuffer = SafeFreeContextBuffer.CreateEmptyHandle(); } if (refContext == null || refContext.IsInvalid) { refContext = new SafeDeleteContext(); } if (targetName == null || targetName.Length == 0) { targetName = dummyStr; } fixed (char* namePtr = targetName) { errorCode = MustRunInitializeSecurityContext( inCredentials, contextHandle.IsZero ? null : &contextHandle, (byte*)(((object)targetName == (object)dummyStr) ? null : namePtr), inFlags, endianness, inSecurityBufferDescriptor, refContext, outSecurityBufferDescriptor, ref outFlags, outFreeContextBuffer ); } // Get unmanaged buffer with index 0 as the only one passed into PInvoke outSecBuffer.size = outUnmanagedBuffer[0].count; outSecBuffer.type = outUnmanagedBuffer[0].type; if (outSecBuffer.size > 0) { outSecBuffer.token = DiagnosticUtility.Utility.AllocateByteArray(outSecBuffer.size); Marshal.Copy(outUnmanagedBuffer[0].token, outSecBuffer.token, 0, outSecBuffer.size); } else { outSecBuffer.token = null; } } } } finally { if (pinnedInBytes != null) { for (int index = 0; index < pinnedInBytes.Length; index++) { if (pinnedInBytes[index].IsAllocated) { pinnedInBytes[index].Free(); } } } if (pinnedOutBytes.IsAllocated) { pinnedOutBytes.Free(); } if (outFreeContextBuffer != null) { outFreeContextBuffer.Close(); } } return errorCode; } // // After PINvoke call the method will fix the handleTemplate.handle with the returned value. // The caller is responsible for creating a correct SafeFreeContextBuffer or null can be passed if no handle is returned. // // Since it has a CER, this method can't have any references to imports from DLLs that may not exist on the system. // static unsafe int MustRunInitializeSecurityContext( SafeFreeCredentials inCredentials, void* inContextPtr, byte* targetName, SspiContextFlags inFlags, Endianness endianness, SecurityBufferDescriptor inputBuffer, SafeDeleteContext outContext, SecurityBufferDescriptor outputBuffer, ref SspiContextFlags attributes, SafeFreeContextBuffer handleTemplate) { int errorCode = -1; bool b1 = false; bool b2 = false; // Run the body of this method as a non-interruptible block. RuntimeHelpers.PrepareConstrainedRegions(); try { inCredentials.DangerousAddRef(ref b1); outContext.DangerousAddRef(ref b2); } catch (Exception e) { if (System.Runtime.Fx.IsFatal(e)) throw; if (b1) { inCredentials.DangerousRelease(); b1 = false; } if (b2) { outContext.DangerousRelease(); b2 = false; } if (!(e is ObjectDisposedException)) throw; } finally { long timeStamp; if (!b1) { // caller should retry inCredentials = null; } else if (b1 && b2) { SSPIHandle credentialHandle = inCredentials._handle; // PreSharp Bug: Call 'Marshal.GetLastWin32Error' or 'Marshal.GetHRForLastWin32Error' before any other interop call. #pragma warning suppress 56523 // This API does not set Win32 Last Error. errorCode = InitializeSecurityContextW( ref credentialHandle, inContextPtr, targetName, inFlags, 0, endianness, inputBuffer, 0, ref outContext._handle, outputBuffer, ref attributes, out timeStamp ); // // When a credential handle is first associated with the context we keep credential // ref count bumped up to ensure ordered finalization. // If the credential handle has been changed we de-ref the old one and associate the // context with the new cred handle but only if the call was successful. if (outContext._EffectiveCredential != inCredentials && (errorCode & 0x80000000) == 0) { // Disassociate the previous credential handle if (outContext._EffectiveCredential != null) outContext._EffectiveCredential.DangerousRelease(); outContext._EffectiveCredential = inCredentials; } else { inCredentials.DangerousRelease(); } outContext.DangerousRelease(); // The idea is that SSPI has allocated a block and filled up outUnmanagedBuffer+8 slot with the pointer. if (handleTemplate != null) { handleTemplate.Set(((SecurityBufferStruct*)outputBuffer.UnmanagedPointer)->token); //ATTN: on 64 BIT that is still +8 cause of 2* c++ unsigned long == 8 bytes if (handleTemplate.IsInvalid) { handleTemplate.SetHandleAsInvalid(); } } } if (inContextPtr == null && (errorCode & 0x80000000) != 0) { // an error on the first call, need to set the out handle to invalid value outContext._handle.SetToInvalid(); } } return errorCode; } //------------------------------------------------------------------- internal static unsafe int AcceptSecurityContext( SafeFreeCredentials inCredentials, ref SafeDeleteContext refContext, SspiContextFlags inFlags, Endianness endianness, SecurityBuffer inSecBuffer, SecurityBuffer[] inSecBuffers, SecurityBuffer outSecBuffer, ref SspiContextFlags outFlags) { if (inCredentials == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("inCredentials"); } SecurityBufferDescriptor inSecurityBufferDescriptor = null; if (inSecBuffer != null) { inSecurityBufferDescriptor = new SecurityBufferDescriptor(1); } else if (inSecBuffers != null) { inSecurityBufferDescriptor = new SecurityBufferDescriptor(inSecBuffers.Length); } SecurityBufferDescriptor outSecurityBufferDescriptor = new SecurityBufferDescriptor(1); // actually this is returned in outFlags bool isSspiAllocated = (inFlags & SspiContextFlags.AllocateMemory) != 0 ? true : false; int errorCode = -1; SSPIHandle contextHandle = new SSPIHandle(); if (refContext != null) { contextHandle = refContext._handle; } // these are pinned user byte arrays passed along with SecurityBuffers GCHandle[] pinnedInBytes = null; GCHandle pinnedOutBytes = new GCHandle(); // optional output buffer that may need to be freed SafeFreeContextBuffer outFreeContextBuffer = null; try { pinnedOutBytes = GCHandle.Alloc(outSecBuffer.token, GCHandleType.Pinned); SecurityBufferStruct[] inUnmanagedBuffer = new SecurityBufferStruct[inSecurityBufferDescriptor == null ? 1 : inSecurityBufferDescriptor.Count]; fixed (void* inUnmanagedBufferPtr = inUnmanagedBuffer) { if (inSecurityBufferDescriptor != null) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers inSecurityBufferDescriptor.UnmanagedPointer = inUnmanagedBufferPtr; pinnedInBytes = new GCHandle[inSecurityBufferDescriptor.Count]; SecurityBuffer securityBuffer; for (int index = 0; index < inSecurityBufferDescriptor.Count; ++index) { securityBuffer = inSecBuffer != null ? inSecBuffer : inSecBuffers[index]; if (securityBuffer != null) { // Copy the SecurityBuffer content into unmanaged place holder inUnmanagedBuffer[index].count = securityBuffer.size; inUnmanagedBuffer[index].type = securityBuffer.type; // use the unmanaged token if it's not null; otherwise use the managed buffer if (securityBuffer.unmanagedToken != null) { inUnmanagedBuffer[index].token = securityBuffer.unmanagedToken.DangerousGetHandle(); } else if (securityBuffer.token == null || securityBuffer.token.Length == 0) { inUnmanagedBuffer[index].token = IntPtr.Zero; } else { pinnedInBytes[index] = GCHandle.Alloc(securityBuffer.token, GCHandleType.Pinned); inUnmanagedBuffer[index].token = Marshal.UnsafeAddrOfPinnedArrayElement(securityBuffer.token, securityBuffer.offset); } } } } SecurityBufferStruct[] outUnmanagedBuffer = new SecurityBufferStruct[1]; fixed (void* outUnmanagedBufferPtr = outUnmanagedBuffer) { // Fix Descriptor pointer that points to unmanaged SecurityBuffers outSecurityBufferDescriptor.UnmanagedPointer = outUnmanagedBufferPtr; // Copy the SecurityBuffer content into unmanaged place holder outUnmanagedBuffer[0].count = outSecBuffer.size; outUnmanagedBuffer[0].type = outSecBuffer.type; if (outSecBuffer.token == null || outSecBuffer.token.Length == 0) { outUnmanagedBuffer[0].token = IntPtr.Zero; } else { outUnmanagedBuffer[0].token = Marshal.UnsafeAddrOfPinnedArrayElement(outSecBuffer.token, outSecBuffer.offset); } if (isSspiAllocated) { outFreeContextBuffer = SafeFreeContextBuffer.CreateEmptyHandle(); } if (refContext == null || refContext.IsInvalid) { refContext = new SafeDeleteContext(); } errorCode = MustRunAcceptSecurityContext( inCredentials, contextHandle.IsZero ? null : &contextHandle, inSecurityBufferDescriptor, inFlags, endianness, refContext, outSecurityBufferDescriptor, ref outFlags, outFreeContextBuffer ); // Get unmanaged buffer with index 0 as the only one passed into PInvoke outSecBuffer.size = outUnmanagedBuffer[0].count; outSecBuffer.type = outUnmanagedBuffer[0].type; if (outSecBuffer.size > 0) { outSecBuffer.token = DiagnosticUtility.Utility.AllocateByteArray(outSecBuffer.size); Marshal.Copy(outUnmanagedBuffer[0].token, outSecBuffer.token, 0, outSecBuffer.size); } else { outSecBuffer.token = null; } } } } finally { if (pinnedInBytes != null) { for (int index = 0; index < pinnedInBytes.Length; index++) { if (pinnedInBytes[index].IsAllocated) { pinnedInBytes[index].Free(); } } } if (pinnedOutBytes.IsAllocated) { pinnedOutBytes.Free(); } if (outFreeContextBuffer != null) { outFreeContextBuffer.Close(); } } return errorCode; } // After PINvoke call the method will fix the handleTemplate.handle with the returned value. // The caller is responsible for creating a correct SafeFreeContextBuffer_XXX flavour or null can be passed if no handle is returned. // This method is run as non-interruptible. static unsafe int MustRunAcceptSecurityContext( SafeFreeCredentials inCredentials, void* inContextPtr, SecurityBufferDescriptor inputBuffer, SspiContextFlags inFlags, Endianness endianness, SafeDeleteContext outContext, SecurityBufferDescriptor outputBuffer, ref SspiContextFlags outFlags, SafeFreeContextBuffer handleTemplate) { int errorCode = -1; bool b1 = false; bool b2 = false; // Run the body of this method as a non-interruptible block. RuntimeHelpers.PrepareConstrainedRegions(); try { inCredentials.DangerousAddRef(ref b1); outContext.DangerousAddRef(ref b2); } catch (Exception e) { if (System.Runtime.Fx.IsFatal(e)) throw; if (b1) { inCredentials.DangerousRelease(); b1 = false; } if (b2) { outContext.DangerousRelease(); b2 = false; } if (!(e is ObjectDisposedException)) throw; } finally { long timeStamp; if (!b1) { // caller should retry inCredentials = null; } else if (b1 && b2) { SSPIHandle credentialHandle = inCredentials._handle; // PreSharp Bug: Call 'Marshal.GetLastWin32Error' or 'Marshal.GetHRForLastWin32Error' before any other interop call. #pragma warning suppress 56523 // This API does not set Win32 Last Error. errorCode = AcceptSecurityContext( ref credentialHandle, inContextPtr, inputBuffer, inFlags, endianness, ref outContext._handle, outputBuffer, ref outFlags, out timeStamp ); // // When a credential handle is first associated with the context we keep credential // ref count bumped up to ensure ordered finalization. // If the credential handle has been changed we de-ref the old one and associate the // context with the new cred handle but only if the call was successful. if (outContext._EffectiveCredential != inCredentials && (errorCode & 0x80000000) == 0) { // Disassociate the previous credential handle if (outContext._EffectiveCredential != null) outContext._EffectiveCredential.DangerousRelease(); outContext._EffectiveCredential = inCredentials; } else { inCredentials.DangerousRelease(); } outContext.DangerousRelease(); // The idea is that SSPI has allocated a block and filled up outUnmanagedBuffer+8 slot with the pointer. if (handleTemplate != null) { handleTemplate.Set(((SecurityBufferStruct*)outputBuffer.UnmanagedPointer)->token); //ATTN: on 64 BIT that is still +8 cause of 2* c++ unsigned long == 8 bytes if (handleTemplate.IsInvalid) { handleTemplate.SetHandleAsInvalid(); } } if (inContextPtr == null && (errorCode & 0x80000000) != 0) { // an error on the first call, need to set the out handle to invalid value outContext._handle.SetToInvalid(); } } } return errorCode; } public static int ImpersonateSecurityContext(SafeDeleteContext context) { int status = (int)SecurityStatus.InvalidHandle; bool b = false; RuntimeHelpers.PrepareConstrainedRegions(); try { context.DangerousAddRef(ref b); } catch (Exception e) { if (System.Runtime.Fx.IsFatal(e)) throw; if (b) { context.DangerousRelease(); b = false; } if (!(e is ObjectDisposedException)) throw; } finally { if (b) { // PreSharp Bug: Call 'Marshal.GetLastWin32Error' or 'Marshal.GetHRForLastWin32Error' before any other interop call. #pragma warning suppress 56523 // The API does not set Win32 Last Error. It returns a error code. status = ImpersonateSecurityContext(ref context._handle); context.DangerousRelease(); } } return status; } public static int EncryptMessage(SafeDeleteContext context, SecurityBufferDescriptor inputOutput, uint sequenceNumber) { int status = (int)SecurityStatus.InvalidHandle; bool b = false; RuntimeHelpers.PrepareConstrainedRegions(); try { context.DangerousAddRef(ref b); } catch (Exception e) { if (System.Runtime.Fx.IsFatal(e)) throw; if (b) { context.DangerousRelease(); b = false; } if (!(e is ObjectDisposedException)) throw; } finally { if (b) { // PreSharp Bug: Call 'Marshal.GetLastWin32Error' or 'Marshal.GetHRForLastWin32Error' before any other interop call. #pragma warning suppress 56523 // The API does not set Win32 Last Error. It returns a error code. status = EncryptMessage(ref context._handle, 0, inputOutput, sequenceNumber); context.DangerousRelease(); } } return status; } public unsafe static int DecryptMessage(SafeDeleteContext context, SecurityBufferDescriptor inputOutput, uint sequenceNumber) { int status = (int)SecurityStatus.InvalidHandle; bool b = false; uint qop = 0; RuntimeHelpers.PrepareConstrainedRegions(); try { context.DangerousAddRef(ref b); } catch (Exception e) { if (System.Runtime.Fx.IsFatal(e)) throw; if (b) { context.DangerousRelease(); b = false; } if (!(e is ObjectDisposedException)) throw; } finally { if (b) { #pragma warning suppress 56523 // we don't take any action on the win32 error message. status = DecryptMessage(ref context._handle, inputOutput, sequenceNumber, &qop); context.DangerousRelease(); } } const uint SECQOP_WRAP_NO_ENCRYPT = 0x80000001; if (status == 0 && qop == SECQOP_WRAP_NO_ENCRYPT) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SspiPayloadNotEncrypted))); } return status; } internal int GetSecurityContextToken(out SafeCloseHandle safeHandle) { int status = (int)SecurityStatus.InvalidHandle; bool b = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref b); } catch (Exception e) { if (System.Runtime.Fx.IsFatal(e)) throw; if (b) { DangerousRelease(); b = false; } if (!(e is ObjectDisposedException)) throw; } finally { if (b) { // PreSharp Bug: Call 'Marshal.GetLastWin32Error' or 'Marshal.GetHRForLastWin32Error' before any other interop call. #pragma warning suppress 56523 // The API does not set Win32 Last Error. The API returns a error code. status = QuerySecurityContextToken(ref _handle, out safeHandle); DangerousRelease(); } else { safeHandle = new SafeCloseHandle(IntPtr.Zero, false); } } return status; } protected override bool ReleaseHandle() { if (this._EffectiveCredential != null) this._EffectiveCredential.DangerousRelease(); // PreSharp Bug: Call 'Marshal.GetLastWin32Error' or 'Marshal.GetHRForLastWin32Error' before any other interop call. #pragma warning suppress 56523 // The API does not set Win32 Last Error. It returns a error code. return DeleteSecurityContext(ref _handle) == 0; } [DllImport(SECURITY, ExactSpelling = true, SetLastError = true)] [ResourceExposure(ResourceScope.None)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] extern static int QuerySecurityContextToken(ref SSPIHandle phContext, [Out] out SafeCloseHandle handle); [DllImport(SECURITY, ExactSpelling = true, SetLastError = true)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] [ResourceExposure(ResourceScope.None)] internal extern static unsafe int InitializeSecurityContextW( ref SSPIHandle credentialHandle, [In] void* inContextPtr, [In] byte* targetName, [In] SspiContextFlags inFlags, [In] int reservedI, [In] Endianness endianness, [In] SecurityBufferDescriptor inputBuffer, [In] int reservedII, ref SSPIHandle outContextPtr, [In, Out] SecurityBufferDescriptor outputBuffer, [In, Out] ref SspiContextFlags attributes, out long timestamp ); [DllImport(SECURITY, ExactSpelling = true, SetLastError = true)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] [ResourceExposure(ResourceScope.None)] internal extern static unsafe int AcceptSecurityContext( ref SSPIHandle credentialHandle, [In] void* inContextPtr, [In] SecurityBufferDescriptor inputBuffer, [In] SspiContextFlags inFlags, [In] Endianness endianness, ref SSPIHandle outContextPtr, [In, Out] SecurityBufferDescriptor outputBuffer, [In, Out] ref SspiContextFlags attributes, out long timestamp ); [DllImport(SECURITY, ExactSpelling = true, SetLastError = true)] [SuppressUnmanagedCodeSecurity] [ResourceExposure(ResourceScope.None)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal extern static int DeleteSecurityContext( ref SSPIHandle handlePtr ); [DllImport(SECURITY, ExactSpelling = true, SetLastError = true)] [ResourceExposure(ResourceScope.None)] internal extern static int ImpersonateSecurityContext( ref SSPIHandle handlePtr ); [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] [DllImport(SECURITY, ExactSpelling = true, SetLastError = true)] [ResourceExposure(ResourceScope.None)] internal extern static int EncryptMessage( ref SSPIHandle contextHandle, [In] uint qualityOfProtection, [In, Out] SecurityBufferDescriptor inputOutput, [In] uint sequenceNumber ); [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] [DllImport(SECURITY, ExactSpelling = true, SetLastError = true)] [ResourceExposure(ResourceScope.None)] internal unsafe extern static int DecryptMessage( ref SSPIHandle contextHandle, [In, Out] SecurityBufferDescriptor inputOutput, [In] uint sequenceNumber, uint* qualityOfProtection ); } class SafeFreeCredentials : SafeHandle { const string SECURITY = "security.Dll"; internal SSPIHandle _handle; //should be always used as by ref in PINvokes parameters protected SafeFreeCredentials() : base(IntPtr.Zero, true) { _handle = new SSPIHandle(); } //internal static string ToString(SafeFreeCredentials obj) //{ return obj == null ? "null" : SSPIHandle.ToString(ref obj._handle); } public override bool IsInvalid { get { return IsClosed || _handle.IsZero; } } //This method should never be called for this type //public new IntPtr DangerousGetHandle() //{ // throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException()); //} public static unsafe int AcquireCredentialsHandle( string package, CredentialUse intent, ref AuthIdentityEx authdata, out SafeFreeCredentials outCredential) { int errorCode = -1; long timeStamp; outCredential = new SafeFreeCredentials(); RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { // PreSharp Bug: Call 'Marshal.GetLastWin32Error' or 'Marshal.GetHRForLastWin32Error' before any other interop call. #pragma warning suppress 56523 // The API does not set Win32 Last Error. It returns a error code. errorCode = AcquireCredentialsHandleW( null, package, (int)intent, null, ref authdata, null, null, ref outCredential._handle, out timeStamp ); if (errorCode != 0) { outCredential.SetHandleAsInvalid(); } } return errorCode; } public static unsafe int AcquireDefaultCredential( string package, CredentialUse intent, ref AuthIdentityEx authIdentity, out SafeFreeCredentials outCredential) { int errorCode = -1; long timeStamp; outCredential = new SafeFreeCredentials(); RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { // PreSharp Bug: Call 'Marshal.GetLastWin32Error' or 'Marshal.GetHRForLastWin32Error' before any other interop call. #pragma warning suppress 56523 // The API does not set Win32 Last Error. It returns a error code. errorCode = AcquireCredentialsHandleW( null, package, (int)intent, null, ref authIdentity, // IntPtr.Zero, null, null, ref outCredential._handle, out timeStamp ); if (errorCode != 0) { outCredential.SetHandleAsInvalid(); } } return errorCode; } public static unsafe int AcquireCredentialsHandle( string package, CredentialUse intent, ref SecureCredential authdata, out SafeFreeCredentials outCredential) { int errorCode = -1; long timeStamp; // If there is a certificate, wrap it into an array IntPtr copiedPtr = authdata.certContextArray; try { IntPtr certArrayPtr = new IntPtr(&copiedPtr); if (copiedPtr != IntPtr.Zero) { authdata.certContextArray = certArrayPtr; } outCredential = new SafeFreeCredentials(); RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { // PreSharp Bug: Call 'Marshal.GetLastWin32Error' or 'Marshal.GetHRForLastWin32Error' before any other interop call. #pragma warning suppress 56523 // The API does not set Win32 Last Error. It returns a error code. errorCode = AcquireCredentialsHandleW( null, package, (int)intent, null, ref authdata, null, null, ref outCredential._handle, out timeStamp ); if (errorCode != 0) { outCredential.SetHandleAsInvalid(); } } } finally { authdata.certContextArray = copiedPtr; } return errorCode; } public static unsafe int AcquireCredentialsHandle( string package, CredentialUse intent, ref IntPtr ppAuthIdentity, out SafeFreeCredentials outCredential ) { int errorCode = -1; long timeStamp; outCredential = new SafeFreeCredentials(); RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { // PreSharp Bug: Call 'Marshal.GetLastWin32Error' or 'Marshal.GetHRForLastWin32Error' before any other interop call. #pragma warning suppress 56523 // The API does not set Win32 Last Error. It returns a error code. errorCode = AcquireCredentialsHandleW( null, package, (int)intent, null, ppAuthIdentity, null, null, ref outCredential._handle, out timeStamp ); if (errorCode != 0) { outCredential.SetHandleAsInvalid(); } } return errorCode; } protected override bool ReleaseHandle() { // PreSharp Bug: Call 'Marshal.GetLastWin32Error' or 'Marshal.GetHRForLastWin32Error' before any other interop call. #pragma warning suppress 56523 // The API does not set Win32 Last Error. It returns a error code. return FreeCredentialsHandle(ref _handle) == 0; } [ResourceExposure(ResourceScope.None)] [DllImport(SECURITY, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)] internal extern static unsafe int AcquireCredentialsHandleW( [In] string principal, [In] string moduleName, [In] int usage, [In] void* logonID, [In] ref AuthIdentityEx authdata, [In] void* keyCallback, [In] void* keyArgument, ref SSPIHandle handlePtr, [Out] out long timeStamp ); [ResourceExposure(ResourceScope.None)] [DllImport(SECURITY, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)] internal extern static unsafe int AcquireCredentialsHandleW( [In] string principal, [In] string moduleName, [In] int usage, [In] void* logonID, [In] IntPtr zero, [In] void* keyCallback, [In] void* keyArgument, ref SSPIHandle handlePtr, [Out] out long timeStamp ); [ResourceExposure(ResourceScope.None)] [DllImport(SECURITY, ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)] internal extern static unsafe int AcquireCredentialsHandleW( [In] string principal, [In] string moduleName, [In] int usage, [In] void* logonID, [In] ref SecureCredential authData, [In] void* keyCallback, [In] void* keyArgument, ref SSPIHandle handlePtr, [Out] out long timeStamp ); [DllImport(SECURITY, ExactSpelling = true, SetLastError = true)] [SuppressUnmanagedCodeSecurity] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [ResourceExposure(ResourceScope.None)] internal extern static int FreeCredentialsHandle( ref SSPIHandle handlePtr ); } sealed class SafeFreeCertContext : SafeHandleZeroOrMinusOneIsInvalid { const string CRYPT32 = "crypt32.dll"; const string ADVAPI32 = "advapi32.dll"; internal SafeFreeCertContext() : base(true) { } // This must be ONLY called from this file and form a MustRun method [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal unsafe void Set(IntPtr value) { this.handle = value; } const uint CRYPT_ACQUIRE_SILENT_FLAG = 0x00000040; [DllImport(CRYPT32, ExactSpelling = true, SetLastError = true)] [SuppressUnmanagedCodeSecurity] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [ResourceExposure(ResourceScope.None)] extern static bool CertFreeCertificateContext(// Suppressing returned status check, it's always==TRUE, [In] IntPtr certContext); protected override bool ReleaseHandle() { // PreSharp Bug: Call 'Marshal.GetLastWin32Error' or 'Marshal.GetHRForLastWin32Error' before any other interop call. #pragma warning suppress 56523 // The API does not set Win32 Last Error. return CertFreeCertificateContext(handle); } } sealed class SafeFreeContextBuffer : SafeHandleZeroOrMinusOneIsInvalid { const string SECURITY = "security.dll"; SafeFreeContextBuffer() : base(true) { } // This must be ONLY called from this file and form a MustRun method [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal unsafe void Set(IntPtr value) { this.handle = value; } internal static int EnumeratePackages(out int pkgnum, out SafeFreeContextBuffer pkgArray) { int res = -1; // PreSharp Bug: Call 'Marshal.GetLastWin32Error' or 'Marshal.GetHRForLastWin32Error' before any other interop call. #pragma warning suppress 56523 // The API does not set Win32 Last Error. The API returns a error code. res = SafeFreeContextBuffer.EnumerateSecurityPackagesW(out pkgnum, out pkgArray); if (res != 0) { Utility.CloseInvalidOutSafeHandle(pkgArray); pkgArray = null; } return res; } internal static SafeFreeContextBuffer CreateEmptyHandle() { return new SafeFreeContextBuffer(); } // // After PInvoke call the method will fix the refHandle.handle with the returned value. // The caller is responsible for creating a correct SafeHandle template or null can be passed if no handle is returned. // // This method is run as non-interruptible. // public static unsafe int QueryContextAttributes(SafeDeleteContext phContext, ContextAttribute contextAttribute, byte* buffer, SafeHandle refHandle) { int status = (int)SecurityStatus.InvalidHandle; bool b = false; // We don't want to be interrupted by thread abort exceptions or unexpected out-of-memory errors failing to jit // one of the following methods. So run within a CER non-interruptible block. RuntimeHelpers.PrepareConstrainedRegions(); try { phContext.DangerousAddRef(ref b); } catch (Exception e) { if (System.Runtime.Fx.IsFatal(e)) throw; if (b) { phContext.DangerousRelease(); b = false; } if (!(e is ObjectDisposedException)) throw; } finally { if (b) { // PreSharp Bug: Call 'Marshal.GetLastWin32Error' or 'Marshal.GetHRForLastWin32Error' before any other interop call. #pragma warning suppress 56523 // The API does not set Win32 Last Error. The API returns a error code. status = SafeFreeContextBuffer.QueryContextAttributesW(ref phContext._handle, contextAttribute, buffer); phContext.DangerousRelease(); } if (status == 0 && refHandle != null) { if (refHandle is SafeFreeContextBuffer) { if (contextAttribute == ContextAttribute.SessionKey) { IntPtr keyPtr = Marshal.ReadIntPtr(new IntPtr(buffer), SecPkgContext_SessionKey.SessionkeyOffset); ((SafeFreeContextBuffer)refHandle).Set(keyPtr); } else { ((SafeFreeContextBuffer)refHandle).Set(*(IntPtr*)buffer); } } else { ((SafeFreeCertContext)refHandle).Set(*(IntPtr*)buffer); } } if (status != 0 && refHandle != null) { refHandle.SetHandleAsInvalid(); } } return status; } protected override bool ReleaseHandle() { // PreSharp Bug: Call 'Marshal.GetLastWin32Error' or 'Marshal.GetHRForLastWin32Error' before any other interop call. #pragma warning suppress 56523 // The API does not set Win32 Last Error. The API returns a error code. return FreeContextBuffer(handle) == 0; } [DllImport(SECURITY, ExactSpelling = true, SetLastError = true)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] [ResourceExposure(ResourceScope.None)] internal extern static unsafe int QueryContextAttributesW( ref SSPIHandle contextHandle, [In] ContextAttribute attribute, [In] void* buffer); [DllImport(SECURITY, ExactSpelling = true, SetLastError = true)] [ResourceExposure(ResourceScope.None)] internal extern static int EnumerateSecurityPackagesW( [Out] out int pkgnum, [Out] out SafeFreeContextBuffer handle); [DllImport(SECURITY, ExactSpelling = true, SetLastError = true)] [SuppressUnmanagedCodeSecurity] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [ResourceExposure(ResourceScope.None)] extern static int FreeContextBuffer( [In] IntPtr contextBuffer); } sealed class SafeCloseHandle : SafeHandleZeroOrMinusOneIsInvalid { const string KERNEL32 = "kernel32.dll"; SafeCloseHandle() : base(true) { } internal SafeCloseHandle(IntPtr handle, bool ownsHandle) : base(ownsHandle) { DiagnosticUtility.DebugAssert(handle == IntPtr.Zero || !ownsHandle, "Unsafe to create a SafeHandle that owns a pre-existing handle before the SafeHandle was created."); SetHandle(handle); } protected override bool ReleaseHandle() { // PreSharp Bug: Call 'Marshal.GetLastWin32Error' or 'Marshal.GetHRForLastWin32Error' before any other interop call. #pragma warning suppress 56523 // We are not interested to throw an exception here. We can ignore the Last Error code. return CloseHandle(handle); } [DllImport(KERNEL32, ExactSpelling = true, SetLastError = true)] [SuppressUnmanagedCodeSecurity] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [ResourceExposure(ResourceScope.None)] extern static bool CloseHandle(IntPtr handle); } #pragma warning disable 618 // have not moved to the v4 security model yet [SecurityCritical(SecurityCriticalScope.Everything)] #pragma warning restore 618 sealed class SafeHGlobalHandle : SafeHandleZeroOrMinusOneIsInvalid { SafeHGlobalHandle() : base(true) { } // 0 is an Invalid Handle SafeHGlobalHandle(IntPtr handle) : base(true) { DiagnosticUtility.DebugAssert(handle == IntPtr.Zero, "SafeHGlobalHandle constructor can only be called with IntPtr.Zero."); SetHandle(handle); } protected override bool ReleaseHandle() { Marshal.FreeHGlobal(handle); return true; } public static SafeHGlobalHandle InvalidHandle { get { return new SafeHGlobalHandle(IntPtr.Zero); } } public static SafeHGlobalHandle AllocHGlobal(string s) { byte[] bytes = DiagnosticUtility.Utility.AllocateByteArray(checked((s.Length + 1) * 2)); Encoding.Unicode.GetBytes(s, 0, s.Length, bytes, 0); return AllocHGlobal(bytes); } public static SafeHGlobalHandle AllocHGlobal(byte[] bytes) { SafeHGlobalHandle result = AllocHGlobal(bytes.Length); Marshal.Copy(bytes, 0, result.DangerousGetHandle(), bytes.Length); return result; } public static SafeHGlobalHandle AllocHGlobal(uint cb) { // The cast could overflow to minus. // Unfortunately, Marshal.AllocHGlobal only takes int. return AllocHGlobal((int)cb); } public static SafeHGlobalHandle AllocHGlobal(int cb) { if (cb < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("cb", SR.GetString(SR.ValueMustBeNonNegative))); } SafeHGlobalHandle result = new SafeHGlobalHandle(); // CER RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { IntPtr ptr = Marshal.AllocHGlobal(cb); result.SetHandle(ptr); } return result; } } sealed class SafeLsaLogonProcessHandle : SafeHandleZeroOrMinusOneIsInvalid { SafeLsaLogonProcessHandle() : base(true) { } // 0 is an Invalid Handle internal SafeLsaLogonProcessHandle(IntPtr handle) : base(true) { SetHandle(handle); } internal static SafeLsaLogonProcessHandle InvalidHandle { get { return new SafeLsaLogonProcessHandle(IntPtr.Zero); } } override protected bool ReleaseHandle() { // LsaDeregisterLogonProcess returns an NTSTATUS return NativeMethods.LsaDeregisterLogonProcess(handle) >= 0; } } sealed class SafeLsaReturnBufferHandle : SafeHandleZeroOrMinusOneIsInvalid { SafeLsaReturnBufferHandle() : base(true) { } // 0 is an Invalid Handle internal SafeLsaReturnBufferHandle(IntPtr handle) : base(true) { SetHandle(handle); } internal static SafeLsaReturnBufferHandle InvalidHandle { get { return new SafeLsaReturnBufferHandle(IntPtr.Zero); } } override protected bool ReleaseHandle() { // LsaFreeReturnBuffer returns an NTSTATUS return NativeMethods.LsaFreeReturnBuffer(handle) >= 0; } } }
/* * Copyright (c) Citrix Systems, Inc. * 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. * * 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.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Net.Security; using System.Security.Cryptography.X509Certificates; namespace XenAPI { public partial class HTTP { public class TooManyRedirectsException : Exception { private readonly int redirect; private readonly Uri uri; public TooManyRedirectsException(int redirect, Uri uri) { this.redirect = redirect; this.uri = uri; } } public class BadServerResponseException : Exception { public BadServerResponseException(string msg) : base(msg) { } } public class CancelledException : Exception { } public delegate bool FuncBool(); public delegate void UpdateProgressDelegate(int percent); public delegate void DataCopiedDelegate(long bytes); // Size of byte buffer used for GETs and PUTs // (not the socket rx buffer) public const int BUFFER_SIZE = 32 * 1024; public const int MAX_REDIRECTS = 10; public const int DEFAULT_HTTPS_PORT = 443; #region Helper functions private static void WriteLine(String txt, Stream stream) { byte[] bytes = System.Text.Encoding.ASCII.GetBytes(String.Format("{0}\r\n", txt)); stream.Write(bytes, 0, bytes.Length); } private static void WriteLine(Stream stream) { WriteLine("", stream); } private static string ReadLine(Stream stream) { System.Text.StringBuilder result = new StringBuilder(); while (true) { int b = stream.ReadByte(); if (b == -1) throw new EndOfStreamException(); char c = Convert.ToChar(b); result.Append(c); if (c == '\n') return result.ToString(); } } /// <summary> /// Read HTTP headers, doing any redirects as necessary /// </summary> /// <param name="stream"></param> /// <returns>True if a redirect has occurred - headers will need to be resent.</returns> private static bool ReadHttpHeaders(ref Stream stream, IWebProxy proxy, bool nodelay, int timeout_ms) { string response = ReadLine(stream); int code = getResultCode(response); switch (code) { case 200: break; case 302: string url = ""; while (true) { response = ReadLine(stream); if (response.StartsWith("Location: ")) url = response.Substring(10); if (response.Equals("\r\n") || response.Equals("\n") || response.Equals("")) break; } Uri redirect = new Uri(url.Trim()); stream.Close(); stream = ConnectStream(redirect, proxy, nodelay, timeout_ms); return true; // headers need to be sent again default: if (response.EndsWith("\r\n")) response = response.Substring(0, response.Length - 2); else if (response.EndsWith("\n")) response = response.Substring(0, response.Length - 1); stream.Close(); throw new BadServerResponseException(string.Format("Received error code {0} from the server", response)); } while (true) { string line = ReadLine(stream); if (System.Text.RegularExpressions.Regex.Match(line, "^\\s*$").Success) break; } return false; } public static int getResultCode(string line) { string[] bits = line.Split(new char[] { ' ' }); return (bits.Length < 2 ? 0 : Int32.Parse(bits[1])); } public static bool UseSSL(Uri uri) { return uri.Scheme == "https" || uri.Port == DEFAULT_HTTPS_PORT; } private static bool ValidateServerCertificate( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; } public static long CopyStream(Stream inStream, Stream outStream, DataCopiedDelegate progressDelegate, FuncBool cancellingDelegate) { long bytesWritten = 0; byte[] buffer = new byte[BUFFER_SIZE]; DateTime lastUpdate = DateTime.Now; while (cancellingDelegate == null || !cancellingDelegate()) { int bytesRead = inStream.Read(buffer, 0, buffer.Length); if (bytesRead == 0) break; outStream.Write(buffer, 0, bytesRead); bytesWritten += bytesRead; if (progressDelegate != null && DateTime.Now - lastUpdate > TimeSpan.FromMilliseconds(500)) { progressDelegate(bytesWritten); lastUpdate = DateTime.Now; } } if (cancellingDelegate != null && cancellingDelegate()) throw new CancelledException(); if (progressDelegate != null) progressDelegate(bytesWritten); return bytesWritten; } /// <summary> /// Build a URI from a hostname, a path, and some query arguments /// </summary> /// <param name="args">An even-length array, alternating argument names and values</param> /// <returns></returns> public static Uri BuildUri(string hostname, string path, params object[] args) { // The last argument may be an object[] in its own right, in which case we need // to flatten the array. List<object> flatargs = new List<object>(); foreach (object arg in args) { if (arg is IEnumerable<object>) flatargs.AddRange((IEnumerable<object>)arg); else flatargs.Add(arg); } UriBuilder uri = new UriBuilder(); uri.Scheme = "https"; uri.Port = DEFAULT_HTTPS_PORT; uri.Host = hostname; uri.Path = path; StringBuilder query = new StringBuilder(); for (int i = 0; i < flatargs.Count - 1; i += 2) { string kv; // If the argument is null, don't include it in the URL if (flatargs[i + 1] == null) continue; // bools are special because some xapi calls use presence/absence and some // use "b=true" (not "True") and "b=false". But all accept "b=true" or absent. if (flatargs[i + 1] is bool) { if (!((bool)flatargs[i + 1])) continue; kv = flatargs[i] + "=true"; } else kv = flatargs[i] + "=" + Uri.EscapeDataString(flatargs[i + 1].ToString()); if (query.Length != 0) query.Append('&'); query.Append(kv); } uri.Query = query.ToString(); return uri.Uri; } #endregion private static NetworkStream ConnectSocket(Uri uri, bool nodelay, int timeout_ms) { AddressFamily addressFamily = uri.HostNameType == UriHostNameType.IPv6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork; Socket socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp); socket.NoDelay = nodelay; //socket.ReceiveBufferSize = 64 * 1024; socket.ReceiveTimeout = timeout_ms; socket.SendTimeout = timeout_ms; socket.Connect(uri.Host, uri.Port); return new NetworkStream(socket, true); } /// <summary> /// This function will connect a stream to a uri (host and port), /// negotiating proxies and SSL /// </summary> /// <param name="uri"></param> /// <param name="timeout_ms">Timeout, in ms. 0 for no timeout.</param> /// <returns></returns> public static Stream ConnectStream(Uri uri, IWebProxy proxy, bool nodelay, int timeout_ms) { IMockWebProxy mockProxy = proxy != null ? proxy as IMockWebProxy : null; if (mockProxy != null) return mockProxy.GetStream(uri); Stream stream; bool useProxy = proxy != null && !proxy.IsBypassed(uri); if (useProxy) { Uri proxyURI = proxy.GetProxy(uri); stream = ConnectSocket(proxyURI, nodelay, timeout_ms); } else { stream = ConnectSocket(uri, nodelay, timeout_ms); } try { if (useProxy) { string line = String.Format("CONNECT {0}:{1} HTTP/1.0", uri.Host, uri.Port); WriteLine(line, stream); WriteLine(stream); ReadHttpHeaders(ref stream, proxy, nodelay, timeout_ms); } if (UseSSL(uri)) { SslStream sslStream = new SslStream(stream, false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null); sslStream.AuthenticateAsClient(""); stream = sslStream; } return stream; } catch { stream.Close(); throw; } } private static Stream DO_HTTP(Uri uri, IWebProxy proxy, bool nodelay, int timeout_ms, params string[] headers) { Stream stream = ConnectStream(uri, proxy, nodelay, timeout_ms); int redirects = 0; do { if (redirects > MAX_REDIRECTS) throw new TooManyRedirectsException(redirects, uri); redirects++; foreach (string header in headers) WriteLine(header, stream); WriteLine(stream); stream.Flush(); } while (ReadHttpHeaders(ref stream, proxy, nodelay, timeout_ms)); return stream; } // // The following functions do all the HTTP headers related stuff // returning the stream ready for use // public static Stream CONNECT(Uri uri, IWebProxy proxy, String session, int timeout_ms) { return DO_HTTP(uri, proxy, true, timeout_ms, string.Format("CONNECT {0} HTTP/1.0", uri.PathAndQuery), string.Format("Host: {0}", uri.Host), string.Format("Cookie: session_id={0}", session)); } public static Stream PUT(Uri uri, IWebProxy proxy, long ContentLength, int timeout_ms) { return DO_HTTP(uri, proxy, false, timeout_ms, string.Format("PUT {0} HTTP/1.0", uri.PathAndQuery), string.Format("Content-Length: {0}", ContentLength)); } public static Stream GET(Uri uri, IWebProxy proxy, int timeout_ms) { return DO_HTTP(uri, proxy, false, timeout_ms, string.Format("GET {0} HTTP/1.0", uri.PathAndQuery)); } /// <summary> /// A general HTTP PUT method, with delegates for progress and cancelling. May throw various exceptions. /// </summary> /// <param name="progressDelegate">Delegate called periodically (500ms) with percent complete</param> /// <param name="cancellingDelegate">Delegate called periodically to see if need to cancel</param> /// <param name="uri">URI to PUT to</param> /// <param name="proxy">A proxy to handle the HTTP connection</param> /// <param name="path">Path to file to put</param> /// <param name="timeout_ms">Timeout for the connection in ms. 0 for no timeout.</param> public static void Put(UpdateProgressDelegate progressDelegate, FuncBool cancellingDelegate, Uri uri, IWebProxy proxy, string path, int timeout_ms) { using (Stream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read), requestStream = PUT(uri, proxy, fileStream.Length, timeout_ms)) { long len = fileStream.Length; DataCopiedDelegate dataCopiedDelegate = delegate(long bytes) { if (progressDelegate != null && len > 0) progressDelegate((int)((bytes * 100) / len)); }; CopyStream(fileStream, requestStream, dataCopiedDelegate, cancellingDelegate); } } /// <summary> /// A general HTTP GET method, with delegates for progress and cancelling. May throw various exceptions. /// </summary> /// <param name="dataRxDelegate">Delegate called periodically (500 ms) with the number of bytes transferred</param> /// <param name="cancellingDelegate">Delegate called periodically to see if need to cancel</param> /// <param name="uri">URI to GET from</param> /// <param name="proxy">A proxy to handle the HTTP connection</param> /// <param name="path">Path to file to receive the data</param> /// <param name="timeout_ms">Timeout for the connection in ms. 0 for no timeout.</param> public static void Get(DataCopiedDelegate dataCopiedDelegate, FuncBool cancellingDelegate, Uri uri, IWebProxy proxy, string path, int timeout_ms) { string tmpFile = Path.GetTempFileName(); try { using (Stream fileStream = new FileStream(tmpFile, FileMode.Create, FileAccess.Write, FileShare.None), downloadStream = GET(uri, proxy, timeout_ms)) { CopyStream(downloadStream, fileStream, dataCopiedDelegate, cancellingDelegate); fileStream.Flush(); } File.Delete(path); File.Move(tmpFile, path); } finally { File.Delete(tmpFile); } } } }
// MbUnit Test Framework // // Copyright (c) 2004 Jonathan de Halleux // // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from // the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment in the product // documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must // not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. // // MbUnit HomePage: http://www.mbunit.com // Author: Jonathan de Halleux namespace MbUnit.Core.Reports.Serialization { using System; using System.Xml; using System.Xml.Serialization; /// <summary /> /// <remarks /> [XmlType(IncludeInSchema=true, TypeName="report-assembly")] [XmlRoot(ElementName="report-assembly")] [Serializable] public sealed class ReportAssembly { /// <summary /> /// <remarks /> private ReportAssemblyVersion _version; /// <summary /> /// <remarks /> private string _name; /// <summary /> /// <remarks /> private NamespaceCollection _nameSpaces = new NamespaceCollection(); /// <summary /> /// <remarks /> private ReportCounter _counter; /// <summary /> /// <remarks /> private string _fullName; private string location; private ReportSetUpAndTearDown _setUp = null; private ReportSetUpAndTearDown _tearDown = null; public void UpdateCounts() { this.Counter =new ReportCounter(); foreach(ReportNamespace ns in this.Namespaces) { ns.UpdateCounts(); this.Counter.AddCounts(ns.Counter); } // check setup if (this.SetUp != null && this.SetUp.Result != ReportRunResult.Success) { this.Counter.FailureCount++; return; } // check tearDown if (this.TearDown != null && this.TearDown.Result != ReportRunResult.Success) { this.Counter.FailureCount++; return; } } /// <summary /> /// <remarks /> [XmlElement(ElementName = "tear-down")] public ReportSetUpAndTearDown TearDown { get { return this._tearDown; } set { this._tearDown = value; } } /// <summary /> /// <remarks /> [XmlElement(ElementName = "set-up")] public ReportSetUpAndTearDown SetUp { get { return this._setUp; } set { this._setUp = value; } } /// <summary /> /// <remarks /> [XmlElement(ElementName="counter")] public ReportCounter Counter { get { return this._counter; } set { this._counter = value; } } /// <summary /> /// <remarks /> [XmlElement(ElementName="version")] public ReportAssemblyVersion Version { get { return this._version; } set { this._version = value; } } /// <summary /> /// <remarks /> [XmlArray(ElementName="namespaces")] [XmlArrayItem(ElementName="namespace", Type=typeof(ReportNamespace), IsNullable=false)] public NamespaceCollection Namespaces { get { return this._nameSpaces; } set { this._nameSpaces = value; } } /// <summary /> /// <remarks /> [XmlAttribute(AttributeName="name")] public string Name { get { return this._name; } set { this._name = value; } } [XmlAttribute(AttributeName ="location")] public string Location { get { return this.location; } set { this.location = value; } } /// <summary /> /// <remarks /> [XmlAttribute(AttributeName="full-name")] public string FullName { get { return this._fullName; } set { this._fullName = value; } } [Serializable] public sealed class NamespaceCollection : System.Collections.CollectionBase { /// <summary /> /// <remarks /> public NamespaceCollection() { } /// <summary /> /// <remarks /> public object this[int index] { get { return this.List[index]; } set { this.List[index] = value; } } /// <summary /> /// <remarks /> public void Add(object o) { this.List.Add(o); } /// <summary /> /// <remarks /> public void AddReportNamespace(ReportNamespace o) { this.List.Add(o); } /// <summary /> /// <remarks /> public bool ContainsReportNamespace(ReportNamespace o) { return this.List.Contains(o); } /// <summary /> /// <remarks /> public void RemoveReportNamespace(ReportNamespace o) { this.List.Remove(o); } } } }
// 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.IO; using Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter; using Microsoft.Protocols.TestSuites.FileSharing.Common.TestSuite; using Microsoft.Protocols.TestTools; using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb2; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.Protocols.TestSuites.FileSharing.SMB2.TestSuite { [TestClass] public class AppInstanceIdBasic : SMB2TestBase { #region Variables private Smb2FunctionalClient clientForInitialOpen; private Smb2FunctionalClient clientForReOpen; private string fileName; private string sharePath; #endregion #region Test Initialize and Cleanup [ClassInitialize()] public static void ClassInitialize(TestContext testContext) { TestClassBase.Initialize(testContext); } [ClassCleanup()] public static void ClassCleanup() { TestClassBase.Cleanup(); } #endregion #region Test Case Initialize and Clean up protected override void TestInitialize() { base.TestInitialize(); fileName = string.Format("{0}_{1}.txt", CurrentTestCaseName, Guid.NewGuid()); sharePath = Smb2Utility.GetUncPath(testConfig.SutComputerName, testConfig.BasicFileShare); } protected override void TestCleanup() { if (clientForInitialOpen != null) { try { clientForInitialOpen.Disconnect(); } catch (Exception ex) { BaseTestSite.Log.Add(LogEntryKind.Debug, "Unexpected exception when disconnect clientBeforeFailover: {0}", ex.ToString()); } } if (clientForReOpen != null) { try { clientForReOpen.Disconnect(); } catch (Exception ex) { BaseTestSite.Log.Add(LogEntryKind.Debug, "Unexpected exception when disconnect clientAfterFailover: {0}", ex.ToString()); } } sutProtocolController.DeleteFile(sharePath, fileName); base.TestCleanup(); } #endregion #region Test Cases [TestMethod] [TestCategory(TestCategories.Bvt)] [TestCategory(TestCategories.Smb30)] [TestCategory(TestCategories.AppInstanceId)] [Description("The case is designed to test when client fails over to a new client, the previous open can be closed by the new client with the same AppInstanceId.")] public void BVT_AppInstanceId() { // Client1 opens a file with DurableHandleRequestV2 and AppInstanceId. // Client2 opens that file with DurableHandleRequestV2 and with the same AppInstanceId successfully. // Client1 writes to that file but fails since the first open is closed. #region Check Applicability TestConfig.CheckDialect(DialectRevision.Smb30); TestConfig.CheckCreateContext(CreateContextTypeValue.SMB2_CREATE_APP_INSTANCE_ID, CreateContextTypeValue.SMB2_CREATE_DURABLE_HANDLE_REQUEST_V2); #endregion AppInstanceIdTest(sameAppInstanceId: true, containCreateDurableContext: true); } [TestMethod] [TestCategory(TestCategories.Smb30)] [TestCategory(TestCategories.AppInstanceId)] [TestCategory(TestCategories.InvalidIdentifier)] [Description("The case is designed to test when client fails over to a new client, the previous opened file cannot be closed by the new client with different AppInstanceId.")] public void AppInstanceId_Negative_DifferentAppInstanceIdInReopen() { // Client1 opens a file with DurableHandleRequestV2 and AppInstanceId. // Client2 opens that file with DurableHandleRequestV2 and with the different AppInstanceId, but fails. // Client1 writes to that file and succeeds since the first open is not closed. #region Check Applicability TestConfig.CheckDialect(DialectRevision.Smb30); TestConfig.CheckCreateContext(CreateContextTypeValue.SMB2_CREATE_APP_INSTANCE_ID, CreateContextTypeValue.SMB2_CREATE_DURABLE_HANDLE_REQUEST_V2); #endregion AppInstanceIdTest(sameAppInstanceId: false, containCreateDurableContext: true); } [TestMethod] [TestCategory(TestCategories.Smb311)] [TestCategory(TestCategories.AppInstanceId)] [TestCategory(TestCategories.Positive)] [Description("The case is designed to test if the server implements dialect 3.11, " + "and when client fails over to a new client, the previous open can be closed by the new client with the same AppInstanceId. " + "AppInstanceId should work without DH2Q create context.")] public void AppInstanceId_Smb311() { // Client1 opens a file with create context AppInstanceId, no create context DurableHandleRequestV2 // Client1 writes to that file. // Client2 opens that file with the same AppInstanceId successfully. // Client1 writes to that file but fails since the first open is closed. #region Check Applicability TestConfig.CheckDialect(DialectRevision.Smb311); TestConfig.CheckCreateContext(CreateContextTypeValue.SMB2_CREATE_APP_INSTANCE_ID); #endregion AppInstanceIdTest(sameAppInstanceId: true, containCreateDurableContext: false); } private void AppInstanceIdTest(bool sameAppInstanceId, bool containCreateDurableContext) { string content = Smb2Utility.CreateRandomString(TestConfig.WriteBufferLengthInKb); #region Client 1 Connect to Server BaseTestSite.Log.Add(LogEntryKind.TestStep, "Start the first client by sending the following requests: NEGOTIATE; SESSION_SETUP; TREE_CONNECT"); clientForInitialOpen = new Smb2FunctionalClient(TestConfig.Timeout, TestConfig, BaseTestSite); clientForInitialOpen.ConnectToServer(TestConfig.UnderlyingTransport, TestConfig.SutComputerName, TestConfig.SutIPAddress, TestConfig.ClientNic1IPAddress); clientForInitialOpen.Negotiate(TestConfig.RequestDialects, TestConfig.IsSMB1NegotiateEnabled); clientForInitialOpen.SessionSetup( TestConfig.DefaultSecurityPackage, TestConfig.SutComputerName, TestConfig.AccountCredential, TestConfig.UseServerGssToken); uint treeIdForInitialOpen; clientForInitialOpen.TreeConnect(sharePath, out treeIdForInitialOpen); Guid appInstanceId = Guid.NewGuid(); FILEID fileIdForInitialOpen; BaseTestSite.Log.Add( LogEntryKind.TestStep, "The first client sends CREATE request for exclusive open with SMB2_CREATE_APP_INSTANCE_ID create context."); Smb2CreateContextResponse[] serverCreateContexts; Smb2CreateContextRequest[] createContextsRequestForInitialOpen = null; if (containCreateDurableContext) { BaseTestSite.Log.Add(LogEntryKind.TestStep, "SMB2_CREATE_DURABLE_HANDLE_REQUEST_V2 create context is also included in the CREATE request."); createContextsRequestForInitialOpen = new Smb2CreateContextRequest[] { new Smb2CreateDurableHandleRequestV2 { CreateGuid = Guid.NewGuid() }, new Smb2CreateAppInstanceId { AppInstanceId = appInstanceId } }; } else { BaseTestSite.Log.Add(LogEntryKind.TestStep, "SMB2_CREATE_DURABLE_HANDLE_REQUEST_V2 create context is not included in the CREATE request."); createContextsRequestForInitialOpen = new Smb2CreateContextRequest[] { new Smb2CreateAppInstanceId { AppInstanceId = appInstanceId } }; } clientForInitialOpen.Create( treeIdForInitialOpen, fileName, CreateOptions_Values.FILE_NON_DIRECTORY_FILE, out fileIdForInitialOpen, out serverCreateContexts, RequestedOplockLevel_Values.OPLOCK_LEVEL_NONE, createContextsRequestForInitialOpen, shareAccess: ShareAccess_Values.NONE); #endregion #region Client 2 Connect to Server BaseTestSite.Log.Add(LogEntryKind.TestStep, "Start the second client by sending the following requests: NEGOTIATE; SESSION-SETUP; TREE_CONNECT"); clientForReOpen = new Smb2FunctionalClient(TestConfig.Timeout, TestConfig, BaseTestSite); clientForReOpen.ConnectToServer(TestConfig.UnderlyingTransport, TestConfig.SutComputerName, TestConfig.SutIPAddress, TestConfig.ClientNic2IPAddress); clientForReOpen.Negotiate(TestConfig.RequestDialects, TestConfig.IsSMB1NegotiateEnabled); clientForReOpen.SessionSetup( TestConfig.DefaultSecurityPackage, TestConfig.SutComputerName, TestConfig.AccountCredential, TestConfig.UseServerGssToken); uint treeIdForReOpen; clientForReOpen.TreeConnect(sharePath, out treeIdForReOpen); FILEID fileIdForReOpen; BaseTestSite.Log.Add( LogEntryKind.TestStep, "The second client sends CREATE request for exclusive open with the {0} SMB2_CREATE_APP_INSTANCE_ID of the first client.", sameAppInstanceId ? "same" : "different"); Smb2CreateContextRequest[] createContextsRequestForReOpen = null; if (containCreateDurableContext) { BaseTestSite.Log.Add(LogEntryKind.TestStep, "SMB2_CREATE_DURABLE_HANDLE_REQUEST_V2 create context is also included in the CREATE request."); createContextsRequestForReOpen = new Smb2CreateContextRequest[] { new Smb2CreateDurableHandleRequestV2 { CreateGuid = Guid.NewGuid() }, new Smb2CreateAppInstanceId { AppInstanceId = sameAppInstanceId ? appInstanceId : Guid.NewGuid() } }; } else { BaseTestSite.Log.Add(LogEntryKind.TestStep, "SMB2_CREATE_DURABLE_HANDLE_REQUEST_V2 create context is not included in the CREATE request."); createContextsRequestForReOpen = new Smb2CreateContextRequest[] { new Smb2CreateAppInstanceId { AppInstanceId = sameAppInstanceId ? appInstanceId : Guid.NewGuid() } }; } clientForReOpen.Create( treeIdForReOpen, fileName, CreateOptions_Values.FILE_NON_DIRECTORY_FILE, out fileIdForReOpen, out serverCreateContexts, RequestedOplockLevel_Values.OPLOCK_LEVEL_NONE, createContextsRequestForReOpen, shareAccess: ShareAccess_Values.NONE, checker: (header, response) => { if (sameAppInstanceId) { BaseTestSite.Assert.AreEqual(Smb2Status.STATUS_SUCCESS, header.Status, "The second client should create the open successfully."); } else { BaseTestSite.Assert.AreNotEqual(Smb2Status.STATUS_SUCCESS, header.Status, "The second client should not create the open successfully."); } }); BaseTestSite.Log.Add(LogEntryKind.TestStep, "The first client sends another WRITE request."); if (sameAppInstanceId) { clientForInitialOpen.Write(treeIdForInitialOpen, fileIdForInitialOpen, content, checker: (header, response) => { BaseTestSite.Assert.AreNotEqual( Smb2Status.STATUS_SUCCESS, header.Status, "The initial open is closed. Write should not succeed. Actually server returns with {0}.", Smb2Status.GetStatusCode(header.Status)); BaseTestSite.CaptureRequirementIfAreEqual( Smb2Status.STATUS_FILE_CLOSED, header.Status, RequirementCategory.STATUS_FILE_CLOSED.Id, RequirementCategory.STATUS_FILE_CLOSED.Description); }); // The first open is closed, no need to do clean up job. // Clean up the second client. BaseTestSite.Log.Add(LogEntryKind.TestStep, "Tear down the second client by sending the following requests: CLOSE; TREE_DISCONNECT; LOG_OFF; DISCONNECT"); clientForReOpen.Close(treeIdForReOpen, fileIdForReOpen); clientForReOpen.TreeDisconnect(treeIdForReOpen); clientForReOpen.LogOff(); clientForReOpen.Disconnect(); } else { BaseTestSite.Log.Add(LogEntryKind.TestStep, "The initial open is not closed. Write should succeed."); clientForInitialOpen.Write(treeIdForInitialOpen, fileIdForInitialOpen, content); BaseTestSite.Log.Add(LogEntryKind.TestStep, "Tear down the first client by sending the following requests: CLOSE; TREE_DISCONNECT; LOG_OFF"); clientForInitialOpen.Close(treeIdForInitialOpen, fileIdForInitialOpen); clientForInitialOpen.TreeDisconnect(treeIdForInitialOpen); clientForInitialOpen.LogOff(); // The second client doesn't create the open succesfully, so no need to close the open. BaseTestSite.Log.Add(LogEntryKind.TestStep, "Tear down the second client by sending the following requests: TREE_DISCONNECT; LOG_OFF; DISCONNECT"); clientForReOpen.TreeDisconnect(treeIdForReOpen); clientForReOpen.LogOff(); clientForReOpen.Disconnect(); } #endregion } #endregion } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace ApplicationGateway { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for ApplicationGatewaysOperations. /// </summary> public static partial class ApplicationGatewaysOperationsExtensions { /// <summary> /// Deletes the specified application gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> public static void Delete(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName) { operations.DeleteAsync(resourceGroupName, applicationGatewayName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified application gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, applicationGatewayName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Gets the specified application gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> public static ApplicationGateway Get(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName) { return operations.GetAsync(resourceGroupName, applicationGatewayName).GetAwaiter().GetResult(); } /// <summary> /// Gets the specified application gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ApplicationGateway> GetAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, applicationGatewayName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates the specified application gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update application gateway operation. /// </param> public static ApplicationGateway CreateOrUpdate(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, ApplicationGateway parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, applicationGatewayName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates the specified application gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update application gateway operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ApplicationGateway> CreateOrUpdateAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, ApplicationGateway parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, applicationGatewayName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all application gateways in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> public static IPage<ApplicationGateway> List(this IApplicationGatewaysOperations operations, string resourceGroupName) { return operations.ListAsync(resourceGroupName).GetAwaiter().GetResult(); } /// <summary> /// Lists all application gateways in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ApplicationGateway>> ListAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the application gateways in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<ApplicationGateway> ListAll(this IApplicationGatewaysOperations operations) { return operations.ListAllAsync().GetAwaiter().GetResult(); } /// <summary> /// Gets all the application gateways in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ApplicationGateway>> ListAllAsync(this IApplicationGatewaysOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Starts the specified application gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> public static void Start(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName) { operations.StartAsync(resourceGroupName, applicationGatewayName).GetAwaiter().GetResult(); } /// <summary> /// Starts the specified application gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task StartAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.StartWithHttpMessagesAsync(resourceGroupName, applicationGatewayName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Stops the specified application gateway in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> public static void Stop(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName) { operations.StopAsync(resourceGroupName, applicationGatewayName).GetAwaiter().GetResult(); } /// <summary> /// Stops the specified application gateway in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task StopAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.StopWithHttpMessagesAsync(resourceGroupName, applicationGatewayName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Gets the backend health of the specified application gateway in a resource /// group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='expand'> /// Expands BackendAddressPool and BackendHttpSettings referenced in backend /// health. /// </param> public static ApplicationGatewayBackendHealth BackendHealth(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, string expand = default(string)) { return operations.BackendHealthAsync(resourceGroupName, applicationGatewayName, expand).GetAwaiter().GetResult(); } /// <summary> /// Gets the backend health of the specified application gateway in a resource /// group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='expand'> /// Expands BackendAddressPool and BackendHttpSettings referenced in backend /// health. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ApplicationGatewayBackendHealth> BackendHealthAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BackendHealthWithHttpMessagesAsync(resourceGroupName, applicationGatewayName, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the specified application gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> public static void BeginDelete(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName) { operations.BeginDeleteAsync(resourceGroupName, applicationGatewayName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified application gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, applicationGatewayName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Creates or updates the specified application gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update application gateway operation. /// </param> public static ApplicationGateway BeginCreateOrUpdate(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, ApplicationGateway parameters) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, applicationGatewayName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates the specified application gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update application gateway operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ApplicationGateway> BeginCreateOrUpdateAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, ApplicationGateway parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, applicationGatewayName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Starts the specified application gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> public static void BeginStart(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName) { operations.BeginStartAsync(resourceGroupName, applicationGatewayName).GetAwaiter().GetResult(); } /// <summary> /// Starts the specified application gateway. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginStartAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.BeginStartWithHttpMessagesAsync(resourceGroupName, applicationGatewayName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Stops the specified application gateway in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> public static void BeginStop(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName) { operations.BeginStopAsync(resourceGroupName, applicationGatewayName).GetAwaiter().GetResult(); } /// <summary> /// Stops the specified application gateway in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginStopAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.BeginStopWithHttpMessagesAsync(resourceGroupName, applicationGatewayName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Gets the backend health of the specified application gateway in a resource /// group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='expand'> /// Expands BackendAddressPool and BackendHttpSettings referenced in backend /// health. /// </param> public static ApplicationGatewayBackendHealth BeginBackendHealth(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, string expand = default(string)) { return operations.BeginBackendHealthAsync(resourceGroupName, applicationGatewayName, expand).GetAwaiter().GetResult(); } /// <summary> /// Gets the backend health of the specified application gateway in a resource /// group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationGatewayName'> /// The name of the application gateway. /// </param> /// <param name='expand'> /// Expands BackendAddressPool and BackendHttpSettings referenced in backend /// health. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ApplicationGatewayBackendHealth> BeginBackendHealthAsync(this IApplicationGatewaysOperations operations, string resourceGroupName, string applicationGatewayName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginBackendHealthWithHttpMessagesAsync(resourceGroupName, applicationGatewayName, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all application gateways in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<ApplicationGateway> ListNext(this IApplicationGatewaysOperations operations, string nextPageLink) { return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Lists all application gateways in a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ApplicationGateway>> ListNextAsync(this IApplicationGatewaysOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the application gateways in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<ApplicationGateway> ListAllNext(this IApplicationGatewaysOperations operations, string nextPageLink) { return operations.ListAllNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all the application gateways in a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ApplicationGateway>> ListAllNextAsync(this IApplicationGatewaysOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System; using System.Threading; using TextWindow; using System.Windows.Forms; using edu.wpi.disco; using edu.wpi.disco.lang; using edu.wpi.disco.plugin; using edu.wpi.cetask; public class DiscoUnity : MonoBehaviour { public const String VERSION = "1.0.6"; // Note: Sleep below is a quick and easy way to prevent Disco from using 100% of processor // A more sophisticated approach would would adjust to how much was used in each update // fields accessible from Inspector public int Sleep = 1000; public System.Threading.ThreadPriority Priority = System.Threading.ThreadPriority.BelowNormal; public bool Tracing = false; public bool Console = false; public bool Menu = false; public String Models; //TODO thread-safe dynamic loading private bool discoRunning = true; private bool formStarted, formLoaded; private bool sensing; private bool onWindows = (Environment.OSVersion.Platform == PlatformID.Win32NT); // for synchronizing execution of NPC actions (including utterances) private Task task; // for synchronizing presentation and choice of player menu private String[] menu, lastMenu; private bool newMenu; // because menu can be null private java.util.List items; // corresponding to lastMenu private Agenda.Plugin.Item chosen; private String formatted; // text for chosen utterance private edu.wpi.disco.Console console; private bool firstPrompt = true; // following are all readonly (see initializations in Awake and Start) private EventWaitHandle taskHandle, menuHandle, sensingHandle; private Program program; private TextForm form; private Player player; private Agent npc; private Thread discoThread, formThread; private Interaction interaction; private W32ClassBatchUnregisterer w32Classes; // for overriding to present NPC utterance output // called on Unity thread protected virtual void Say (String utterance) { Debug.Log("SAY "+utterance); } // for overriding to present player utterance choices // called on Unity thread // note that we do *not* assume game is locked until player responds (see MenuChoice) // NB: this may be called with null to clear the menu! protected virtual void UpdateMenu (String[] choices) { if ( choices != null ) { String menu = choices[0]; for (int i = 1; i < choices.Length; i++) menu += Environment.NewLine+choices[i]; Debug.Log(menu); } } protected String[] GetLastMenu () { return lastMenu; } // call to communicate player menu choice back to Disco // called on Unity (GUI) thread // note zero refers to first choice (normal array indexing) // note we pass back in the original choices array to guarantee that is same menu // returns false iff there if choice out of bounds or new menu has been posted public bool MenuChoice (String[] choices, int choice) { if ( newMenu || choices != lastMenu || choice < 0 || lastMenu == null || choice >= lastMenu.Length ) return false; chosen = (Agenda.Plugin.Item) items.get(choice); formatted = lastMenu[choice]; // need to remember actual string due to alternatives lastMenu = null; // prevent selecting twice from same menu return true; } // return discourse state public edu.wpi.disco.Disco getDisco () { return interaction.getDisco(); } // note Awake, Start, Update, etc. made public virtual so can override in extensions public virtual void Awake () // do non-primitive initializations for MonoBehavior's here { taskHandle = new EventWaitHandle(false, EventResetMode.ManualReset); menuHandle = new EventWaitHandle(false, EventResetMode.ManualReset); sensingHandle = new EventWaitHandle(false, EventResetMode.ManualReset); w32Classes = new W32ClassBatchUnregisterer(); program = new Program(); player = new Player("Player"); npc = new NPC(this, "NPC"); interaction = new Interaction(npc, player); interaction.setOk(false); // suppress default Ok's // support calling Debug.Log from scripts getDisco().eval( "Debug = { Log : function (obj) { TextWindow.Program.Log(obj); }}", "DiscoUnity"); discoThread = new Thread ((ThreadStart)delegate { try { while (discoRunning) { // start console if requested if ( Console && !formStarted ) { formStarted = true; //second parameter is called when the console Form is loaded program.StartWindow (formThread, (sender, evt) => { if(onWindows) w32Classes.AddWindowClassesRecursively ((Control)sender); formLoaded = true; form.Writer.WriteLine(" DiscoUnity "+VERSION); console = new edu.wpi.disco.Console(null, interaction); interaction.setConsole(console); console.init(getDisco()); console.setReader(new Program.ConsoleReader(form)); form.shell.shellTextBox.GotFocus += (s, e) => { // improve window readability if ( !firstPrompt && form.shell.shellTextBox.IsCaretJustBeforePrompt() ) { firstPrompt = false; form.Writer.Write(console.getPrompt()); } }; interaction.start(true); // start console thread }); } // do Sensing on Unity thread sensing = true; sensingHandle.WaitOne(); sensingHandle.Reset(); UpdateDisco(getDisco()); // manage toplevel goals getDisco().tick(); // update conditions // process player menu choice, if any if ( chosen != null ) { getDisco().doneUtterance(chosen.task, formatted); done(true, chosen.task, chosen.contributes); chosen = null; formatted = null; } // process NPC response, if any Agenda.Plugin.Item item = npc.respondIf(interaction, true); if ( item != null && !item.task.Equals(npc.getLastUtterance()) ) npc.done(interaction, item); if ( Menu ) { // update player menu options (including empty) java.util.List newItems = player.generate(interaction); if ( !newItems.equals(items) ) { String [] choices = null; if ( !newItems.isEmpty() ) { choices = new String[newItems.size()]; int i = 0; java.util.Iterator l = newItems.iterator(); while ( l.hasNext() ) choices[i++] = translate(((Agenda.Plugin.Item) l.next()).task); } lastMenu = null; // block choosing from old menu menu = choices; items = newItems; newMenu = true; menuHandle.WaitOne(); // execute on Unity thread menuHandle.Reset(); lastMenu = choices; } } // sleep for a while Thread.Sleep(Sleep); } } catch (Exception e) { Debug.Log("Disco thread terminating: "+e); if ( Tracing ) Debug.Log(e.ToString()); } }); discoThread.IsBackground = true; discoThread.Priority = Priority; formThread = new Thread ((ThreadStart)delegate { try { /* while (true) { // for testing program.WriteLine("Echo: " + program.ReadLine()); } */ form = program.GetForm(); java.lang.System.setOut (new java.io.PrintStream (new Program.ConsoleOut (form.Writer), true)); java.lang.System.setErr (java.lang.System.@out); } catch (Exception e) { Debug.Log("Console form thread terminating: "+e); } }); formThread.IsBackground = true; } public virtual void Start() { if(onWindows) { AppDomain.CurrentDomain.DomainUnload += delegate { EnsureFormIsClosed (); w32Classes.TryUnregisterAll (); }; } if ( Models.Length != 0 ) { String[] modelArray = Models.Split(new char[] {','}); for (int i = 0; i < modelArray.Length; i++) { String name = modelArray[i]; TextAsset model =(TextAsset) Resources.Load(name); if ( model == null ) Debug.LogWarning("Cannot find task model: "+name); else { if ( Tracing ) Debug.Log("LOADING "+name); TextAsset properties = (TextAsset) Resources.Load(name+".properties"); TextAsset translate = (TextAsset) Resources.Load(name+".translate.properties"); getDisco().load(name, model.text, properties == null ? null : properties.text, translate == null ? null : translate.text); } } } discoThread.Start(); } // called on Disco or Console thread private void done (bool external, Task occurrence, Plan contributes) { occurrence.done(external); if ( !external || occurrence is Utterance ) { // execute on Unity Thread task = occurrence; taskHandle.WaitOne(); taskHandle.Reset(); } if ( contributes == null ) contributes = getDisco().explainBest(occurrence, true); getDisco().done(occurrence, contributes); if ( console != null ) { // improve readability if ( !form.shell.shellTextBox.IsCaretJustBeforePrompt() ) form.Writer.WriteLine(); firstPrompt = false; console.done(occurrence); } } class NPC : Agent { private readonly DiscoUnity disco; public NPC (DiscoUnity disco, String name) : base(name) { this.disco = disco; } override public void done (Interaction interaction, Agenda.Plugin.Item item) { disco.done(false, item.task, item.contributes); if ( item.task is Utterance ) lastUtterance = (Utterance) item.task; retry(interaction.getDisco()); } } class Player : edu.wpi.disco.User { public Player (String name) : base(name) { // tweak TTSay plugins agenda.remove(java.lang.Class.forName("edu.wpi.disco.plugin.ProposeHowPlugin")); new ProposeHowPlugin(agenda, 30); agenda.remove(java.lang.Class.forName("edu.wpi.disco.plugin.ProposeShouldSelfPlugin")); new ProposeShouldSelfPlugin(agenda, 90, true); //suppressExternal } } // this method is called on Unity thread once before each Disco update protected virtual void Sensing () {} // this method is called on Disco thread once after Sensing and // before each Disco update, e.g., to manage toplevel goals protected virtual void UpdateDisco (Disco disco) {} public virtual void Update () // called on Unity thread { if ( form != null && formLoaded ) { if ( !Console && form.Visible ) form.Hide(); if ( Console && !form.Visible ) form.Show(); } if ( sensing ) { Sensing(); sensing = false; sensingHandle.Set(); } if ( task != null ) { if ( Tracing ) Debug.Log("EXECUTING "+task); execute(task); if ( task is Utterance && task.isSystem() ) Say(translate(task)); task = null; taskHandle.Set(); } if ( newMenu ) { UpdateMenu(menu); menu = null; newMenu = false; menuHandle.Set(); } } private static void execute (Task task) { Script script = task.getScript(); if ( script != null ) script.eval(task); } private String translate (Task task) { java.lang.StringBuffer buffer = new java.lang.StringBuffer( Utils.capitalize(getDisco().translate((Utterance) task))); Utils.endSentence(buffer); return buffer.toString(); } public virtual void OnDestroy () { if ( interaction != null ) interaction.exit(); discoRunning = false; if ( sensingHandle != null ) sensingHandle.Set(); if ( taskHandle != null ) taskHandle.Set(); if ( menuHandle != null ) menuHandle.Set(); EnsureFormIsClosed (); } void EnsureFormIsClosed () { if (form != null) { form.Close (); form.Dispose (); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Linq; using Microsoft.CSharp.RuntimeBinder.Errors; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal enum MemLookFlags : uint { None = 0, Ctor = EXPRFLAG.EXF_CTOR, NewObj = EXPRFLAG.EXF_NEWOBJCALL, Operator = EXPRFLAG.EXF_OPERATOR, Indexer = EXPRFLAG.EXF_INDEXER, UserCallable = EXPRFLAG.EXF_USERCALLABLE, BaseCall = EXPRFLAG.EXF_BASECALL, // All EXF flags are < 0x01000000 MustBeInvocable = 0x20000000, TypeVarsAllowed = 0x40000000, ExtensionCall = 0x80000000, All = Ctor | NewObj | Operator | Indexer | UserCallable | BaseCall | MustBeInvocable | TypeVarsAllowed | ExtensionCall } ///////////////////////////////////////////////////////////////////////////////// // MemberLookup class handles looking for a member within a type and its // base types. This only handles AGGTYPESYMs and TYVARSYMs. // // Lookup must be called before any other methods. internal class MemberLookup { // The inputs to Lookup. private CSemanticChecker _pSemanticChecker; private SymbolLoader _pSymbolLoader; private CType _typeSrc; private EXPR _obj; private CType _typeQual; private ParentSymbol _symWhere; private Name _name; private int _arity; private MemLookFlags _flags; private CMemberLookupResults _results; // For maintaining the type array. We throw the first 8 or so here. private List<AggregateType> _rgtypeStart; // Results of the lookup. private List<AggregateType> _prgtype; private int _csym; // Number of syms found. private SymWithType _swtFirst; // The first symbol found. private List<MethPropWithType> _methPropWithTypeList; // When we look up methods, we want to keep the list of all candidate methods given a particular name. // These are for error reporting. private SymWithType _swtAmbig; // An ambiguous symbol. private SymWithType _swtInaccess; // An inaccessible symbol. private SymWithType _swtBad; // If we're looking for a ructor or indexer, this matched on name, but isn't the right thing. private SymWithType _swtBogus; // A bogus member - such as an indexed property. private SymWithType _swtBadArity; // An symbol with the wrong arity. private SymWithType _swtAmbigWarn; // An ambiguous symbol, but only warn. // We have an override symbol, which we've errored on in SymbolPrepare. If we have nothing better, use this. // This is because if we have: // // class C : D // { // public override int M() { } // static void Main() // { // C c = new C(); // c.M(); <-- // // We try to look up M, and find the M on C, but throw it out since its an override, and // we want the virtual that it overrides. However, in this case, we'll never find that // virtual, since it doesn't exist. We therefore want to use the override anyway, and // continue on to give results with that. private SymWithType _swtOverride; private bool _fMulti; // Whether symFirst is of a kind for which we collect multiples (methods and indexers). /*************************************************************************************************** Another match was found. Increment the count of syms and add the type to our list if it's not already there. ***************************************************************************************************/ private void RecordType(AggregateType type, Symbol sym) { Debug.Assert(type != null && sym != null); if (!_prgtype.Contains(type)) { _prgtype.Add(type); } // Now record the sym.... _csym++; // If it is first, record it. if (_swtFirst == null) { _swtFirst.Set(sym, type); Debug.Assert(_csym == 1); Debug.Assert(_prgtype[0] == type); _fMulti = sym.IsMethodSymbol() || sym.IsPropertySymbol() && sym.AsPropertySymbol().isIndexer(); } } /****************************************************************************** Search just the given type (not any bases). Returns true iff it finds something (which will have been recorded by RecordType). pfHideByName is set to true iff something was found that hides all members of base types (eg, a hidebyname method). ******************************************************************************/ private bool SearchSingleType(AggregateType typeCur, out bool pfHideByName) { bool fFoundSome = false; MethPropWithType mwpInsert; pfHideByName = false; // Make sure this type is accessible. It may not be due to private inheritance // or friend assemblies. bool fInaccess = !GetSemanticChecker().CheckTypeAccess(typeCur, _symWhere); if (fInaccess && (_csym != 0 || _swtInaccess != null)) return false; // Loop through symbols. Symbol symCur = null; for (symCur = GetSymbolLoader().LookupAggMember(_name, typeCur.getAggregate(), symbmask_t.MASK_ALL); symCur != null; symCur = GetSymbolLoader().LookupNextSym(symCur, typeCur.getAggregate(), symbmask_t.MASK_ALL)) { // Check for arity. switch (symCur.getKind()) { case SYMKIND.SK_MethodSymbol: // For non-zero arity, only methods of the correct arity are considered. // For zero arity, don't filter out any methods since we do type argument // inferencing. if (_arity > 0 && symCur.AsMethodSymbol().typeVars.size != _arity) { if (!_swtBadArity) _swtBadArity.Set(symCur, typeCur); continue; } break; case SYMKIND.SK_AggregateSymbol: // For types, always filter on arity. if (symCur.AsAggregateSymbol().GetTypeVars().size != _arity) { if (!_swtBadArity) _swtBadArity.Set(symCur, typeCur); continue; } break; case SYMKIND.SK_TypeParameterSymbol: if ((_flags & MemLookFlags.TypeVarsAllowed) == 0) continue; if (_arity > 0) { if (!_swtBadArity) _swtBadArity.Set(symCur, typeCur); continue; } break; default: // All others are only considered when arity is zero. if (_arity > 0) { if (!_swtBadArity) _swtBadArity.Set(symCur, typeCur); continue; } break; } // Check for user callability. if (symCur.IsOverride() && !symCur.IsHideByName()) { if (!_swtOverride) { _swtOverride.Set(symCur, typeCur); } continue; } if ((_flags & MemLookFlags.UserCallable) != 0 && symCur.IsMethodOrPropertySymbol() && !symCur.AsMethodOrPropertySymbol().isUserCallable()) { bool bIsIndexedProperty = false; // If its an indexed property method symbol, let it through. if (symCur.IsMethodSymbol() && symCur.AsMethodSymbol().isPropertyAccessor() && ((symCur.name.Text.StartsWith("set_", StringComparison.Ordinal) && symCur.AsMethodSymbol().Params.size > 1) || (symCur.name.Text.StartsWith("get_", StringComparison.Ordinal) && symCur.AsMethodSymbol().Params.size > 0))) { bIsIndexedProperty = true; } if (!bIsIndexedProperty) { if (!_swtInaccess) { _swtInaccess.Set(symCur, typeCur); } continue; } } if (fInaccess || !GetSemanticChecker().CheckAccess(symCur, typeCur, _symWhere, _typeQual)) { // Not accessible so get the next sym. if (!_swtInaccess) { _swtInaccess.Set(symCur, typeCur); } if (fInaccess) { return false; } continue; } // Make sure that whether we're seeing a ctor, operator, or indexer is consistent with the flags. if (((_flags & MemLookFlags.Ctor) == 0) != (!symCur.IsMethodSymbol() || !symCur.AsMethodSymbol().IsConstructor()) || ((_flags & MemLookFlags.Operator) == 0) != (!symCur.IsMethodSymbol() || !symCur.AsMethodSymbol().isOperator) || ((_flags & MemLookFlags.Indexer) == 0) != (!symCur.IsPropertySymbol() || !symCur.AsPropertySymbol().isIndexer())) { if (!_swtBad) { _swtBad.Set(symCur, typeCur); } continue; } // We can't call CheckBogus on methods or indexers because if the method has the wrong // number of parameters people don't think they should have to /r the assemblies containing // the parameter types and they complain about the resulting CS0012 errors. if (!symCur.IsMethodSymbol() && (_flags & MemLookFlags.Indexer) == 0 && GetSemanticChecker().CheckBogus(symCur)) { // A bogus member - we can't use these, so only record them for error reporting. if (!_swtBogus) { _swtBogus.Set(symCur, typeCur); } continue; } // if we are in a calling context then we should only find a property if it is delegate valued if ((_flags & MemLookFlags.MustBeInvocable) != 0) { if ((symCur.IsFieldSymbol() && !IsDelegateType(symCur.AsFieldSymbol().GetType(), typeCur) && !IsDynamicMember(symCur)) || (symCur.IsPropertySymbol() && !IsDelegateType(symCur.AsPropertySymbol().RetType, typeCur) && !IsDynamicMember(symCur))) { if (!_swtBad) { _swtBad.Set(symCur, typeCur); } continue; } } if (symCur.IsMethodOrPropertySymbol()) { mwpInsert = new MethPropWithType(symCur.AsMethodOrPropertySymbol(), typeCur); _methPropWithTypeList.Add(mwpInsert); } // We have a visible symbol. fFoundSome = true; if (_swtFirst) { if (!typeCur.isInterfaceType()) { // Non-interface case. Debug.Assert(_fMulti || typeCur == _prgtype[0]); if (!_fMulti) { if (_swtFirst.Sym.IsFieldSymbol() && symCur.IsEventSymbol() #if !CSEE // The isEvent bit is only set on symbols which come from source... // This is not a problem for the compiler because the field is only // accessible in the scope in whcih it is declared, // but in the EE we ignore accessibility... && _swtFirst.Field().isEvent #endif ) { // m_swtFirst is just the field behind the event symCur so ignore symCur. continue; } else if (_swtFirst.Sym.IsFieldSymbol() && symCur.IsEventSymbol()) { // symCur is the matching event. continue; } goto LAmbig; } if (_swtFirst.Sym.getKind() != symCur.getKind()) { if (typeCur == _prgtype[0]) goto LAmbig; // This one is hidden by the first one. This one also hides any more in base types. pfHideByName = true; continue; } } // Interface case. // m_fMulti : n n n y y y y y // same-kind : * * * y n n n n // fDiffHidden: * * * * y n n n // meth : * * * * * y n * can n happen? just in case, we better handle it.... // hack : n * y * * y * n // meth-2 : * n y * * * * * // res : A A S R H H A A else if (!_fMulti) { // Give method groups priority. if ( /* !GetSymbolLoader().options.fLookupHack ||*/ !symCur.IsMethodSymbol()) goto LAmbig; _swtAmbigWarn = _swtFirst; // Erase previous results so we'll record this method as the first. _prgtype = new List<AggregateType>(); _csym = 0; _swtFirst.Clear(); _swtAmbig.Clear(); } else if (_swtFirst.Sym.getKind() != symCur.getKind()) { if (!typeCur.fDiffHidden) { // Give method groups priority. if ( /*!GetSymbolLoader().options.fLookupHack ||*/ !_swtFirst.Sym.IsMethodSymbol()) goto LAmbig; if (!_swtAmbigWarn) _swtAmbigWarn.Set(symCur, typeCur); } // This one is hidden by another. This one also hides any more in base types. pfHideByName = true; continue; } } RecordType(typeCur, symCur); if (symCur.IsMethodOrPropertySymbol() && symCur.AsMethodOrPropertySymbol().isHideByName) pfHideByName = true; // We've found a symbol in this type but need to make sure there aren't any conflicting // syms here, so keep searching the type. } Debug.Assert(!fInaccess || !fFoundSome); return fFoundSome; LAmbig: // Ambiguous! if (!_swtAmbig) _swtAmbig.Set(symCur, typeCur); pfHideByName = true; return true; } private bool IsDynamicMember(Symbol sym) { System.Runtime.CompilerServices.DynamicAttribute da = null; if (sym.IsFieldSymbol()) { if (!sym.AsFieldSymbol().getType().isPredefType(PredefinedType.PT_OBJECT)) { return false; } var o = sym.AsFieldSymbol().AssociatedFieldInfo.GetCustomAttributes(typeof(System.Runtime.CompilerServices.DynamicAttribute), false).ToArray(); if (o.Length == 1) { da = o[0] as System.Runtime.CompilerServices.DynamicAttribute; } } else { Debug.Assert(sym.IsPropertySymbol()); if (!sym.AsPropertySymbol().getType().isPredefType(PredefinedType.PT_OBJECT)) { return false; } var o = sym.AsPropertySymbol().AssociatedPropertyInfo.GetCustomAttributes(typeof(System.Runtime.CompilerServices.DynamicAttribute), false).ToArray(); if (o.Length == 1) { da = o[0] as System.Runtime.CompilerServices.DynamicAttribute; } } if (da == null) { return false; } return (da.TransformFlags.Count == 0 || (da.TransformFlags.Count == 1 && da.TransformFlags[0])); } /****************************************************************************** Lookup in a class and its bases (until *ptypeEnd is hit). ptypeEnd [in/out] - *ptypeEnd should be either null or object. If we find something here that would hide members of object, this sets *ptypeEnd to null. Returns true when searching should continue to the interfaces. ******************************************************************************/ private bool LookupInClass(AggregateType typeStart, ref AggregateType ptypeEnd) { Debug.Assert(!_swtFirst || _fMulti); Debug.Assert(typeStart != null && !typeStart.isInterfaceType() && (ptypeEnd == null || typeStart != ptypeEnd)); AggregateType typeEnd = ptypeEnd; AggregateType typeCur; // Loop through types. Loop until we hit typeEnd (object or null). for (typeCur = typeStart; typeCur != typeEnd && typeCur != null; typeCur = typeCur.GetBaseClass()) { Debug.Assert(!typeCur.isInterfaceType()); bool fHideByName = false; SearchSingleType(typeCur, out fHideByName); _flags &= ~MemLookFlags.TypeVarsAllowed; if (_swtFirst && !_fMulti) { // Everything below this type and in interfaces is hidden. return false; } if (fHideByName) { // This hides everything below it and in object, but not in the interfaces! ptypeEnd = null; // Return true to indicate that it's ok to search additional types. return true; } if ((_flags & MemLookFlags.Ctor) != 0) { // If we're looking for a constructor, don't check base classes or interfaces. return false; } } Debug.Assert(typeCur == typeEnd); return true; } /****************************************************************************** Returns true if searching should continue to object. ******************************************************************************/ private bool LookupInInterfaces(AggregateType typeStart, TypeArray types) { Debug.Assert(!_swtFirst || _fMulti); Debug.Assert(typeStart == null || typeStart.isInterfaceType()); Debug.Assert(typeStart != null || types.size != 0); // Clear all the hidden flags. Anything found in a class hides any other // kind of member in all the interfaces. if (typeStart != null) { typeStart.fAllHidden = false; typeStart.fDiffHidden = (_swtFirst != null); } for (int i = 0; i < types.size; i++) { AggregateType type = types.Item(i).AsAggregateType(); Debug.Assert(type.isInterfaceType()); type.fAllHidden = false; type.fDiffHidden = !!_swtFirst; } bool fHideObject = false; AggregateType typeCur = typeStart; int itypeNext = 0; if (typeCur == null) { typeCur = types.Item(itypeNext++).AsAggregateType(); } Debug.Assert(typeCur != null); // Loop through the interfaces. for (; ;) { Debug.Assert(typeCur != null && typeCur.isInterfaceType()); bool fHideByName = false; if (!typeCur.fAllHidden && SearchSingleType(typeCur, out fHideByName)) { fHideByName |= !_fMulti; // Mark base interfaces appropriately. TypeArray ifaces = typeCur.GetIfacesAll(); for (int i = 0; i < ifaces.size; i++) { AggregateType type = ifaces.Item(i).AsAggregateType(); Debug.Assert(type.isInterfaceType()); if (fHideByName) type.fAllHidden = true; type.fDiffHidden = true; } // If we hide all base types, that includes object! if (fHideByName) fHideObject = true; } _flags &= ~MemLookFlags.TypeVarsAllowed; if (itypeNext >= types.size) return !fHideObject; // Substitution has already been done. typeCur = types.Item(itypeNext++).AsAggregateType(); } } private SymbolLoader GetSymbolLoader() { return _pSymbolLoader; } private CSemanticChecker GetSemanticChecker() { return _pSemanticChecker; } private ErrorHandling GetErrorContext() { return GetSymbolLoader().GetErrorContext(); } private void ReportBogus(SymWithType swt) { Debug.Assert(swt.Sym.hasBogus() && swt.Sym.checkBogus()); MethodSymbol meth1; MethodSymbol meth2; switch (swt.Sym.getKind()) { case SYMKIND.SK_EventSymbol: break; case SYMKIND.SK_PropertySymbol: if (swt.Prop().useMethInstead) { meth1 = swt.Prop().methGet; meth2 = swt.Prop().methSet; ReportBogusForEventsAndProperties(swt, meth1, meth2); return; } break; case SYMKIND.SK_MethodSymbol: if (swt.Meth().name == GetSymbolLoader().GetNameManager().GetPredefName(PredefinedName.PN_INVOKE) && swt.Meth().getClass().IsDelegate()) { swt.Set(swt.Meth().getClass(), swt.GetType()); } break; default: break; } // Generic bogus error. GetErrorContext().ErrorRef(ErrorCode.ERR_BindToBogus, swt); } private void ReportBogusForEventsAndProperties(SymWithType swt, MethodSymbol meth1, MethodSymbol meth2) { if (meth1 != null && meth2 != null) { GetErrorContext().Error(ErrorCode.ERR_BindToBogusProp2, swt.Sym.name, new SymWithType(meth1, swt.GetType()), new SymWithType(meth2, swt.GetType()), new ErrArgRefOnly(swt.Sym)); return; } if (meth1 != null || meth2 != null) { GetErrorContext().Error(ErrorCode.ERR_BindToBogusProp1, swt.Sym.name, new SymWithType(meth1 != null ? meth1 : meth2, swt.GetType()), new ErrArgRefOnly(swt.Sym)); return; } throw Error.InternalCompilerError(); } private bool IsDelegateType(CType pSrcType, AggregateType pAggType) { CType pInstantiatedType = GetSymbolLoader().GetTypeManager().SubstType(pSrcType, pAggType, pAggType.GetTypeArgsAll()); return pInstantiatedType.isDelegateType(); } ///////////////////////////////////////////////////////////////////////////////// // Public methods. public MemberLookup() { _methPropWithTypeList = new List<MethPropWithType>(); _rgtypeStart = new List<AggregateType>(); _swtFirst = new SymWithType(); _swtAmbig = new SymWithType(); _swtInaccess = new SymWithType(); _swtBad = new SymWithType(); _swtBogus = new SymWithType(); _swtBadArity = new SymWithType(); _swtAmbigWarn = new SymWithType(); _swtOverride = new SymWithType(); } /*************************************************************************************************** Lookup must be called before anything else can be called. typeSrc - Must be an AggregateType or TypeParameterType. obj - the expression through which the member is being accessed. This is used for accessibility of protected members and for constructing a MEMGRP from the results of the lookup. It is legal for obj to be an EK_CLASS, in which case it may be used for accessibility, but will not be used for MEMGRP construction. symWhere - the symbol from with the name is being accessed (for checking accessibility). name - the name to look for. arity - the number of type args specified. Only members that support this arity are found. Note that when arity is zero, all methods are considered since we do type argument inferencing. flags - See MemLookFlags. TypeVarsAllowed only applies to the most derived type (not base types). ***************************************************************************************************/ public bool Lookup(CSemanticChecker checker, CType typeSrc, EXPR obj, ParentSymbol symWhere, Name name, int arity, MemLookFlags flags) { Debug.Assert((flags & ~MemLookFlags.All) == 0); Debug.Assert(obj == null || obj.type != null); Debug.Assert(typeSrc.IsAggregateType() || typeSrc.IsTypeParameterType()); Debug.Assert(checker != null); _prgtype = _rgtypeStart; // Save the inputs for error handling, etc. _pSemanticChecker = checker; _pSymbolLoader = checker.GetSymbolLoader(); _typeSrc = typeSrc; _obj = (obj != null && !obj.isCLASS()) ? obj : null; _symWhere = symWhere; _name = name; _arity = arity; _flags = flags; if ((_flags & MemLookFlags.BaseCall) != 0) _typeQual = null; else if ((_flags & MemLookFlags.Ctor) != 0) _typeQual = _typeSrc; else if (obj != null) _typeQual = (CType)obj.type; else _typeQual = null; // Determine what to search. AggregateType typeCls1 = null; AggregateType typeIface = null; TypeArray ifaces = BSYMMGR.EmptyTypeArray(); AggregateType typeCls2 = null; if (typeSrc.IsTypeParameterType()) { Debug.Assert((_flags & (MemLookFlags.Ctor | MemLookFlags.NewObj | MemLookFlags.Operator | MemLookFlags.BaseCall | MemLookFlags.TypeVarsAllowed)) == 0); _flags &= ~MemLookFlags.TypeVarsAllowed; ifaces = typeSrc.AsTypeParameterType().GetInterfaceBounds(); typeCls1 = typeSrc.AsTypeParameterType().GetEffectiveBaseClass(); if (ifaces.size > 0 && typeCls1.isPredefType(PredefinedType.PT_OBJECT)) typeCls1 = null; } else if (!typeSrc.isInterfaceType()) { typeCls1 = typeSrc.AsAggregateType(); if (typeCls1.IsWindowsRuntimeType()) { ifaces = typeCls1.GetWinRTCollectionIfacesAll(GetSymbolLoader()); } } else { Debug.Assert(typeSrc.isInterfaceType()); Debug.Assert((_flags & (MemLookFlags.Ctor | MemLookFlags.NewObj | MemLookFlags.Operator | MemLookFlags.BaseCall)) == 0); typeIface = typeSrc.AsAggregateType(); ifaces = typeIface.GetIfacesAll(); } if (typeIface != null || ifaces.size > 0) typeCls2 = GetSymbolLoader().GetReqPredefType(PredefinedType.PT_OBJECT); // Search the class first (except possibly object). if (typeCls1 == null || LookupInClass(typeCls1, ref typeCls2)) { // Search the interfaces. if ((typeIface != null || ifaces.size > 0) && LookupInInterfaces(typeIface, ifaces) && typeCls2 != null) { // Search object last. Debug.Assert(typeCls2 != null && typeCls2.isPredefType(PredefinedType.PT_OBJECT)); AggregateType result = null; LookupInClass(typeCls2, ref result); } } // if we are reqested with extension methods _results = new CMemberLookupResults(GetAllTypes(), _name); return !FError(); } public CMemberLookupResults GetResults() { return _results; } // Whether there were errors. public bool FError() { return !_swtFirst || _swtAmbig; } // The first symbol found. public Symbol SymFirst() { return _swtFirst.Sym; } public SymWithType SwtFirst() { return _swtFirst; } public SymWithType SwtInaccessible() { return _swtInaccess; } public EXPR GetObject() { return _obj; } public CType GetSourceType() { return _typeSrc; } public MemLookFlags GetFlags() { return _flags; } // Put all the types in a type array. public TypeArray GetAllTypes() { return GetSymbolLoader().getBSymmgr().AllocParams(_prgtype.Count, _prgtype.ToArray()); } /****************************************************************************** Reports errors. Only call this if FError() is true. ******************************************************************************/ public void ReportErrors() { Debug.Assert(FError()); // Report error. // NOTE: If the definition of FError changes, this code will need to change. Debug.Assert(!_swtFirst || _swtAmbig); if (_swtFirst) { // Ambiguous lookup. GetErrorContext().ErrorRef(ErrorCode.ERR_AmbigMember, _swtFirst, _swtAmbig); } else if (_swtInaccess) { if (!_swtInaccess.Sym.isUserCallable() && ((_flags & MemLookFlags.UserCallable) != 0)) GetErrorContext().Error(ErrorCode.ERR_CantCallSpecialMethod, _swtInaccess); else GetSemanticChecker().ReportAccessError(_swtInaccess, _symWhere, _typeQual); } else if ((_flags & MemLookFlags.Ctor) != 0) { if (_arity > 0) { GetErrorContext().Error(ErrorCode.ERR_BadCtorArgCount, _typeSrc.getAggregate(), _arity); } else { GetErrorContext().Error(ErrorCode.ERR_NoConstructors, _typeSrc.getAggregate()); } } else if ((_flags & MemLookFlags.Operator) != 0) { GetErrorContext().Error(ErrorCode.ERR_NoSuchMember, _typeSrc, _name); } else if ((_flags & MemLookFlags.Indexer) != 0) { GetErrorContext().Error(ErrorCode.ERR_BadIndexLHS, _typeSrc); } else if (_swtBad) { GetErrorContext().Error((_flags & MemLookFlags.MustBeInvocable) != 0 ? ErrorCode.ERR_NonInvocableMemberCalled : ErrorCode.ERR_CantCallSpecialMethod, _swtBad); } else if (_swtBogus) { ReportBogus(_swtBogus); } else if (_swtBadArity) { int cvar; switch (_swtBadArity.Sym.getKind()) { case SYMKIND.SK_MethodSymbol: Debug.Assert(_arity != 0); cvar = _swtBadArity.Sym.AsMethodSymbol().typeVars.size; GetErrorContext().ErrorRef(cvar > 0 ? ErrorCode.ERR_BadArity : ErrorCode.ERR_HasNoTypeVars, _swtBadArity, new ErrArgSymKind(_swtBadArity.Sym), cvar); break; case SYMKIND.SK_AggregateSymbol: cvar = _swtBadArity.Sym.AsAggregateSymbol().GetTypeVars().size; GetErrorContext().ErrorRef(cvar > 0 ? ErrorCode.ERR_BadArity : ErrorCode.ERR_HasNoTypeVars, _swtBadArity, new ErrArgSymKind(_swtBadArity.Sym), cvar); break; default: Debug.Assert(_arity != 0); ExpressionBinder.ReportTypeArgsNotAllowedError(GetSymbolLoader(), _arity, _swtBadArity, new ErrArgSymKind(_swtBadArity.Sym)); break; } } else { if ((_flags & MemLookFlags.ExtensionCall) != 0) { GetErrorContext().Error(ErrorCode.ERR_NoSuchMemberOrExtension, _typeSrc, _name); } else { GetErrorContext().Error(ErrorCode.ERR_NoSuchMember, _typeSrc, _name); } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System.Globalization { // // N.B.: // A lot of this code is directly from DateTime.cs. If you update that class, // update this one as well. // However, we still need these duplicated code because we will add era support // in this class. // // using System.Threading; using System; using System.Globalization; using System.Runtime.Serialization; using System.Diagnostics.Contracts; // This calendar recognizes two era values: // 0 CurrentEra (AD) // 1 BeforeCurrentEra (BC) [System.Runtime.InteropServices.ComVisible(true)] [Serializable] public class GregorianCalendar : Calendar { /* A.D. = anno Domini */ public const int ADEra = 1; internal const int DatePartYear = 0; internal const int DatePartDayOfYear = 1; internal const int DatePartMonth = 2; internal const int DatePartDay = 3; // // This is the max Gregorian year can be represented by DateTime class. The limitation // is derived from DateTime class. // internal const int MaxYear = 9999; internal GregorianCalendarTypes m_type; internal static readonly int[] DaysToMonth365 = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; internal static readonly int[] DaysToMonth366 = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }; private static volatile Calendar s_defaultInstance; #region Serialization [OnDeserialized] private void OnDeserialized(StreamingContext ctx) { if (m_type < GregorianCalendarTypes.Localized || m_type > GregorianCalendarTypes.TransliteratedFrench) { throw new SerializationException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Serialization_MemberOutOfRange"), "type", "GregorianCalendar")); } } #endregion Serialization [System.Runtime.InteropServices.ComVisible(false)] public override DateTime MinSupportedDateTime { get { return (DateTime.MinValue); } } [System.Runtime.InteropServices.ComVisible(false)] public override DateTime MaxSupportedDateTime { get { return (DateTime.MaxValue); } } // Return the type of the Gregorian calendar. // [System.Runtime.InteropServices.ComVisible(false)] public override CalendarAlgorithmType AlgorithmType { get { return CalendarAlgorithmType.SolarCalendar; } } /*=================================GetDefaultInstance========================== **Action: Internal method to provide a default intance of GregorianCalendar. Used by NLS+ implementation ** and other calendars. **Returns: **Arguments: **Exceptions: ============================================================================*/ internal static Calendar GetDefaultInstance() { if (s_defaultInstance == null) { s_defaultInstance = new GregorianCalendar(); } return (s_defaultInstance); } // Construct an instance of gregorian calendar. public GregorianCalendar() : this(GregorianCalendarTypes.Localized) { } public GregorianCalendar(GregorianCalendarTypes type) { if ((int)type < (int)GregorianCalendarTypes.Localized || (int)type > (int)GregorianCalendarTypes.TransliteratedFrench) { throw new ArgumentOutOfRangeException( "type", Environment.GetResourceString("ArgumentOutOfRange_Range", GregorianCalendarTypes.Localized, GregorianCalendarTypes.TransliteratedFrench)); } Contract.EndContractBlock(); this.m_type = type; } public virtual GregorianCalendarTypes CalendarType { get { return (m_type); } set { VerifyWritable(); switch (value) { case GregorianCalendarTypes.Localized: case GregorianCalendarTypes.USEnglish: case GregorianCalendarTypes.MiddleEastFrench: case GregorianCalendarTypes.Arabic: case GregorianCalendarTypes.TransliteratedEnglish: case GregorianCalendarTypes.TransliteratedFrench: m_type = value; break; default: throw new ArgumentOutOfRangeException("m_type", Environment.GetResourceString("ArgumentOutOfRange_Enum")); } } } internal override int ID { get { // By returning different ID for different variations of GregorianCalendar, // we can support the Transliterated Gregorian calendar. // DateTimeFormatInfo will use this ID to get formatting information about // the calendar. return ((int)m_type); } } // Returns a given date part of this DateTime. This method is used // to compute the year, day-of-year, month, or day part. internal virtual int GetDatePart(long ticks, int part) { // n = number of days since 1/1/0001 int n = (int)(ticks / TicksPerDay); // y400 = number of whole 400-year periods since 1/1/0001 int y400 = n / DaysPer400Years; // n = day number within 400-year period n -= y400 * DaysPer400Years; // y100 = number of whole 100-year periods within 400-year period int y100 = n / DaysPer100Years; // Last 100-year period has an extra day, so decrement result if 4 if (y100 == 4) y100 = 3; // n = day number within 100-year period n -= y100 * DaysPer100Years; // y4 = number of whole 4-year periods within 100-year period int y4 = n / DaysPer4Years; // n = day number within 4-year period n -= y4 * DaysPer4Years; // y1 = number of whole years within 4-year period int y1 = n / DaysPerYear; // Last year has an extra day, so decrement result if 4 if (y1 == 4) y1 = 3; // If year was requested, compute and return it if (part == DatePartYear) { return (y400 * 400 + y100 * 100 + y4 * 4 + y1 + 1); } // n = day number within year n -= y1 * DaysPerYear; // If day-of-year was requested, return it if (part == DatePartDayOfYear) { return (n + 1); } // Leap year calculation looks different from IsLeapYear since y1, y4, // and y100 are relative to year 1, not year 0 bool leapYear = (y1 == 3 && (y4 != 24 || y100 == 3)); int[] days = leapYear? DaysToMonth366: DaysToMonth365; // All months have less than 32 days, so n >> 5 is a good conservative // estimate for the month int m = n >> 5 + 1; // m = 1-based month number while (n >= days[m]) m++; // If month was requested, return it if (part == DatePartMonth) return (m); // Return 1-based day-of-month return (n - days[m - 1] + 1); } /*=================================GetAbsoluteDate========================== **Action: Gets the absolute date for the given Gregorian date. The absolute date means ** the number of days from January 1st, 1 A.D. **Returns: the absolute date **Arguments: ** year the Gregorian year ** month the Gregorian month ** day the day **Exceptions: ** ArgumentOutOfRangException if year, month, day value is valid. **Note: ** This is an internal method used by DateToTicks() and the calculations of Hijri and Hebrew calendars. ** Number of Days in Prior Years (both common and leap years) + ** Number of Days in Prior Months of Current Year + ** Number of Days in Current Month ** ============================================================================*/ internal static long GetAbsoluteDate(int year, int month, int day) { if (year >= 1 && year <= MaxYear && month >= 1 && month <= 12) { int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))) ? DaysToMonth366: DaysToMonth365; if (day >= 1 && (day <= days[month] - days[month - 1])) { int y = year - 1; int absoluteDate = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1; return (absoluteDate); } } throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadYearMonthDay")); } // Returns the tick count corresponding to the given year, month, and day. // Will check the if the parameters are valid. internal virtual long DateToTicks(int year, int month, int day) { return (GetAbsoluteDate(year, month, day)* TicksPerDay); } // Returns the DateTime resulting from adding the given number of // months to the specified DateTime. The result is computed by incrementing // (or decrementing) the year and month parts of the specified DateTime by // value months, and, if required, adjusting the day part of the // resulting date downwards to the last day of the resulting month in the // resulting year. The time-of-day part of the result is the same as the // time-of-day part of the specified DateTime. // // In more precise terms, considering the specified DateTime to be of the // form y / m / d + t, where y is the // year, m is the month, d is the day, and t is the // time-of-day, the result is y1 / m1 / d1 + t, // where y1 and m1 are computed by adding value months // to y and m, and d1 is the largest value less than // or equal to d that denotes a valid day in month m1 of year // y1. // public override DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException( "months", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), -120000, 120000)); } Contract.EndContractBlock(); int y = GetDatePart(time.Ticks, DatePartYear); int m = GetDatePart(time.Ticks, DatePartMonth); int d = GetDatePart(time.Ticks, DatePartDay); int i = m - 1 + months; if (i >= 0) { m = i % 12 + 1; y = y + i / 12; } else { m = 12 + (i + 1) % 12; y = y + (i - 11) / 12; } int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? DaysToMonth366: DaysToMonth365; int days = (daysArray[m] - daysArray[m - 1]); if (d > days) { d = days; } long ticks = DateToTicks(y, m, d) + time.Ticks % TicksPerDay; Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime); return (new DateTime(ticks)); } // Returns the DateTime resulting from adding the given number of // years to the specified DateTime. The result is computed by incrementing // (or decrementing) the year part of the specified DateTime by value // years. If the month and day of the specified DateTime is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of the specified DateTime. // public override DateTime AddYears(DateTime time, int years) { return (AddMonths(time, years * 12)); } // Returns the day-of-month part of the specified DateTime. The returned // value is an integer between 1 and 31. // public override int GetDayOfMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartDay)); } // Returns the day-of-week part of the specified DateTime. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public override DayOfWeek GetDayOfWeek(DateTime time) { return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7)); } // Returns the day-of-year part of the specified DateTime. The returned value // is an integer between 1 and 366. // public override int GetDayOfYear(DateTime time) { return (GetDatePart(time.Ticks, DatePartDayOfYear)); } // Returns the number of days in the month given by the year and // month arguments. // public override int GetDaysInMonth(int year, int month, int era) { if (era == CurrentEra || era == ADEra) { if (year < 1 || year > MaxYear) { throw new ArgumentOutOfRangeException("year", Environment.GetResourceString("ArgumentOutOfRange_Range", 1, MaxYear)); } if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Month")); } int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366: DaysToMonth365); return (days[month] - days[month - 1]); } throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } // Returns the number of days in the year given by the year argument for the current era. // public override int GetDaysInYear(int year, int era) { if (era == CurrentEra || era == ADEra) { if (year >= 1 && year <= MaxYear) { return ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 366:365); } throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, MaxYear)); } throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } // Returns the era for the specified DateTime value. public override int GetEra(DateTime time) { return (ADEra); } public override int[] Eras { get { return (new int[] {ADEra} ); } } // Returns the month part of the specified DateTime. The returned value is an // integer between 1 and 12. // public override int GetMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartMonth)); } // Returns the number of months in the specified year and era. public override int GetMonthsInYear(int year, int era) { if (era == CurrentEra || era == ADEra) { if (year >= 1 && year <= MaxYear) { return (12); } throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, MaxYear)); } throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } // Returns the year part of the specified DateTime. The returned value is an // integer between 1 and 9999. // public override int GetYear(DateTime time) { return (GetDatePart(time.Ticks, DatePartYear)); } // Checks whether a given day in the specified era is a leap day. This method returns true if // the date is a leap day, or false if not. // public override bool IsLeapDay(int year, int month, int day, int era) { if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Range", 1, 12)); } Contract.EndContractBlock(); if (era != CurrentEra && era != ADEra) { throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } if (year < 1 || year > MaxYear) { throw new ArgumentOutOfRangeException( "year", Environment.GetResourceString("ArgumentOutOfRange_Range", 1, MaxYear)); } if (day < 1 || day > GetDaysInMonth(year, month)) { throw new ArgumentOutOfRangeException("day", Environment.GetResourceString("ArgumentOutOfRange_Range", 1, GetDaysInMonth(year, month))); } if (!IsLeapYear(year)) { return (false); } if (month == 2 && day == 29) { return (true); } return (false); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // [System.Runtime.InteropServices.ComVisible(false)] public override int GetLeapMonth(int year, int era) { if (era != CurrentEra && era != ADEra) { throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } if (year < 1 || year > MaxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, MaxYear)); } Contract.EndContractBlock(); return (0); } // Checks whether a given month in the specified era is a leap month. This method returns true if // month is a leap month, or false if not. // public override bool IsLeapMonth(int year, int month, int era) { if (era != CurrentEra && era != ADEra) { throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } if (year < 1 || year > MaxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, MaxYear)); } if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Range", 1, 12)); } Contract.EndContractBlock(); return (false); } // Checks whether a given year in the specified era is a leap year. This method returns true if // year is a leap year, or false if not. // public override bool IsLeapYear(int year, int era) { if (era == CurrentEra || era == ADEra) { if (year >= 1 && year <= MaxYear) { return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); } throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, MaxYear)); } throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { if (era == CurrentEra || era == ADEra) { return new DateTime(year, month, day, hour, minute, second, millisecond); } throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } internal override Boolean TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result) { if (era == CurrentEra || era == ADEra) { return DateTime.TryCreate(year, month, day, hour, minute, second, millisecond, out result); } result = DateTime.MinValue; return false; } private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 2029; public override int TwoDigitYearMax { get { if (twoDigitYearMax == -1) { twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX); } return (twoDigitYearMax); } set { VerifyWritable(); if (value < 99 || value > MaxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 99, MaxYear)); } twoDigitYearMax = value; } } public override int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException("year", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); if (year > MaxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, MaxYear)); } return (base.ToFourDigitYear(year)); } } }
// ReSharper disable All using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Controllers; using Frapid.ApplicationState.Cache; using Frapid.ApplicationState.Models; using Frapid.DataAccess; using Frapid.DataAccess.Models; using Frapid.Framework; using Frapid.Framework.Extensions; using Frapid.WebApi; using Frapid.Config.Entities; using Frapid.Config.DataAccess; namespace Frapid.Config.Api { /// <summary> /// Provides a direct HTTP access to execute the function GetCustomFieldDefinition. /// </summary> [RoutePrefix("api/v1.0/config/procedures/get-custom-field-definition")] public class GetCustomFieldDefinitionController : FrapidApiController { /// <summary> /// The GetCustomFieldDefinition repository. /// </summary> private IGetCustomFieldDefinitionRepository repository; public class Annotation { public string TableName { get; set; } public string ResourceId { get; set; } } public GetCustomFieldDefinitionController() { } public GetCustomFieldDefinitionController(IGetCustomFieldDefinitionRepository repository) { this.repository = repository; } protected override void Initialize(HttpControllerContext context) { base.Initialize(context); if (this.repository == null) { this.repository = new GetCustomFieldDefinitionProcedure { _Catalog = this.MetaUser.Catalog, _LoginId = this.MetaUser.LoginId, _UserId = this.MetaUser.UserId }; } } /// <summary> /// Creates meta information of "get custom field definition" annotation. /// </summary> /// <returns>Returns the "get custom field definition" annotation meta information to perform CRUD operation.</returns> [AcceptVerbs("GET", "HEAD")] [Route("annotation")] [Route("~/api/config/procedures/get-custom-field-definition/annotation")] [RestAuthorize] public EntityView GetAnnotation() { return new EntityView { Columns = new List<EntityColumn>() { new EntityColumn { ColumnName = "_table_name", PropertyName = "TableName", DataType = "string", DbDataType = "text", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "_resource_id", PropertyName = "ResourceId", DataType = "string", DbDataType = "text", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 } } }; } /// <summary> /// Creates meta information of "get custom field definition" entity. /// </summary> /// <returns>Returns the "get custom field definition" meta information to perform CRUD operation.</returns> [AcceptVerbs("GET", "HEAD")] [Route("meta")] [Route("~/api/config/procedures/get-custom-field-definition/meta")] [RestAuthorize] public EntityView GetEntityView() { return new EntityView { Columns = new List<EntityColumn>() { new EntityColumn { ColumnName = "table_name", PropertyName = "TableName", DataType = "string", DbDataType = "character varying", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "key_name", PropertyName = "KeyName", DataType = "string", DbDataType = "character varying", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "custom_field_setup_id", PropertyName = "CustomFieldSetupId", DataType = "int", DbDataType = "integer", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "form_name", PropertyName = "FormName", DataType = "string", DbDataType = "character varying", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "field_order", PropertyName = "FieldOrder", DataType = "int", DbDataType = "integer", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "field_name", PropertyName = "FieldName", DataType = "string", DbDataType = "character varying", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "field_label", PropertyName = "FieldLabel", DataType = "string", DbDataType = "character varying", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "description", PropertyName = "Description", DataType = "string", DbDataType = "text", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "data_type", PropertyName = "DataType", DataType = "string", DbDataType = "character varying", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "is_number", PropertyName = "IsNumber", DataType = "bool", DbDataType = "boolean", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "is_date", PropertyName = "IsDate", DataType = "bool", DbDataType = "boolean", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "is_boolean", PropertyName = "IsBoolean", DataType = "bool", DbDataType = "boolean", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "is_long_text", PropertyName = "IsLongText", DataType = "bool", DbDataType = "boolean", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "resource_id", PropertyName = "ResourceId", DataType = "string", DbDataType = "text", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "value", PropertyName = "Value", DataType = "string", DbDataType = "text", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 } } }; } [AcceptVerbs("POST")] [Route("execute")] [Route("~/api/config/procedures/get-custom-field-definition/execute")] [RestAuthorize] public IEnumerable<DbGetCustomFieldDefinitionResult> Execute([FromBody] Annotation annotation) { try { this.repository.TableName = annotation.TableName; this.repository.ResourceId = annotation.ResourceId; return this.repository.Execute(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } } }
/*``The contents of this file are subject to the Erlang Public License, * Version 1.1, (the "License"); you may not use this file except in * compliance with the License. You should have received a copy of the * Erlang Public License along with this software. If not, it can be * retrieved via the world wide web at http://www.erlang.org/. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See * the License for the specific language governing rights and limitations * under the License. * * The Initial Developer of the Original Code is Ericsson Utvecklings AB. * Portions created by Ericsson are Copyright 1999, Ericsson Utvecklings * AB. All Rights Reserved.'' * * Converted from Java to C# by Vlad Dumitrescu ([email protected]) */ namespace Otp.Erlang { using System; /* * Provides a C# representation of Erlang lists. Lists are created * from zero or more arbitrary Erlang terms. * * <p> The arity of the list is the number of elements it contains. **/ [Serializable] public class List:Erlang.Object { private Object[] elems = null; // todo: use a linked structure to make a proper list with append, // car, cdr etc methods. The current representation is essensially the // same as for tuples except that empty lists are allowed. // private Object car = null; // private Object cdr = null; // int arity; /* * Create an empty list. **/ public List() { this.elems = null; // empty list } /* * Create a list of characters. * * @param str the characters from which to create the list. * public List(System.String str) { this.elems = new Object[] { new Erlang.String(str) }; } * Create a list containing one element. * * @param elem the elememet to make the list from. * public List(Object elem) { this.elems = new Object[1]; elems[0] = elem; } */ /* * Create a list from an array of arbitrary Erlang terms. * * @param elems the array of terms from which to create the list. * @param count the number of terms to insert. */ public List(Object[] elems): this(elems, 0, elems.Length) { } /* * Create a list from an array of arbitrary Erlang terms. * * @param elems the array of terms from which to create the list. * @param start the offset of the first term to insert. * @param count the number of terms to insert. */ public List(Object[] elems, int start, int count) { if ((elems != null) && (count > 0)) { this.elems = new Object[count]; Array.Copy(elems, 0, this.elems, start, count); } } /* * Create a list from an array of arbitrary Erlang terms. * * @param elems the array of terms from which to create the list. **/ public List(params System.Object[] elems) { if ((elems != null) && (elems.Length > 0)) { this.elems = new Object[elems.Length]; for (int i=0; i < elems.Length; i++) { System.Object o = elems[i]; if (o is int) this.elems[i] = new Int((int)o); else if (o is string) this.elems[i] = new String((string)o); else if (o is float) this.elems[i] = new Double((float)o); else if (o is double) this.elems[i] = new Double((double)o); else if (o is Erlang.Object) this.elems[i] = (o as Erlang.Object); //else if (o is BigInteger) this.elems[i] = (BigInteger)o; else if (o is uint) this.elems[i] = new UInt((int)o); else if (o is short) this.elems[i] = new Short((short)o); else if (o is ushort) this.elems[i] = new UShort((short)o); else throw new System.ArgumentException("Unknown type of element[" + i + "]: " + o.GetType().ToString()); } } } /* * Create a list from a stream containing an list encoded in Erlang * external format. * * @param buf the stream containing the encoded list. * * @exception DecodeException if the buffer does not * contain a valid external representation of an Erlang list. **/ public List(OtpInputStream buf) { this.elems = null; int arity = buf.read_list_head(); if (arity > 0) { this.elems = new Object[arity]; for (int i = 0; i < arity; i++) { elems[i] = buf.read_any(); } /*discard the terminating nil (empty list) */ buf.read_nil(); } } /* * Get the arity of the list. * * @return the number of elements contained in the list. **/ public int arity() { if (elems == null) return 0; else return elems.Length; } /* * Get the specified element from the list. * * @param i the index of the requested element. List elements are * numbered as array elements, starting at 0. * * @return the requested element, of null if i is not a valid * element index. **/ public Object elementAt(int i) { if ((i >= arity()) || (i < 0)) return null; return elems[i]; } /* * Get all the elements from the list as an array. * * @return an array containing all of the list's elements. **/ public Object[] elements() { if (arity() == 0) return null; else { Object[] res = new Object[arity()]; Array.Copy(this.elems, 0, res, 0, res.Length); return res; } } public Object this[int index] { get { return elementAt(index); } set { this.elems[index] = value; } } public int Length { get { return this.elems.Length; } } /* * Get the string representation of the list. * * @return the string representation of the list. **/ public override System.String ToString() { System.Text.StringBuilder s = new System.Text.StringBuilder(); int _arity = arity(); s.Append("["); for (int i = 0; i < _arity; i++) { if (i > 0) s.Append(","); s.Append(elems[i].ToString()); } s.Append("]"); return s.ToString(); } /* * Convert this list to the equivalent Erlang external * representation. Note that this method never encodes lists as * strings, even when it is possible to do so. * * @param buf An output stream to which the encoded list should be * written. * **/ public override void encode(OtpOutputStream buf) { int _arity = arity(); if (_arity > 0) { buf.write_list_head(_arity); for (int i = 0; i < _arity; i++) { buf.write_any(elems[i]); } } buf.write_nil(); } /* * Determine if two lists are equal. Lists are equal if they have * the same arity and all of the elements are equal. * * @param o the list to compare to. * * @return true if the lists have the same arity and all the * elements are equal. **/ public override bool Equals(System.Object o) { if (!(o is List)) return false; List l = (List) o; int a = this.arity(); if (a != l.arity()) return false; for (int i = 0; i < a; i++) { if (!this.elems[i].Equals(l.elems[i])) return false; // early exit } return true; } public override int GetHashCode() { return 1; } public override System.Object clone() { List newList = (List) (base.clone()); newList.elems = new Object[elems.Length]; elems.CopyTo(newList.elems, 0); return newList; } } }
// 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 NLog; using NLog.Config; using NLog.Targets; using NLog.Targets.Wrappers; using System; using System.Diagnostics; namespace YetiCommon.Logging { /// <summary> /// Manages the global NLog configuration. /// </summary> public class YetiLog { // We need to use the Component Logging pattern because we are running alongside other // Visual Studio extensions (aka components) that may also be using NLog. // https://github.com/NLog/NLog/wiki/Configure-component-logging private static LogFactory logFactory = null; static NLogTraceListener nlogTracelistener; const string GeneralFileTargetName = "file-general"; const string TraceFileTargetName = "file-trace"; const string TraceLoggerPrefix = "Trace"; const string CallSequenceTargetName = "file-call-sequence"; const string CallSequenceLoggerSuffix = "CallSequenceDiagram"; public static bool IsInitialized => logFactory != null; /// <summary> /// Performs one-time setup for NLog configuration. /// This configuration is shared by all VSI components. /// </summary> /// <param name="appName">Log file name prefix</param> /// <param name="logDateTime">Timestamp used as log file name suffix</param> /// <exception cref="InvalidOperationException"> /// Thrown when this has already been initialized. /// </exception> public static void Initialize(string appName, DateTime logDateTime) { if (string.IsNullOrEmpty(appName)) { throw new ArgumentException("null or empty", nameof(appName)); } if (appName.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) >= 0) { throw new ArgumentException("contains invalid file name chars", nameof(appName)); } if (logFactory != null) { throw new InvalidOperationException( nameof(YetiLog) + " has already been initialized."); } // Setup NLog configuration. var config = new LoggingConfiguration(); string time = ToLogFileDateTime(DateTime.Now); SetupGeneralLogging(appName, time, ref config); SetupCallSequenceLogging(appName, time, ref config); SetupTraceLogging(appName, time, ref config); logFactory = new LogFactory(config); // Send System.Diagnotics.Debug and System.Diagnostics.Trace to NLog. nlogTracelistener = new NLogTraceListener(); nlogTracelistener.LogFactory = logFactory; nlogTracelistener.DisableFlush = true; Trace.Listeners.Add(nlogTracelistener); } /// <summary> /// Unintialize the underlying NLog LogFactory forcing data to be flushed. /// </summary> /// <exception cref="InvalidOperationException"> /// Thrown when this hasn't been initialized. /// </exception> public static void Uninitialize() { if (logFactory == null) { throw new InvalidOperationException( nameof(YetiLog) + " is not in an initialized state."); } // Make sure that the configuration is properly closed when the process terminates or // you may lose some log output // Reference: https://github.com/NLog/NLog/wiki/Configure-component-logging logFactory.Configuration = null; logFactory = null; Trace.Listeners.Remove(nlogTracelistener); } /// <summary> /// For general logging, create a file target with a fixed basename, and enable log /// rotation for this target. Accepts events from all loggers at Debug level and higher. /// </summary> /// <param name="appName">log file prefix unique to this executable</param> /// <param name="time">time string to differentiate instances</param> private static void SetupGeneralLogging(string appName, string time, ref LoggingConfiguration config) { var fileTarget = CreateBaseFileTarget(appName, time); fileTarget.Layout = "${time} ${logger:whenEmpty=${callSite}} ${message}"; fileTarget.ArchiveNumbering = ArchiveNumberingMode.Sequence; fileTarget.ArchiveAboveSize = 10 * 1024 * 1024; fileTarget.ArchiveEvery = FileArchivePeriod.Day; config.AddTarget(GeneralFileTargetName, fileTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, fileTarget)); } /// <summary> /// For call sequence logging, create a file target with a fixed basename, and enable log /// rotation for this target. Accepts events from loggers at Trace level. /// </summary> /// <param name="appName">log file prefix unique to this executable</param> /// <param name="time">time string to differentiate instances</param> private static void SetupCallSequenceLogging(string appName, string time, ref LoggingConfiguration config) { var fileTarget = CreateBaseFileTarget(appName, time, CallSequenceLoggerSuffix); fileTarget.Layout = "${message}"; fileTarget.ArchiveNumbering = ArchiveNumberingMode.Sequence; fileTarget.ArchiveAboveSize = 10 * 1024 * 1024; fileTarget.ArchiveEvery = FileArchivePeriod.Day; config.AddTarget(CallSequenceTargetName, fileTarget); config.LoggingRules.Add(new LoggingRule( CallSequenceLoggerSuffix, LogLevel.Trace, LogLevel.Trace, fileTarget)); } /// <summary> /// For trace logging, create a file target keyed by the shortName (suffix) of the /// logger name. This enables us to have separate tracing sessions, potentially /// with multiple sessions running in parallel. Only accepts events from loggers /// with the |TraceLoggerPrefix| in the name and at Trace level. /// </summary> /// <param name="appName">log file prefix unique to this executable</param> /// <param name="time">time string to differentiate instances</param> private static void SetupTraceLogging(string appName, string time, ref LoggingConfiguration config) { var traceFileTarget = CreateBaseFileTarget($"{appName}.Trace", time, "${logger:shortName=true}"); // TODO: look into deferring message-formatting for better performance traceFileTarget.Layout = "${message}"; // Further performance optimizations. Keep files open for 30s at a time. // The timeout ensures that files for completed debug sessions are closed. traceFileTarget.KeepFileOpen = true; traceFileTarget.OpenFileCacheTimeout = 30; // Use async writes for trace logging to reduce overhead at the trace site. var asyncWrapper = new AsyncTargetWrapper(traceFileTarget); asyncWrapper.OverflowAction = AsyncTargetWrapperOverflowAction.Grow; config.AddTarget(TraceFileTargetName, traceFileTarget); config.LoggingRules.Add( new LoggingRule($"{TraceLoggerPrefix}.*", LogLevel.Trace, LogLevel.Trace, asyncWrapper)); } /// <summary> /// Creates a file target for log events using the appName prefix, followed by the suffixes /// joined with dots. Logs are written to the GGP SDK logs directory. /// </summary> /// <remarks>Log file names must be unique to this instance of this executable.</remarks> /// <param name="appName">prefix to uniquely identify this executable</param> /// <param name="suffixes">one or more strings to uniquely identify this log file</param> private static FileTarget CreateBaseFileTarget(string appName, params string[] suffixes) { if (suffixes.Length < 1) { throw new ArgumentException("need at least 1 suffix", nameof(suffixes)); } var suffix = string.Join(".", suffixes); var logPath = SDKUtil.GetLoggingPath(); var fileTarget = new FileTarget(); fileTarget.FileName = string.Format("{0}/{1}.{2}.log", logPath, appName, suffix); // Set up an archive file name regardless if archiving will be used or not. // https://github.com/nlog/NLog/wiki/File-target#archival-options // Note that {{#}} gets converted to {#} in the formatted string, which is then // replaced by the archive number. fileTarget.ArchiveFileName = string.Format("{0}/{1}.{2}.{{#}}.log", logPath, appName, suffix); // Disable concurrent writes because we always use a unique file for each process. fileTarget.ConcurrentWrites = false; return fileTarget; } /// <summary> /// Returns the current general log file path. /// </summary> /// <exception cref="InvalidOperationException"> /// Thrown when this hasn't been initialized. /// </exception> public static string CurrentLogFile { get { if (logFactory == null) { throw new InvalidOperationException( nameof(YetiLog) + " has not been initialized."); } var target = (FileTarget)logFactory.Configuration.FindTargetByName(GeneralFileTargetName); return target.FileName.Render(LogEventInfo.CreateNullEvent()); } } /// <summary> /// Converts |dateTime| to a format suitable for use in log file names with precision in /// seconds. /// </summary> public static string ToLogFileDateTime(DateTime dateTime) => dateTime.ToString("yyyyMMdd-HHmmss"); /// <summary> /// Returns a logger to use for debug trace events associated with a specific key. /// All traces from the same key will go to the same log file. The log file name will /// contain the provided key. /// </summary> /// <param name="key">Log file name suffix; cannot contain dots</param> /// <exception cref="InvalidOperationException"> /// Thrown when this hasn't been initialized. /// </exception> public static ILogger GetTraceLogger(string key) { if (string.IsNullOrEmpty(key)) { throw new ArgumentException("null or empty", nameof(key)); } if (key.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) >= 0) { throw new ArgumentException("contains invalid file name chars", nameof(key)); } if (logFactory == null) { throw new InvalidOperationException(nameof(YetiLog) + " has not been initialized."); } // The logger short name (suffix) is defined as the part after the last dot, so we // can't be introducing any dots into the key itself. if (key.IndexOf('.') >= 0) { throw new ArgumentException("contains a dot", nameof(key)); } // The key becomes the shortname of the logger, which is part of the log file name. return logFactory.GetLogger($"{TraceLoggerPrefix}.{key}"); } /// <summary> /// Returns a logger to use for call sequence traces. /// </summary> /// <exception cref="InvalidOperationException"> /// Thrown when this hasn't been initialized. /// </exception> public static ILogger GetCallSequenceLogger() { if (logFactory == null) { throw new InvalidOperationException(nameof(YetiLog) + " has not been initialized."); } return logFactory.GetLogger(CallSequenceLoggerSuffix); } /// <summary> /// Gets the specified named logger. /// </summary> /// <exception cref="ArgumentNullException"> /// Thrown if name is null. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown when this hasn't been initialized. /// </exception> public static ILogger GetLogger(string name) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (logFactory == null) { throw new InvalidOperationException(nameof(YetiLog) + " has not been initialized."); } return logFactory.GetLogger(name); } static Grpc.Core.Logging.ILogger originalGrpcLogger = null; /// <summary> /// Toggles Grpc logging capture. /// /// Logs are captured to the YetiVSI log files. /// </summary> public static void ToggleGrpcLogging(bool enabled) { if (enabled && originalGrpcLogger == null) { originalGrpcLogger = Grpc.Core.GrpcEnvironment.Logger; Trace.WriteLine($"Enabling GrpcLogging."); Grpc.Core.GrpcEnvironment.SetLogger(new Grpc.Core.Logging.LogLevelFilterLogger( new Cloud.GrpcLogger(), Grpc.Core.Logging.LogLevel.Debug)); } else if (!enabled && originalGrpcLogger != null) { Trace.WriteLine($"Disabling GrpcLogging."); // Calling SetLogger(null) will raise an exception. Grpc.Core.GrpcEnvironment.SetLogger(originalGrpcLogger); originalGrpcLogger = null; } else { Trace.WriteLine($"WARNING: Could not toggle Grpc Logging. " + $"Cannot set enabled={enabled} when originalGrpcLogger={originalGrpcLogger}"); } } } }
/* * REST API Documentation for the MOTI Hired Equipment Tracking System (HETS) Application * * The Hired Equipment Program is for owners/operators who have a dump truck, bulldozer, backhoe or other piece of equipment they want to hire out to the transportation ministry for day labour and emergency projects. The Hired Equipment Program distributes available work to local equipment owners. The program is based on seniority and is designed to deliver work to registered users fairly and efficiently through the development of local area call-out lists. * * OpenAPI spec version: v1 * * */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; using HETSAPI.Models; namespace HETSAPI.Models { /// <summary> /// /// </summary> public partial class ImportMap : AuditableEntity, IEquatable<ImportMap> { /// <summary> /// Default constructor, required by entity framework /// </summary> public ImportMap() { this.Id = 0; } /// <summary> /// Initializes a new instance of the <see cref="ImportMap" /> class. /// </summary> /// <param name="Id">A system generated unique identifier for the ImportMap (required).</param> /// <param name="OldTable">Table name in old system (required).</param> /// <param name="NewTable">Table name in new system. (required).</param> /// <param name="OldKey">Old primary key for record (required).</param> /// <param name="NewKey">New primary key for record (required).</param> public ImportMap(int Id, string OldTable, string NewTable, string OldKey, int NewKey) { this.Id = Id; this.OldTable = OldTable; this.NewTable = NewTable; this.OldKey = OldKey; this.NewKey = NewKey; } /// <summary> /// A system generated unique identifier for the ImportMap /// </summary> /// <value>A system generated unique identifier for the ImportMap</value> [MetaDataExtension (Description = "A system generated unique identifier for the ImportMap")] public int Id { get; set; } /// <summary> /// Table name in old system /// </summary> /// <value>Table name in old system</value> [MetaDataExtension (Description = "Table name in old system")] public string OldTable { get; set; } /// <summary> /// Table name in new system. /// </summary> /// <value>Table name in new system.</value> [MetaDataExtension (Description = "Table name in new system.")] public string NewTable { get; set; } /// <summary> /// Old primary key for record /// </summary> /// <value>Old primary key for record</value> [MetaDataExtension (Description = "Old primary key for record")] [MaxLength(250)] public string OldKey { get; set; } /// <summary> /// New primary key for record /// </summary> /// <value>New primary key for record</value> [MetaDataExtension (Description = "New primary key for record")] public int NewKey { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ImportMap {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" OldTable: ").Append(OldTable).Append("\n"); sb.Append(" NewTable: ").Append(NewTable).Append("\n"); sb.Append(" OldKey: ").Append(OldKey).Append("\n"); sb.Append(" NewKey: ").Append(NewKey).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != GetType()) { return false; } return Equals((ImportMap)obj); } /// <summary> /// Returns true if ImportMap instances are equal /// </summary> /// <param name="other">Instance of ImportMap to be compared</param> /// <returns>Boolean</returns> public bool Equals(ImportMap other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return ( this.Id == other.Id || this.Id.Equals(other.Id) ) && ( this.OldTable == other.OldTable || this.OldTable != null && this.OldTable.Equals(other.OldTable) ) && ( this.NewTable == other.NewTable || this.NewTable != null && this.NewTable.Equals(other.NewTable) ) && ( this.OldKey == other.OldKey || this.OldKey != null && this.OldKey.Equals(other.OldKey) ) && ( this.NewKey == other.NewKey || this.NewKey.Equals(other.NewKey) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks hash = hash * 59 + this.Id.GetHashCode(); if (this.OldTable != null) { hash = hash * 59 + this.OldTable.GetHashCode(); } if (this.NewTable != null) { hash = hash * 59 + this.NewTable.GetHashCode(); } if (this.OldKey != null) { hash = hash * 59 + this.OldKey.GetHashCode(); } hash = hash * 59 + this.NewKey.GetHashCode(); return hash; } } #region Operators /// <summary> /// Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator ==(ImportMap left, ImportMap right) { return Equals(left, right); } /// <summary> /// Not Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator !=(ImportMap left, ImportMap right) { return !Equals(left, right); } #endregion Operators } }
// // Author: // Jb Evain ([email protected]) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using Mono.Cecil.Cil; using Mono.Collections.Generic; namespace Mono.Cecil.Rocks { #if INSIDE_ROCKS public #endif interface IILVisitor { void OnInlineNone (OpCode opcode); void OnInlineSByte (OpCode opcode, sbyte value); void OnInlineByte (OpCode opcode, byte value); void OnInlineInt32 (OpCode opcode, int value); void OnInlineInt64 (OpCode opcode, long value); void OnInlineSingle (OpCode opcode, float value); void OnInlineDouble (OpCode opcode, double value); void OnInlineString (OpCode opcode, string value); void OnInlineBranch (OpCode opcode, int offset); void OnInlineSwitch (OpCode opcode, int [] offsets); void OnInlineVariable (OpCode opcode, VariableDefinition variable); void OnInlineArgument (OpCode opcode, ParameterDefinition parameter); void OnInlineSignature (OpCode opcode, CallSite callSite); void OnInlineType (OpCode opcode, TypeReference type); void OnInlineField (OpCode opcode, FieldReference field); void OnInlineMethod (OpCode opcode, MethodReference method); } #if INSIDE_ROCKS public #endif static class ILParser { class ParseContext { public CodeReader Code { get; set; } public int Position { get; set; } public MetadataReader Metadata { get; set; } public Collection<VariableDefinition> Variables { get; set; } public IILVisitor Visitor { get; set; } } public static void Parse (MethodDefinition method, IILVisitor visitor) { if (method == null) throw new ArgumentNullException ("method"); if (visitor == null) throw new ArgumentNullException ("visitor"); if (!method.HasBody || !method.HasImage) throw new ArgumentException (); method.Module.Read (method, (m, _) => { ParseMethod (m, visitor); return true; }); } static void ParseMethod (MethodDefinition method, IILVisitor visitor) { var context = CreateContext (method, visitor); var code = context.Code; var flags = code.ReadByte (); switch (flags & 0x3) { case 0x2: // tiny int code_size = flags >> 2; ParseCode (code_size, context); break; case 0x3: // fat code.Advance (-1); ParseFatMethod (context); break; default: throw new NotSupportedException (); } code.MoveBackTo (context.Position); } static ParseContext CreateContext (MethodDefinition method, IILVisitor visitor) { var code = method.Module.Read (method, (_, reader) => reader.code); var position = code.MoveTo (method); return new ParseContext { Code = code, Position = position, Metadata = code.reader, Visitor = visitor, }; } static void ParseFatMethod (ParseContext context) { var code = context.Code; code.Advance (4); var code_size = code.ReadInt32 (); var local_var_token = code.ReadToken (); if (local_var_token != MetadataToken.Zero) context.Variables = code.ReadVariables (local_var_token); ParseCode (code_size, context); } static void ParseCode (int code_size, ParseContext context) { var code = context.Code; var metadata = context.Metadata; var visitor = context.Visitor; var start = code.Position; var end = start + code_size; while (code.Position < end) { var il_opcode = code.ReadByte (); var opcode = il_opcode != 0xfe ? OpCodes.OneByteOpCode [il_opcode] : OpCodes.TwoBytesOpCode [code.ReadByte ()]; switch (opcode.OperandType) { case OperandType.InlineNone: visitor.OnInlineNone (opcode); break; case OperandType.InlineSwitch: var length = code.ReadInt32 (); var branches = new int [length]; for (int i = 0; i < length; i++) branches [i] = code.ReadInt32 (); visitor.OnInlineSwitch (opcode, branches); break; case OperandType.ShortInlineBrTarget: visitor.OnInlineBranch (opcode, code.ReadSByte ()); break; case OperandType.InlineBrTarget: visitor.OnInlineBranch (opcode, code.ReadInt32 ()); break; case OperandType.ShortInlineI: if (opcode == OpCodes.Ldc_I4_S) visitor.OnInlineSByte (opcode, code.ReadSByte ()); else visitor.OnInlineByte (opcode, code.ReadByte ()); break; case OperandType.InlineI: visitor.OnInlineInt32 (opcode, code.ReadInt32 ()); break; case OperandType.InlineI8: visitor.OnInlineInt64 (opcode, code.ReadInt64 ()); break; case OperandType.ShortInlineR: visitor.OnInlineSingle (opcode, code.ReadSingle ()); break; case OperandType.InlineR: visitor.OnInlineDouble (opcode, code.ReadDouble ()); break; case OperandType.InlineSig: visitor.OnInlineSignature (opcode, code.GetCallSite (code.ReadToken ())); break; case OperandType.InlineString: visitor.OnInlineString (opcode, code.GetString (code.ReadToken ())); break; case OperandType.ShortInlineArg: visitor.OnInlineArgument (opcode, code.GetParameter (code.ReadByte ())); break; case OperandType.InlineArg: visitor.OnInlineArgument (opcode, code.GetParameter (code.ReadInt16 ())); break; case OperandType.ShortInlineVar: visitor.OnInlineVariable (opcode, GetVariable (context, code.ReadByte ())); break; case OperandType.InlineVar: visitor.OnInlineVariable (opcode, GetVariable (context, code.ReadInt16 ())); break; case OperandType.InlineTok: case OperandType.InlineField: case OperandType.InlineMethod: case OperandType.InlineType: var member = metadata.LookupToken (code.ReadToken ()); switch (member.MetadataToken.TokenType) { case TokenType.TypeDef: case TokenType.TypeRef: case TokenType.TypeSpec: visitor.OnInlineType (opcode, (TypeReference) member); break; case TokenType.Method: case TokenType.MethodSpec: visitor.OnInlineMethod (opcode, (MethodReference) member); break; case TokenType.Field: visitor.OnInlineField (opcode, (FieldReference) member); break; case TokenType.MemberRef: var field_ref = member as FieldReference; if (field_ref != null) { visitor.OnInlineField (opcode, field_ref); break; } var method_ref = member as MethodReference; if (method_ref != null) { visitor.OnInlineMethod (opcode, method_ref); break; } throw new InvalidOperationException (); } break; } } } static VariableDefinition GetVariable (ParseContext context, int index) { return context.Variables [index]; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Diagnostics; using System.Xml.Schema; using System.Collections; using System.Threading.Tasks; namespace System.Xml { /// <summary> /// Implementations of XmlRawWriter are intended to be wrapped by the XmlWellFormedWriter. The /// well-formed writer performs many checks in behalf of the raw writer, and keeps state that the /// raw writer otherwise would have to keep. Therefore, the well-formed writer will call the /// XmlRawWriter using the following rules, in order to make raw writers easier to implement: /// /// 1. The well-formed writer keeps a stack of element names, and always calls /// WriteEndElement(string, string, string) instead of WriteEndElement(). /// 2. The well-formed writer tracks namespaces, and will pass himself in via the /// WellformedWriter property. It is used in the XmlRawWriter's implementation of IXmlNamespaceResolver. /// Thus, LookupPrefix does not have to be implemented. /// 3. The well-formed writer tracks write states, so the raw writer doesn't need to. /// 4. The well-formed writer will always call StartElementContent. /// 5. The well-formed writer will always call WriteNamespaceDeclaration for namespace nodes, /// rather than calling WriteStartAttribute(). If the writer is supporting namespace declarations in chunks /// (SupportsNamespaceDeclarationInChunks is true), the XmlWellFormedWriter will call WriteStartNamespaceDeclaration, /// then any method that can be used to write out a value of an attribute (WriteString, WriteChars, WriteRaw, WriteCharEntity...) /// and then WriteEndNamespaceDeclaration - instead of just a single WriteNamespaceDeclaration call. This feature will be /// supported by raw writers serializing to text that wish to preserve the attribute value escaping etc. /// 6. The well-formed writer guarantees a well-formed document, including correct call sequences, /// correct namespaces, and correct document rule enforcement. /// 7. All element and attribute names will be fully resolved and validated. Null will never be /// passed for any of the name parts. /// 8. The well-formed writer keeps track of xml:space and xml:lang. /// 9. The well-formed writer verifies NmToken, Name, and QName values and calls WriteString(). /// </summary> internal abstract partial class XmlRawWriter : XmlWriter { // // XmlWriter implementation // // Raw writers do not have to track whether this is a well-formed document. public override Task WriteStartDocumentAsync() { throw new InvalidOperationException(SR.Xml_InvalidOperation); } public override Task WriteStartDocumentAsync(bool standalone) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } public override Task WriteEndDocumentAsync() { throw new InvalidOperationException(SR.Xml_InvalidOperation); } public override Task WriteDocTypeAsync(string name, string pubid, string sysid, string subset) { return Task.CompletedTask; } // Raw writers do not have to keep a stack of element names. public override Task WriteEndElementAsync() { throw new InvalidOperationException(SR.Xml_InvalidOperation); } // Raw writers do not have to keep a stack of element names. public override Task WriteFullEndElementAsync() { throw new InvalidOperationException(SR.Xml_InvalidOperation); } // By default, convert base64 value to string and call WriteString. public override Task WriteBase64Async(byte[] buffer, int index, int count) { if (base64Encoder == null) { base64Encoder = new XmlRawWriterBase64Encoder(this); } // Encode will call WriteRaw to write out the encoded characters return base64Encoder.EncodeAsync(buffer, index, count); } // Raw writers do not have to verify NmToken values. public override Task WriteNmTokenAsync(string name) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } // Raw writers do not have to verify Name values. public override Task WriteNameAsync(string name) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } // Raw writers do not have to verify QName values. public override Task WriteQualifiedNameAsync(string localName, string ns) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } // Forward call to WriteString(string). public override Task WriteCDataAsync(string text) { return WriteStringAsync(text); } // Forward call to WriteString(string). public override Task WriteCharEntityAsync(char ch) { return WriteStringAsync(ch.ToString()); } // Forward call to WriteString(string). public override Task WriteSurrogateCharEntityAsync(char lowChar, char highChar) { return WriteStringAsync(new string(new char[] { lowChar, highChar })); } // Forward call to WriteString(string). public override Task WriteWhitespaceAsync(string ws) { return WriteStringAsync(ws); } // Forward call to WriteString(string). public override Task WriteCharsAsync(char[] buffer, int index, int count) { return WriteStringAsync(new string(buffer, index, count)); } // Forward call to WriteString(string). public override Task WriteRawAsync(char[] buffer, int index, int count) { return WriteStringAsync(new string(buffer, index, count)); } // Forward call to WriteString(string). public override Task WriteRawAsync(string data) { return WriteStringAsync(data); } // Copying to XmlRawWriter is not currently supported. public override Task WriteAttributesAsync(XmlReader reader, bool defattr) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } public override Task WriteNodeAsync(XmlReader reader, bool defattr) { throw new InvalidOperationException(SR.Xml_InvalidOperation); } // // XmlRawWriter methods and properties // // Write the xml declaration. This must be the first call. internal virtual Task WriteXmlDeclarationAsync(XmlStandalone standalone) { return Task.CompletedTask; } internal virtual Task WriteXmlDeclarationAsync(string xmldecl) { return Task.CompletedTask; } // Called after an element's attributes have been enumerated, but before any children have been // enumerated. This method must always be called, even for empty elements. internal virtual Task StartElementContentAsync() { throw NotImplemented.ByDesign; } // WriteEndElement() and WriteFullEndElement() overloads, in which caller gives the full name of the // element, so that raw writers do not need to keep a stack of element names. This method should // always be called instead of WriteEndElement() or WriteFullEndElement() without parameters. internal virtual Task WriteEndElementAsync(string prefix, string localName, string ns) { throw NotImplemented.ByDesign; } internal virtual Task WriteFullEndElementAsync(string prefix, string localName, string ns) { return WriteEndElementAsync(prefix, localName, ns); } internal virtual async Task WriteQualifiedNameAsync(string prefix, string localName, string ns) { if (prefix.Length != 0) { await WriteStringAsync(prefix).ConfigureAwait(false); await WriteStringAsync(":").ConfigureAwait(false); } await WriteStringAsync(localName).ConfigureAwait(false); } // This method must be called instead of WriteStartAttribute() for namespaces. internal virtual Task WriteNamespaceDeclarationAsync(string prefix, string ns) { throw NotImplemented.ByDesign; } internal virtual Task WriteStartNamespaceDeclarationAsync(string prefix) { throw new NotSupportedException(); } internal virtual Task WriteEndNamespaceDeclarationAsync() { throw new NotSupportedException(); } // This is called when the remainder of a base64 value should be output. internal virtual Task WriteEndBase64Async() { // The Flush will call WriteRaw to write out the rest of the encoded characters return base64Encoder.FlushAsync(); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Drawing; using System.Reflection; using log4net; using Nini.Config; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules.World.LegacyMap { public class ShadedMapTileRenderer : IMapTileTerrainRenderer { private static readonly Color WATER_COLOR = Color.FromArgb(29, 71, 95); private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Scene m_scene; //private IConfigSource m_config; // not used currently public void Initialise(Scene scene, IConfigSource config) { m_scene = scene; // m_config = config; // not used currently } public void TerrainToBitmap(Bitmap mapbmp) { int tc = Environment.TickCount; m_log.Debug("[SHADED MAP TILE RENDERER]: Generating Maptile Step 1: Terrain"); double[,] hm = m_scene.Heightmap.GetDoubles(); bool ShadowDebugContinue = true; bool terraincorruptedwarningsaid = false; float low = 255; float high = 0; for (int x = 0; x < (int)Constants.RegionSize; x++) { for (int y = 0; y < (int)Constants.RegionSize; y++) { float hmval = (float)hm[x, y]; if (hmval < low) low = hmval; if (hmval > high) high = hmval; } } float waterHeight = (float)m_scene.RegionInfo.RegionSettings.WaterHeight; for (int x = 0; x < (int)Constants.RegionSize; x++) { for (int y = 0; y < (int)Constants.RegionSize; y++) { // Y flip the cordinates for the bitmap: hf origin is lower left, bm origin is upper left int yr = ((int)Constants.RegionSize - 1) - y; float heightvalue = (float)hm[x, y]; if (heightvalue > waterHeight) { // scale height value // No, that doesn't scale it: // heightvalue = low + mid * (heightvalue - low) / mid; => low + (heightvalue - low) * mid / mid = low + (heightvalue - low) * 1 = low + heightvalue - low = heightvalue if (Single.IsInfinity(heightvalue) || Single.IsNaN(heightvalue)) heightvalue = 0; else if (heightvalue > 255f) heightvalue = 255f; else if (heightvalue < 0f) heightvalue = 0f; Color color = Color.FromArgb((int)heightvalue, 100, (int)heightvalue); mapbmp.SetPixel(x, yr, color); try { //X // . // // Shade the terrain for shadows if (x < ((int)Constants.RegionSize - 1) && yr < ((int)Constants.RegionSize - 1)) { float hfvalue = (float)hm[x, y]; float hfvaluecompare = 0f; if ((x + 1 < (int)Constants.RegionSize) && (y + 1 < (int)Constants.RegionSize)) { hfvaluecompare = (float)hm[x + 1, y + 1]; // light from north-east => look at land height there } if (Single.IsInfinity(hfvalue) || Single.IsNaN(hfvalue)) hfvalue = 0f; if (Single.IsInfinity(hfvaluecompare) || Single.IsNaN(hfvaluecompare)) hfvaluecompare = 0f; float hfdiff = hfvalue - hfvaluecompare; // => positive if NE is lower, negative if here is lower int hfdiffi = 0; int hfdiffihighlight = 0; float highlightfactor = 0.18f; try { // hfdiffi = Math.Abs((int)((hfdiff * 4) + (hfdiff * 0.5))) + 1; hfdiffi = Math.Abs((int)(hfdiff * 4.5f)) + 1; if (hfdiff % 1f != 0) { // hfdiffi = hfdiffi + Math.Abs((int)(((hfdiff % 1) * 0.5f) * 10f) - 1); hfdiffi = hfdiffi + Math.Abs((int)((hfdiff % 1f) * 5f) - 1); } hfdiffihighlight = Math.Abs((int)((hfdiff * highlightfactor) * 4.5f)) + 1; if (hfdiff % 1f != 0) { // hfdiffi = hfdiffi + Math.Abs((int)(((hfdiff % 1) * 0.5f) * 10f) - 1); hfdiffihighlight = hfdiffihighlight + Math.Abs((int)(((hfdiff * highlightfactor) % 1f) * 5f) - 1); } } catch (OverflowException) { m_log.Debug("[MAPTILE]: Shadow failed at value: " + hfdiff.ToString()); ShadowDebugContinue = false; } if (hfdiff > 0.3f) { // NE is lower than here // We have to desaturate and lighten the land at the same time // we use floats, colors use bytes, so shrink are space down to // 0-255 if (ShadowDebugContinue) { int r = color.R; int g = color.G; int b = color.B; color = Color.FromArgb((r + hfdiffihighlight < 255) ? r + hfdiffihighlight : 255, (g + hfdiffihighlight < 255) ? g + hfdiffihighlight : 255, (b + hfdiffihighlight < 255) ? b + hfdiffihighlight : 255); } } else if (hfdiff < -0.3f) { // here is lower than NE: // We have to desaturate and blacken the land at the same time // we use floats, colors use bytes, so shrink are space down to // 0-255 if (ShadowDebugContinue) { if ((x - 1 > 0) && (yr + 1 < (int)Constants.RegionSize)) { color = mapbmp.GetPixel(x - 1, yr + 1); int r = color.R; int g = color.G; int b = color.B; color = Color.FromArgb((r - hfdiffi > 0) ? r - hfdiffi : 0, (g - hfdiffi > 0) ? g - hfdiffi : 0, (b - hfdiffi > 0) ? b - hfdiffi : 0); mapbmp.SetPixel(x-1, yr+1, color); } } } } } catch (ArgumentException) { if (!terraincorruptedwarningsaid) { m_log.WarnFormat("[SHADED MAP TILE RENDERER]: Your terrain is corrupted in region {0}, it might take a few minutes to generate the map image depending on the corruption level", m_scene.RegionInfo.RegionName); terraincorruptedwarningsaid = true; } color = Color.Black; mapbmp.SetPixel(x, yr, color); } } else { // We're under the water level with the terrain, so paint water instead of land // Y flip the cordinates heightvalue = waterHeight - heightvalue; if (Single.IsInfinity(heightvalue) || Single.IsNaN(heightvalue)) heightvalue = 0f; else if (heightvalue > 19f) heightvalue = 19f; else if (heightvalue < 0f) heightvalue = 0f; heightvalue = 100f - (heightvalue * 100f) / 19f; try { mapbmp.SetPixel(x, yr, WATER_COLOR); } catch (ArgumentException) { if (!terraincorruptedwarningsaid) { m_log.WarnFormat("[SHADED MAP TILE RENDERER]: Your terrain is corrupted in region {0}, it might take a few minutes to generate the map image depending on the corruption level", m_scene.RegionInfo.RegionName); terraincorruptedwarningsaid = true; } Color black = Color.Black; mapbmp.SetPixel(x, ((int)Constants.RegionSize - y) - 1, black); } } } } m_log.Debug("[SHADED MAP TILE RENDERER]: Generating Maptile Step 1: Done in " + (Environment.TickCount - tc) + " ms"); } } }
#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 System.Collections.Generic; using System.Reflection; using System.Collections; using System.Globalization; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Text; #if NETFX_CORE using IConvertible = Newtonsoft.Json.Utilities.Convertible; #endif #if NETFX_CORE || PORTABLE using ICustomAttributeProvider = Newtonsoft.Json.Utilities.CustomAttributeProvider; #endif #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif using Newtonsoft.Json.Serialization; namespace Newtonsoft.Json.Utilities { #if NETFX_CORE || PORTABLE internal enum MemberTypes { Property, Field, Event, Method, Other } internal class CustomAttributeProvider { private readonly object _underlyingObject; public CustomAttributeProvider(object o) { _underlyingObject = o; } public object UnderlyingObject { get { return _underlyingObject; } } } #endif #if NETFX_CORE internal enum TypeCode { Empty, Object, String, Char, Boolean, SByte, Int16, UInt16, Int32, Byte, UInt32, Int64, UInt64, Single, Double, DateTime, Decimal } [Flags] internal enum BindingFlags { Default = 0, IgnoreCase = 1, DeclaredOnly = 2, Instance = 4, Static = 8, Public = 16, NonPublic = 32, FlattenHierarchy = 64, InvokeMethod = 256, CreateInstance = 512, GetField = 1024, SetField = 2048, GetProperty = 4096, SetProperty = 8192, PutDispProperty = 16384, ExactBinding = 65536, PutRefDispProperty = 32768, SuppressChangeType = 131072, OptionalParamBinding = 262144, IgnoreReturn = 16777216 } #endif internal static class ReflectionUtils { public static readonly Type[] EmptyTypes; static ReflectionUtils() { #if !(NETFX_CORE || PORTABLE) EmptyTypes = Type.EmptyTypes; #else EmptyTypes = new Type[0]; #endif } public static ICustomAttributeProvider GetCustomAttributeProvider(this object o) { #if !(NETFX_CORE || PORTABLE) return (ICustomAttributeProvider)o; #else return new ICustomAttributeProvider(o); #endif } public static bool IsVirtual(this PropertyInfo propertyInfo) { ValidationUtils.ArgumentNotNull(propertyInfo, "propertyInfo"); MethodInfo m = propertyInfo.GetGetMethod(); if (m != null && m.IsVirtual) return true; m = propertyInfo.GetSetMethod(); if (m != null && m.IsVirtual) return true; return false; } public static Type GetObjectType(object v) { return (v != null) ? v.GetType() : null; } public static string GetTypeName(Type t, FormatterAssemblyStyle assemblyFormat) { return GetTypeName(t, assemblyFormat, null); } public static string GetTypeName(Type t, FormatterAssemblyStyle assemblyFormat, SerializationBinder binder) { string fullyQualifiedTypeName; #if !(NET20 || NET35) if (binder != null) { string assemblyName, typeName; binder.BindToName(t, out assemblyName, out typeName); fullyQualifiedTypeName = typeName + (assemblyName == null ? "" : ", " + assemblyName); } else { fullyQualifiedTypeName = t.AssemblyQualifiedName; } #else fullyQualifiedTypeName = t.AssemblyQualifiedName; #endif switch (assemblyFormat) { case FormatterAssemblyStyle.Simple: return RemoveAssemblyDetails(fullyQualifiedTypeName); case FormatterAssemblyStyle.Full: return fullyQualifiedTypeName; default: throw new ArgumentOutOfRangeException(); } } private static string RemoveAssemblyDetails(string fullyQualifiedTypeName) { StringBuilder builder = new StringBuilder(); // loop through the type name and filter out qualified assembly details from nested type names bool writingAssemblyName = false; bool skippingAssemblyDetails = false; for (int i = 0; i < fullyQualifiedTypeName.Length; i++) { char current = fullyQualifiedTypeName[i]; switch (current) { case '[': writingAssemblyName = false; skippingAssemblyDetails = false; builder.Append(current); break; case ']': writingAssemblyName = false; skippingAssemblyDetails = false; builder.Append(current); break; case ',': if (!writingAssemblyName) { writingAssemblyName = true; builder.Append(current); } else { skippingAssemblyDetails = true; } break; default: if (!skippingAssemblyDetails) builder.Append(current); break; } } return builder.ToString(); } public static bool IsInstantiatableType(Type t) { ValidationUtils.ArgumentNotNull(t, "t"); if (t.IsAbstract() || t.IsInterface() || t.IsArray || t.IsGenericTypeDefinition() || t == typeof(void)) return false; if (!HasDefaultConstructor(t)) return false; return true; } public static bool HasDefaultConstructor(Type t) { return HasDefaultConstructor(t, false); } public static bool HasDefaultConstructor(Type t, bool nonPublic) { ValidationUtils.ArgumentNotNull(t, "t"); if (t.IsValueType()) return true; return (GetDefaultConstructor(t, nonPublic) != null); } public static ConstructorInfo GetDefaultConstructor(Type t) { return GetDefaultConstructor(t, false); } public static ConstructorInfo GetDefaultConstructor(Type t, bool nonPublic) { BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public; if (nonPublic) bindingFlags = bindingFlags | BindingFlags.NonPublic; return t.GetConstructors(bindingFlags).SingleOrDefault(c => !c.GetParameters().Any()); } public static bool IsNullable(Type t) { ValidationUtils.ArgumentNotNull(t, "t"); if (t.IsValueType()) return IsNullableType(t); return true; } public static bool IsNullableType(Type t) { ValidationUtils.ArgumentNotNull(t, "t"); return (t.IsGenericType() && t.GetGenericTypeDefinition() == typeof(Nullable<>)); } public static Type EnsureNotNullableType(Type t) { return (IsNullableType(t)) ? Nullable.GetUnderlyingType(t) : t; } public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition) { Type implementingType; return ImplementsGenericDefinition(type, genericInterfaceDefinition, out implementingType); } public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition, out Type implementingType) { ValidationUtils.ArgumentNotNull(type, "type"); ValidationUtils.ArgumentNotNull(genericInterfaceDefinition, "genericInterfaceDefinition"); if (!genericInterfaceDefinition.IsInterface() || !genericInterfaceDefinition.IsGenericTypeDefinition()) throw new ArgumentNullException("'{0}' is not a generic interface definition.".FormatWith(CultureInfo.InvariantCulture, genericInterfaceDefinition)); if (type.IsInterface()) { if (type.IsGenericType()) { Type interfaceDefinition = type.GetGenericTypeDefinition(); if (genericInterfaceDefinition == interfaceDefinition) { implementingType = type; return true; } } } foreach (Type i in type.GetInterfaces()) { if (i.IsGenericType()) { Type interfaceDefinition = i.GetGenericTypeDefinition(); if (genericInterfaceDefinition == interfaceDefinition) { implementingType = i; return true; } } } implementingType = null; return false; } public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition) { Type implementingType; return InheritsGenericDefinition(type, genericClassDefinition, out implementingType); } public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition, out Type implementingType) { ValidationUtils.ArgumentNotNull(type, "type"); ValidationUtils.ArgumentNotNull(genericClassDefinition, "genericClassDefinition"); if (!genericClassDefinition.IsClass() || !genericClassDefinition.IsGenericTypeDefinition()) throw new ArgumentNullException("'{0}' is not a generic class definition.".FormatWith(CultureInfo.InvariantCulture, genericClassDefinition)); return InheritsGenericDefinitionInternal(type, genericClassDefinition, out implementingType); } private static bool InheritsGenericDefinitionInternal(Type currentType, Type genericClassDefinition, out Type implementingType) { if (currentType.IsGenericType()) { Type currentGenericClassDefinition = currentType.GetGenericTypeDefinition(); if (genericClassDefinition == currentGenericClassDefinition) { implementingType = currentType; return true; } } if (currentType.BaseType() == null) { implementingType = null; return false; } return InheritsGenericDefinitionInternal(currentType.BaseType(), genericClassDefinition, out implementingType); } /// <summary> /// Gets the type of the typed collection's items. /// </summary> /// <param name="type">The type.</param> /// <returns>The type of the typed collection's items.</returns> public static Type GetCollectionItemType(Type type) { ValidationUtils.ArgumentNotNull(type, "type"); Type genericListType; if (type.IsArray) { return type.GetElementType(); } else if (ImplementsGenericDefinition(type, typeof(IEnumerable<>), out genericListType)) { if (genericListType.IsGenericTypeDefinition()) throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type)); return genericListType.GetGenericArguments()[0]; } else if (typeof(IEnumerable).IsAssignableFrom(type)) { return null; } else { throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type)); } } public static void GetDictionaryKeyValueTypes(Type dictionaryType, out Type keyType, out Type valueType) { ValidationUtils.ArgumentNotNull(dictionaryType, "type"); Type genericDictionaryType; if (ImplementsGenericDefinition(dictionaryType, typeof(IDictionary<,>), out genericDictionaryType)) { if (genericDictionaryType.IsGenericTypeDefinition()) throw new Exception("Type {0} is not a dictionary.".FormatWith(CultureInfo.InvariantCulture, dictionaryType)); Type[] dictionaryGenericArguments = genericDictionaryType.GetGenericArguments(); keyType = dictionaryGenericArguments[0]; valueType = dictionaryGenericArguments[1]; return; } else if (typeof(IDictionary).IsAssignableFrom(dictionaryType)) { keyType = null; valueType = null; return; } else { throw new Exception("Type {0} is not a dictionary.".FormatWith(CultureInfo.InvariantCulture, dictionaryType)); } } public static Type GetDictionaryValueType(Type dictionaryType) { Type keyType; Type valueType; GetDictionaryKeyValueTypes(dictionaryType, out keyType, out valueType); return valueType; } public static Type GetDictionaryKeyType(Type dictionaryType) { Type keyType; Type valueType; GetDictionaryKeyValueTypes(dictionaryType, out keyType, out valueType); return keyType; } /// <summary> /// Gets the member's underlying type. /// </summary> /// <param name="member">The member.</param> /// <returns>The underlying type of the member.</returns> public static Type GetMemberUnderlyingType(MemberInfo member) { ValidationUtils.ArgumentNotNull(member, "member"); switch (member.MemberType()) { case MemberTypes.Field: return ((FieldInfo)member).FieldType; case MemberTypes.Property: return ((PropertyInfo)member).PropertyType; case MemberTypes.Event: return ((EventInfo)member).EventHandlerType; default: throw new ArgumentException("MemberInfo must be of type FieldInfo, PropertyInfo or EventInfo", "member"); } } /// <summary> /// Determines whether the member is an indexed property. /// </summary> /// <param name="member">The member.</param> /// <returns> /// <c>true</c> if the member is an indexed property; otherwise, <c>false</c>. /// </returns> public static bool IsIndexedProperty(MemberInfo member) { ValidationUtils.ArgumentNotNull(member, "member"); PropertyInfo propertyInfo = member as PropertyInfo; if (propertyInfo != null) return IsIndexedProperty(propertyInfo); else return false; } /// <summary> /// Determines whether the property is an indexed property. /// </summary> /// <param name="property">The property.</param> /// <returns> /// <c>true</c> if the property is an indexed property; otherwise, <c>false</c>. /// </returns> public static bool IsIndexedProperty(PropertyInfo property) { ValidationUtils.ArgumentNotNull(property, "property"); return (property.GetIndexParameters().Length > 0); } /// <summary> /// Gets the member's value on the object. /// </summary> /// <param name="member">The member.</param> /// <param name="target">The target object.</param> /// <returns>The member's value on the object.</returns> public static object GetMemberValue(MemberInfo member, object target) { ValidationUtils.ArgumentNotNull(member, "member"); ValidationUtils.ArgumentNotNull(target, "target"); switch (member.MemberType()) { case MemberTypes.Field: return ((FieldInfo)member).GetValue(target); case MemberTypes.Property: try { return ((PropertyInfo)member).GetValue(target, null); } catch (TargetParameterCountException e) { throw new ArgumentException("MemberInfo '{0}' has index parameters".FormatWith(CultureInfo.InvariantCulture, member.Name), e); } default: throw new ArgumentException("MemberInfo '{0}' is not of type FieldInfo or PropertyInfo".FormatWith(CultureInfo.InvariantCulture, CultureInfo.InvariantCulture, member.Name), "member"); } } /// <summary> /// Sets the member's value on the target object. /// </summary> /// <param name="member">The member.</param> /// <param name="target">The target.</param> /// <param name="value">The value.</param> public static void SetMemberValue(MemberInfo member, object target, object value) { ValidationUtils.ArgumentNotNull(member, "member"); ValidationUtils.ArgumentNotNull(target, "target"); switch (member.MemberType()) { case MemberTypes.Field: ((FieldInfo)member).SetValue(target, value); break; case MemberTypes.Property: ((PropertyInfo)member).SetValue(target, value, null); break; default: throw new ArgumentException("MemberInfo '{0}' must be of type FieldInfo or PropertyInfo".FormatWith(CultureInfo.InvariantCulture, member.Name), "member"); } } /// <summary> /// Determines whether the specified MemberInfo can be read. /// </summary> /// <param name="member">The MemberInfo to determine whether can be read.</param> /// /// <param name="nonPublic">if set to <c>true</c> then allow the member to be gotten non-publicly.</param> /// <returns> /// <c>true</c> if the specified MemberInfo can be read; otherwise, <c>false</c>. /// </returns> public static bool CanReadMemberValue(MemberInfo member, bool nonPublic) { switch (member.MemberType()) { case MemberTypes.Field: FieldInfo fieldInfo = (FieldInfo)member; if (nonPublic) return true; else if (fieldInfo.IsPublic) return true; return false; case MemberTypes.Property: PropertyInfo propertyInfo = (PropertyInfo) member; if (!propertyInfo.CanRead) return false; if (nonPublic) return true; return (propertyInfo.GetGetMethod(nonPublic) != null); default: return false; } } /// <summary> /// Determines whether the specified MemberInfo can be set. /// </summary> /// <param name="member">The MemberInfo to determine whether can be set.</param> /// <param name="nonPublic">if set to <c>true</c> then allow the member to be set non-publicly.</param> /// <param name="canSetReadOnly">if set to <c>true</c> then allow the member to be set if read-only.</param> /// <returns> /// <c>true</c> if the specified MemberInfo can be set; otherwise, <c>false</c>. /// </returns> public static bool CanSetMemberValue(MemberInfo member, bool nonPublic, bool canSetReadOnly) { switch (member.MemberType()) { case MemberTypes.Field: FieldInfo fieldInfo = (FieldInfo)member; if (fieldInfo.IsInitOnly && !canSetReadOnly) return false; if (nonPublic) return true; else if (fieldInfo.IsPublic) return true; return false; case MemberTypes.Property: PropertyInfo propertyInfo = (PropertyInfo)member; if (!propertyInfo.CanWrite) return false; if (nonPublic) return true; return (propertyInfo.GetSetMethod(nonPublic) != null); default: return false; } } public static List<MemberInfo> GetFieldsAndProperties(Type type, BindingFlags bindingAttr) { List<MemberInfo> targetMembers = new List<MemberInfo>(); targetMembers.AddRange(GetFields(type, bindingAttr)); targetMembers.AddRange(GetProperties(type, bindingAttr)); // for some reason .NET returns multiple members when overriding a generic member on a base class // http://forums.msdn.microsoft.com/en-US/netfxbcl/thread/b5abbfee-e292-4a64-8907-4e3f0fb90cd9/ // filter members to only return the override on the topmost class // update: I think this is fixed in .NET 3.5 SP1 - leave this in for now... List<MemberInfo> distinctMembers = new List<MemberInfo>(targetMembers.Count); foreach (var groupedMember in targetMembers.GroupBy(m => m.Name)) { int count = groupedMember.Count(); IList<MemberInfo> members = groupedMember.ToList(); if (count == 1) { distinctMembers.Add(members.First()); } else { var resolvedMembers = members.Where(m => !IsOverridenGenericMember(m, bindingAttr) || m.Name == "Item"); distinctMembers.AddRange(resolvedMembers); } } return distinctMembers; } private static bool IsOverridenGenericMember(MemberInfo memberInfo, BindingFlags bindingAttr) { MemberTypes memberType = memberInfo.MemberType(); if (memberType != MemberTypes.Field && memberType != MemberTypes.Property) throw new ArgumentException("Member must be a field or property."); Type declaringType = memberInfo.DeclaringType; if (!declaringType.IsGenericType()) return false; Type genericTypeDefinition = declaringType.GetGenericTypeDefinition(); if (genericTypeDefinition == null) return false; MemberInfo[] members = genericTypeDefinition.GetMember(memberInfo.Name, bindingAttr); if (members.Length == 0) return false; Type memberUnderlyingType = GetMemberUnderlyingType(members[0]); if (!memberUnderlyingType.IsGenericParameter) return false; return true; } public static T GetAttribute<T>(ICustomAttributeProvider attributeProvider) where T : Attribute { return GetAttribute<T>(attributeProvider, true); } public static T GetAttribute<T>(ICustomAttributeProvider attributeProvider, bool inherit) where T : Attribute { T[] attributes = GetAttributes<T>(attributeProvider, inherit); return attributes.SingleOrDefault(); } #if !(NETFX_CORE) public static T[] GetAttributes<T>(ICustomAttributeProvider attributeProvider, bool inherit) where T : Attribute { ValidationUtils.ArgumentNotNull(attributeProvider, "attributeProvider"); object provider; #if !PORTABLE provider = attributeProvider; #else provider = attributeProvider.UnderlyingObject; #endif // http://hyperthink.net/blog/getcustomattributes-gotcha/ // ICustomAttributeProvider doesn't do inheritance if (provider is Type) return (T[])((Type)provider).GetCustomAttributes(typeof(T), inherit); if (provider is Assembly) return (T[])Attribute.GetCustomAttributes((Assembly)provider, typeof(T)); if (provider is MemberInfo) return (T[])Attribute.GetCustomAttributes((MemberInfo)provider, typeof(T), inherit); #if !PORTABLE if (provider is Module) return (T[])Attribute.GetCustomAttributes((Module)provider, typeof(T), inherit); #endif if (provider is ParameterInfo) return (T[])Attribute.GetCustomAttributes((ParameterInfo)provider, typeof(T), inherit); #if !PORTABLE return (T[])attributeProvider.GetCustomAttributes(typeof(T), inherit); #else throw new Exception("Cannot get attributes from '{0}'.".FormatWith(CultureInfo.InvariantCulture, provider)); #endif } #else public static T[] GetAttributes<T>(ICustomAttributeProvider attributeProvider, bool inherit) where T : Attribute { object provider = attributeProvider.UnderlyingObject; if (provider is Type) return ((Type)provider).GetTypeInfo().GetCustomAttributes<T>(inherit).ToArray(); if (provider is Assembly) return ((Assembly)provider).GetCustomAttributes<T>().ToArray(); if (provider is MemberInfo) return ((MemberInfo)provider).GetCustomAttributes<T>(inherit).ToArray(); if (provider is Module) return ((Module)provider).GetCustomAttributes<T>().ToArray(); if (provider is ParameterInfo) return ((ParameterInfo)provider).GetCustomAttributes<T>(inherit).ToArray(); throw new Exception("Cannot get attributes from '{0}'.".FormatWith(CultureInfo.InvariantCulture, provider)); } #endif public static Type MakeGenericType(Type genericTypeDefinition, params Type[] innerTypes) { ValidationUtils.ArgumentNotNull(genericTypeDefinition, "genericTypeDefinition"); ValidationUtils.ArgumentNotNullOrEmpty<Type>(innerTypes, "innerTypes"); ValidationUtils.ArgumentConditionTrue(genericTypeDefinition.IsGenericTypeDefinition(), "genericTypeDefinition", "Type {0} is not a generic type definition.".FormatWith(CultureInfo.InvariantCulture, genericTypeDefinition)); return genericTypeDefinition.MakeGenericType(innerTypes); } public static object CreateGeneric(Type genericTypeDefinition, Type innerType, params object[] args) { return CreateGeneric(genericTypeDefinition, new [] { innerType }, args); } public static object CreateGeneric(Type genericTypeDefinition, IList<Type> innerTypes, params object[] args) { return CreateGeneric(genericTypeDefinition, innerTypes, (t, a) => CreateInstance(t, a.ToArray()), args); } public static object CreateGeneric(Type genericTypeDefinition, IList<Type> innerTypes, Func<Type, IList<object>, object> instanceCreator, params object[] args) { ValidationUtils.ArgumentNotNull(genericTypeDefinition, "genericTypeDefinition"); ValidationUtils.ArgumentNotNullOrEmpty(innerTypes, "innerTypes"); ValidationUtils.ArgumentNotNull(instanceCreator, "createInstance"); Type specificType = MakeGenericType(genericTypeDefinition, innerTypes.ToArray()); return instanceCreator(specificType, args); } public static object CreateInstance(Type type, params object[] args) { ValidationUtils.ArgumentNotNull(type, "type"); #if !PocketPC return Activator.CreateInstance(type, args); #else // CF doesn't have a Activator.CreateInstance overload that takes args // lame if (type.IsValueType && CollectionUtils.IsNullOrEmpty<object>(args)) return Activator.CreateInstance(type); ConstructorInfo[] constructors = type.GetConstructors(); ConstructorInfo match = constructors.Where(c => { ParameterInfo[] parameters = c.GetParameters(); if (parameters.Length != args.Length) return false; for (int i = 0; i < parameters.Length; i++) { ParameterInfo parameter = parameters[i]; object value = args[i]; if (!IsCompatibleValue(value, parameter.ParameterType)) return false; } return true; }).FirstOrDefault(); if (match == null) throw new Exception("Could not create '{0}' with given parameters.".FormatWith(CultureInfo.InvariantCulture, type)); return match.Invoke(args); #endif } public static void SplitFullyQualifiedTypeName(string fullyQualifiedTypeName, out string typeName, out string assemblyName) { int? assemblyDelimiterIndex = GetAssemblyDelimiterIndex(fullyQualifiedTypeName); if (assemblyDelimiterIndex != null) { typeName = fullyQualifiedTypeName.Substring(0, assemblyDelimiterIndex.Value).Trim(); assemblyName = fullyQualifiedTypeName.Substring(assemblyDelimiterIndex.Value + 1, fullyQualifiedTypeName.Length - assemblyDelimiterIndex.Value - 1).Trim(); } else { typeName = fullyQualifiedTypeName; assemblyName = null; } } private static int? GetAssemblyDelimiterIndex(string fullyQualifiedTypeName) { // we need to get the first comma following all surrounded in brackets because of generic types // e.g. System.Collections.Generic.Dictionary`2[[System.String, mscorlib,Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 int scope = 0; for (int i = 0; i < fullyQualifiedTypeName.Length; i++) { char current = fullyQualifiedTypeName[i]; switch (current) { case '[': scope++; break; case ']': scope--; break; case ',': if (scope == 0) return i; break; } } return null; } public static MemberInfo GetMemberInfoFromType(Type targetType, MemberInfo memberInfo) { const BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; switch (memberInfo.MemberType()) { case MemberTypes.Property: PropertyInfo propertyInfo = (PropertyInfo) memberInfo; Type[] types = propertyInfo.GetIndexParameters().Select(p => p.ParameterType).ToArray(); return targetType.GetProperty(propertyInfo.Name, bindingAttr, null, propertyInfo.PropertyType, types, null); default: return targetType.GetMember(memberInfo.Name, memberInfo.MemberType(), bindingAttr).SingleOrDefault(); } } public static IEnumerable<FieldInfo> GetFields(Type targetType, BindingFlags bindingAttr) { ValidationUtils.ArgumentNotNull(targetType, "targetType"); List<MemberInfo> fieldInfos = new List<MemberInfo>(targetType.GetFields(bindingAttr)); #if !NETFX_CORE // Type.GetFields doesn't return inherited private fields // manually find private fields from base class GetChildPrivateFields(fieldInfos, targetType, bindingAttr); #endif return fieldInfos.Cast<FieldInfo>(); } private static void GetChildPrivateFields(IList<MemberInfo> initialFields, Type targetType, BindingFlags bindingAttr) { // fix weirdness with private FieldInfos only being returned for the current Type // find base type fields and add them to result if ((bindingAttr & BindingFlags.NonPublic) != 0) { // modify flags to not search for public fields BindingFlags nonPublicBindingAttr = bindingAttr.RemoveFlag(BindingFlags.Public); while ((targetType = targetType.BaseType()) != null) { // filter out protected fields IEnumerable<MemberInfo> childPrivateFields = targetType.GetFields(nonPublicBindingAttr).Where(f => f.IsPrivate).Cast<MemberInfo>(); initialFields.AddRange(childPrivateFields); } } } public static IEnumerable<PropertyInfo> GetProperties(Type targetType, BindingFlags bindingAttr) { ValidationUtils.ArgumentNotNull(targetType, "targetType"); List<PropertyInfo> propertyInfos = new List<PropertyInfo>(targetType.GetProperties(bindingAttr)); GetChildPrivateProperties(propertyInfos, targetType, bindingAttr); // a base class private getter/setter will be inaccessable unless the property was gotten from the base class for (int i = 0; i < propertyInfos.Count; i++) { PropertyInfo member = propertyInfos[i]; if (member.DeclaringType != targetType) { PropertyInfo declaredMember = (PropertyInfo)GetMemberInfoFromType(member.DeclaringType, member); propertyInfos[i] = declaredMember; } } return propertyInfos; } public static BindingFlags RemoveFlag(this BindingFlags bindingAttr, BindingFlags flag) { return ((bindingAttr & flag) == flag) ? bindingAttr ^ flag : bindingAttr; } private static void GetChildPrivateProperties(IList<PropertyInfo> initialProperties, Type targetType, BindingFlags bindingAttr) { // fix weirdness with private PropertyInfos only being returned for the current Type // find base type properties and add them to result if ((bindingAttr & BindingFlags.NonPublic) != 0) { // modify flags to not search for public fields BindingFlags nonPublicBindingAttr = bindingAttr.RemoveFlag(BindingFlags.Public); while ((targetType = targetType.BaseType()) != null) { foreach (PropertyInfo propertyInfo in targetType.GetProperties(nonPublicBindingAttr)) { PropertyInfo nonPublicProperty = propertyInfo; // have to test on name rather than reference because instances are different // depending on the type that GetProperties was called on int index = initialProperties.IndexOf(p => p.Name == nonPublicProperty.Name); if (index == -1) { initialProperties.Add(nonPublicProperty); } else { // replace nonpublic properties for a child, but gotten from // the parent with the one from the child // the property gotten from the child will have access to private getter/setter initialProperties[index] = nonPublicProperty; } } } } } public static bool IsMethodOverridden(Type currentType, Type methodDeclaringType, string method) { bool isMethodOverriden = currentType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) .Any(info => info.Name == method && // check that the method overrides the original on DynamicObjectProxy info.DeclaringType != methodDeclaringType // todo - find out whether there is a way to do this in winrt #if !NETFX_CORE && info.GetBaseDefinition().DeclaringType == methodDeclaringType #endif ); return isMethodOverriden; } } }
using WixSharp; using WixSharp.UI.Forms; namespace WixSharpSetup.Dialogs { partial class SetupTypeDialog { /// <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.topBorder = new System.Windows.Forms.Panel(); this.label5 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.complete = new System.Windows.Forms.Button(); this.custom = new System.Windows.Forms.Button(); this.typical = new System.Windows.Forms.Button(); this.topPanel = new System.Windows.Forms.Panel(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.banner = new System.Windows.Forms.PictureBox(); this.bottomPanel = new System.Windows.Forms.Panel(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.back = new System.Windows.Forms.Button(); this.next = new System.Windows.Forms.Button(); this.cancel = new System.Windows.Forms.Button(); this.bottomBorder = new System.Windows.Forms.Panel(); this.middlePanel = new System.Windows.Forms.TableLayoutPanel(); this.panel3 = new System.Windows.Forms.Panel(); this.panel4 = new System.Windows.Forms.Panel(); this.panel5 = new System.Windows.Forms.Panel(); this.topPanel.SuspendLayout(); ( (System.ComponentModel.ISupportInitialize)( this.banner ) ).BeginInit(); this.bottomPanel.SuspendLayout(); this.tableLayoutPanel1.SuspendLayout(); this.middlePanel.SuspendLayout(); this.panel3.SuspendLayout(); this.panel4.SuspendLayout(); this.panel5.SuspendLayout(); this.SuspendLayout(); // // topBorder // this.topBorder.Anchor = ( (System.Windows.Forms.AnchorStyles)( ( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left ) | System.Windows.Forms.AnchorStyles.Right ) ) ); this.topBorder.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.topBorder.Location = new System.Drawing.Point( 0, 58 ); this.topBorder.Name = "topBorder"; this.topBorder.Size = new System.Drawing.Size( 494, 1 ); this.topBorder.TabIndex = 18; // // label5 // this.label5.Anchor = ( (System.Windows.Forms.AnchorStyles)( ( System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right ) ) ); this.label5.BackColor = System.Drawing.SystemColors.Control; this.label5.Location = new System.Drawing.Point( 28, 40 ); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size( 445, 38 ); this.label5.TabIndex = 1; this.label5.Text = "[SetupTypeDlgCompleteText]"; // // label4 // this.label4.Anchor = ( (System.Windows.Forms.AnchorStyles)( ( System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right ) ) ); this.label4.BackColor = System.Drawing.SystemColors.Control; this.label4.Location = new System.Drawing.Point( 28, 40 ); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size( 445, 34 ); this.label4.TabIndex = 1; this.label4.Text = "[SetupTypeDlgCustomText]"; // // label3 // this.label3.Anchor = ( (System.Windows.Forms.AnchorStyles)( ( System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right ) ) ); this.label3.AutoEllipsis = true; this.label3.BackColor = System.Drawing.SystemColors.Control; this.label3.Location = new System.Drawing.Point( 28, 40 ); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size( 442, 37 ); this.label3.TabIndex = 1; this.label3.Text = "[SetupTypeDlgTypicalText]"; // // complete // this.complete.Anchor = System.Windows.Forms.AnchorStyles.Left; this.complete.AutoSize = true; this.complete.Location = new System.Drawing.Point( 0, 6 ); this.complete.MaximumSize = new System.Drawing.Size( 113, 0 ); this.complete.MinimumSize = new System.Drawing.Size( 113, 0 ); this.complete.Name = "complete"; this.complete.Size = new System.Drawing.Size( 113, 23 ); this.complete.TabIndex = 16; this.complete.Text = "[SetupTypeDlgCompleteButton]"; this.complete.UseVisualStyleBackColor = true; this.complete.Click += new System.EventHandler( this.complete_Click ); // // custom // this.custom.Anchor = System.Windows.Forms.AnchorStyles.Left; this.custom.AutoSize = true; this.custom.Location = new System.Drawing.Point( 0, 6 ); this.custom.MaximumSize = new System.Drawing.Size( 113, 0 ); this.custom.MinimumSize = new System.Drawing.Size( 113, 0 ); this.custom.Name = "custom"; this.custom.Size = new System.Drawing.Size( 113, 23 ); this.custom.TabIndex = 15; this.custom.Text = "[SetupTypeDlgCustomButton]"; this.custom.UseVisualStyleBackColor = true; this.custom.Click += new System.EventHandler( this.custom_Click ); // // typical // this.typical.Anchor = System.Windows.Forms.AnchorStyles.Left; this.typical.AutoSize = true; this.typical.Location = new System.Drawing.Point( 0, 5 ); this.typical.MaximumSize = new System.Drawing.Size( 113, 0 ); this.typical.MinimumSize = new System.Drawing.Size( 113, 0 ); this.typical.Name = "typical"; this.typical.Size = new System.Drawing.Size( 113, 23 ); this.typical.TabIndex = 0; this.typical.Text = "[SetupTypeDlgTypicalButton]"; this.typical.UseVisualStyleBackColor = true; this.typical.Click += new System.EventHandler( this.typical_Click ); // // topPanel // this.topPanel.Anchor = ( (System.Windows.Forms.AnchorStyles)( ( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left ) | System.Windows.Forms.AnchorStyles.Right ) ) ); this.topPanel.BackColor = System.Drawing.SystemColors.Control; this.topPanel.Controls.Add( this.label2 ); this.topPanel.Controls.Add( this.label1 ); this.topPanel.Controls.Add( this.banner ); this.topPanel.Location = new System.Drawing.Point( 0, 0 ); this.topPanel.Name = "topPanel"; this.topPanel.Size = new System.Drawing.Size( 494, 58 ); this.topPanel.TabIndex = 13; // // label2 // this.label2.AutoSize = true; this.label2.BackColor = System.Drawing.Color.White; this.label2.Location = new System.Drawing.Point( 19, 31 ); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size( 134, 13 ); this.label2.TabIndex = 1; this.label2.Text = "[SetupTypeDlgDescription]"; // // label1 // this.label1.AutoSize = true; this.label1.BackColor = System.Drawing.Color.White; this.label1.Font = new System.Drawing.Font( "Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ( (byte)( 0 ) ) ); this.label1.Location = new System.Drawing.Point( 11, 8 ); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size( 120, 13 ); this.label1.TabIndex = 1; this.label1.Text = "[SetupTypeDlgTitle]"; // // banner // this.banner.Anchor = ( (System.Windows.Forms.AnchorStyles)( ( ( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom ) | System.Windows.Forms.AnchorStyles.Left ) | System.Windows.Forms.AnchorStyles.Right ) ) ); this.banner.BackColor = System.Drawing.Color.White; this.banner.Location = new System.Drawing.Point( 0, 0 ); this.banner.Name = "banner"; this.banner.Size = new System.Drawing.Size( 494, 58 ); this.banner.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.banner.TabIndex = 0; this.banner.TabStop = false; // // bottomPanel // this.bottomPanel.BackColor = System.Drawing.SystemColors.Control; this.bottomPanel.Controls.Add( this.tableLayoutPanel1 ); this.bottomPanel.Controls.Add( this.bottomBorder ); this.bottomPanel.Dock = System.Windows.Forms.DockStyle.Bottom; this.bottomPanel.Location = new System.Drawing.Point( 0, 312 ); this.bottomPanel.Name = "bottomPanel"; this.bottomPanel.Size = new System.Drawing.Size( 494, 49 ); this.bottomPanel.TabIndex = 12; // // tableLayoutPanel1 // this.tableLayoutPanel1.Anchor = ( (System.Windows.Forms.AnchorStyles)( ( ( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom ) | System.Windows.Forms.AnchorStyles.Left ) | System.Windows.Forms.AnchorStyles.Right ) ) ); this.tableLayoutPanel1.ColumnCount = 5; this.tableLayoutPanel1.ColumnStyles.Add( new System.Windows.Forms.ColumnStyle( System.Windows.Forms.SizeType.Percent, 100F ) ); this.tableLayoutPanel1.ColumnStyles.Add( new System.Windows.Forms.ColumnStyle() ); this.tableLayoutPanel1.ColumnStyles.Add( new System.Windows.Forms.ColumnStyle() ); this.tableLayoutPanel1.ColumnStyles.Add( new System.Windows.Forms.ColumnStyle( System.Windows.Forms.SizeType.Absolute, 14F ) ); this.tableLayoutPanel1.ColumnStyles.Add( new System.Windows.Forms.ColumnStyle() ); this.tableLayoutPanel1.Controls.Add( this.back, 1, 0 ); this.tableLayoutPanel1.Controls.Add( this.next, 2, 0 ); this.tableLayoutPanel1.Controls.Add( this.cancel, 4, 0 ); this.tableLayoutPanel1.Location = new System.Drawing.Point( 0, 3 ); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 1; this.tableLayoutPanel1.RowStyles.Add( new System.Windows.Forms.RowStyle( System.Windows.Forms.SizeType.Percent, 100F ) ); this.tableLayoutPanel1.Size = new System.Drawing.Size( 491, 43 ); this.tableLayoutPanel1.TabIndex = 7; // // back // this.back.Anchor = System.Windows.Forms.AnchorStyles.Right; this.back.AutoSize = true; this.back.Enabled = false; this.back.Location = new System.Drawing.Point( 222, 10 ); this.back.MinimumSize = new System.Drawing.Size( 75, 0 ); this.back.Name = "back"; this.back.Size = new System.Drawing.Size( 77, 23 ); this.back.TabIndex = 0; this.back.Text = "[WixUIBack]"; this.back.UseVisualStyleBackColor = true; this.back.Click += new System.EventHandler( this.back_Click ); // // next // this.next.Anchor = System.Windows.Forms.AnchorStyles.Right; this.next.AutoSize = true; this.next.Enabled = false; this.next.Location = new System.Drawing.Point( 305, 10 ); this.next.MinimumSize = new System.Drawing.Size( 75, 0 ); this.next.Name = "next"; this.next.Size = new System.Drawing.Size( 77, 23 ); this.next.TabIndex = 0; this.next.Text = "[WixUINext]"; this.next.UseVisualStyleBackColor = true; this.next.Click += new System.EventHandler( this.next_Click ); // // cancel // this.cancel.Anchor = System.Windows.Forms.AnchorStyles.Right; this.cancel.AutoSize = true; this.cancel.Location = new System.Drawing.Point( 402, 10 ); this.cancel.MinimumSize = new System.Drawing.Size( 75, 0 ); this.cancel.Name = "cancel"; this.cancel.Size = new System.Drawing.Size( 86, 23 ); this.cancel.TabIndex = 0; this.cancel.Text = "[WixUICancel]"; this.cancel.UseVisualStyleBackColor = true; this.cancel.Click += new System.EventHandler( this.cancel_Click ); // // bottomBorder // this.bottomBorder.Anchor = ( (System.Windows.Forms.AnchorStyles)( ( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left ) | System.Windows.Forms.AnchorStyles.Right ) ) ); this.bottomBorder.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.bottomBorder.Location = new System.Drawing.Point( 0, 0 ); this.bottomBorder.Name = "bottomBorder"; this.bottomBorder.Size = new System.Drawing.Size( 494, 1 ); this.bottomBorder.TabIndex = 17; // // middlePanel // this.middlePanel.Anchor = ( (System.Windows.Forms.AnchorStyles)( ( ( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom ) | System.Windows.Forms.AnchorStyles.Left ) | System.Windows.Forms.AnchorStyles.Right ) ) ); this.middlePanel.ColumnCount = 1; this.middlePanel.ColumnStyles.Add( new System.Windows.Forms.ColumnStyle( System.Windows.Forms.SizeType.Percent, 100F ) ); this.middlePanel.Controls.Add( this.panel3, 0, 0 ); this.middlePanel.Controls.Add( this.panel4, 0, 1 ); this.middlePanel.Controls.Add( this.panel5, 0, 2 ); this.middlePanel.Location = new System.Drawing.Point( 14, 60 ); this.middlePanel.Name = "middlePanel"; this.middlePanel.RowCount = 3; this.middlePanel.RowStyles.Add( new System.Windows.Forms.RowStyle( System.Windows.Forms.SizeType.Percent, 33.33333F ) ); this.middlePanel.RowStyles.Add( new System.Windows.Forms.RowStyle( System.Windows.Forms.SizeType.Percent, 33.33333F ) ); this.middlePanel.RowStyles.Add( new System.Windows.Forms.RowStyle( System.Windows.Forms.SizeType.Percent, 33.33333F ) ); this.middlePanel.Size = new System.Drawing.Size( 479, 248 ); this.middlePanel.TabIndex = 19; // // panel3 // this.panel3.Anchor = ( (System.Windows.Forms.AnchorStyles)( ( ( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom ) | System.Windows.Forms.AnchorStyles.Left ) | System.Windows.Forms.AnchorStyles.Right ) ) ); this.panel3.Controls.Add( this.typical ); this.panel3.Controls.Add( this.label3 ); this.panel3.Location = new System.Drawing.Point( 3, 3 ); this.panel3.Name = "panel3"; this.panel3.Size = new System.Drawing.Size( 473, 76 ); this.panel3.TabIndex = 0; // // panel4 // this.panel4.Anchor = ( (System.Windows.Forms.AnchorStyles)( ( ( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom ) | System.Windows.Forms.AnchorStyles.Left ) | System.Windows.Forms.AnchorStyles.Right ) ) ); this.panel4.Controls.Add( this.custom ); this.panel4.Controls.Add( this.label4 ); this.panel4.Location = new System.Drawing.Point( 3, 85 ); this.panel4.Name = "panel4"; this.panel4.Size = new System.Drawing.Size( 473, 76 ); this.panel4.TabIndex = 1; // // panel5 // this.panel5.Anchor = ( (System.Windows.Forms.AnchorStyles)( ( ( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom ) | System.Windows.Forms.AnchorStyles.Left ) | System.Windows.Forms.AnchorStyles.Right ) ) ); this.panel5.Controls.Add( this.complete ); this.panel5.Controls.Add( this.label5 ); this.panel5.Location = new System.Drawing.Point( 3, 167 ); this.panel5.Name = "panel5"; this.panel5.Size = new System.Drawing.Size( 473, 78 ); this.panel5.TabIndex = 2; // // SetupTypeDialog // this.ClientSize = new System.Drawing.Size( 494, 361 ); this.Controls.Add( this.middlePanel ); this.Controls.Add( this.topBorder ); this.Controls.Add( this.topPanel ); this.Controls.Add( this.bottomPanel ); this.Name = "SetupTypeDialog"; this.Text = "[SetupTypeDlg_Title]"; this.Load += new System.EventHandler( this.SetupTypeDialog_Load ); this.topPanel.ResumeLayout( false ); this.topPanel.PerformLayout(); ( (System.ComponentModel.ISupportInitialize)( this.banner ) ).EndInit(); this.bottomPanel.ResumeLayout( false ); this.tableLayoutPanel1.ResumeLayout( false ); this.tableLayoutPanel1.PerformLayout(); this.middlePanel.ResumeLayout( false ); this.panel3.ResumeLayout( false ); this.panel3.PerformLayout(); this.panel4.ResumeLayout( false ); this.panel4.PerformLayout(); this.panel5.ResumeLayout( false ); this.panel5.PerformLayout(); this.ResumeLayout( false ); } #endregion private System.Windows.Forms.PictureBox banner; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Panel topPanel; private System.Windows.Forms.Panel bottomPanel; private System.Windows.Forms.Button typical; private System.Windows.Forms.Button custom; private System.Windows.Forms.Button complete; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.Panel bottomBorder; private System.Windows.Forms.Panel topBorder; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.Button back; private System.Windows.Forms.Button next; private System.Windows.Forms.Button cancel; private System.Windows.Forms.TableLayoutPanel middlePanel; private System.Windows.Forms.Panel panel3; private System.Windows.Forms.Panel panel4; private System.Windows.Forms.Panel panel5; } }
/* * Infoplus API * * Infoplus API. * * OpenAPI spec version: v1.0 * Contact: [email protected] * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Infoplus.Model { /// <summary> /// ThirdPartyParcelAccount /// </summary> [DataContract] public partial class ThirdPartyParcelAccount : IEquatable<ThirdPartyParcelAccount> { /// <summary> /// Initializes a new instance of the <see cref="ThirdPartyParcelAccount" /> class. /// </summary> [JsonConstructorAttribute] protected ThirdPartyParcelAccount() { } /// <summary> /// Initializes a new instance of the <see cref="ThirdPartyParcelAccount" /> class. /// </summary> /// <param name="LobId">LobId (required).</param> /// <param name="Carrier">Carrier (required).</param> /// <param name="AccountNo">AccountNo (required).</param> /// <param name="AccountName">AccountName (required).</param> /// <param name="BillingCompany">BillingCompany (required).</param> /// <param name="Attention">Attention.</param> /// <param name="Street1">Street1 (required).</param> /// <param name="Street2">Street2.</param> /// <param name="Street3">Street3.</param> /// <param name="City">City (required).</param> /// <param name="State">State (required).</param> /// <param name="Country">Country.</param> /// <param name="ZipCode">ZipCode (required).</param> /// <param name="Phone">Phone.</param> /// <param name="Active">Active (required).</param> public ThirdPartyParcelAccount(int? LobId = null, string Carrier = null, string AccountNo = null, string AccountName = null, string BillingCompany = null, string Attention = null, string Street1 = null, string Street2 = null, string Street3 = null, string City = null, string State = null, string Country = null, string ZipCode = null, string Phone = null, string Active = null) { // to ensure "LobId" is required (not null) if (LobId == null) { throw new InvalidDataException("LobId is a required property for ThirdPartyParcelAccount and cannot be null"); } else { this.LobId = LobId; } // to ensure "Carrier" is required (not null) if (Carrier == null) { throw new InvalidDataException("Carrier is a required property for ThirdPartyParcelAccount and cannot be null"); } else { this.Carrier = Carrier; } // to ensure "AccountNo" is required (not null) if (AccountNo == null) { throw new InvalidDataException("AccountNo is a required property for ThirdPartyParcelAccount and cannot be null"); } else { this.AccountNo = AccountNo; } // to ensure "AccountName" is required (not null) if (AccountName == null) { throw new InvalidDataException("AccountName is a required property for ThirdPartyParcelAccount and cannot be null"); } else { this.AccountName = AccountName; } // to ensure "BillingCompany" is required (not null) if (BillingCompany == null) { throw new InvalidDataException("BillingCompany is a required property for ThirdPartyParcelAccount and cannot be null"); } else { this.BillingCompany = BillingCompany; } // to ensure "Street1" is required (not null) if (Street1 == null) { throw new InvalidDataException("Street1 is a required property for ThirdPartyParcelAccount and cannot be null"); } else { this.Street1 = Street1; } // to ensure "City" is required (not null) if (City == null) { throw new InvalidDataException("City is a required property for ThirdPartyParcelAccount and cannot be null"); } else { this.City = City; } // to ensure "State" is required (not null) if (State == null) { throw new InvalidDataException("State is a required property for ThirdPartyParcelAccount and cannot be null"); } else { this.State = State; } // to ensure "ZipCode" is required (not null) if (ZipCode == null) { throw new InvalidDataException("ZipCode is a required property for ThirdPartyParcelAccount and cannot be null"); } else { this.ZipCode = ZipCode; } // to ensure "Active" is required (not null) if (Active == null) { throw new InvalidDataException("Active is a required property for ThirdPartyParcelAccount and cannot be null"); } else { this.Active = Active; } this.Attention = Attention; this.Street2 = Street2; this.Street3 = Street3; this.Country = Country; this.Phone = Phone; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public int? Id { get; private set; } /// <summary> /// Gets or Sets LobId /// </summary> [DataMember(Name="lobId", EmitDefaultValue=false)] public int? LobId { get; set; } /// <summary> /// Gets or Sets Carrier /// </summary> [DataMember(Name="carrier", EmitDefaultValue=false)] public string Carrier { get; set; } /// <summary> /// Gets or Sets AccountNo /// </summary> [DataMember(Name="accountNo", EmitDefaultValue=false)] public string AccountNo { get; set; } /// <summary> /// Gets or Sets AccountName /// </summary> [DataMember(Name="accountName", EmitDefaultValue=false)] public string AccountName { get; set; } /// <summary> /// Gets or Sets BillingCompany /// </summary> [DataMember(Name="billingCompany", EmitDefaultValue=false)] public string BillingCompany { get; set; } /// <summary> /// Gets or Sets Attention /// </summary> [DataMember(Name="attention", EmitDefaultValue=false)] public string Attention { get; set; } /// <summary> /// Gets or Sets Street1 /// </summary> [DataMember(Name="street1", EmitDefaultValue=false)] public string Street1 { get; set; } /// <summary> /// Gets or Sets Street2 /// </summary> [DataMember(Name="street2", EmitDefaultValue=false)] public string Street2 { get; set; } /// <summary> /// Gets or Sets Street3 /// </summary> [DataMember(Name="street3", EmitDefaultValue=false)] public string Street3 { get; set; } /// <summary> /// Gets or Sets City /// </summary> [DataMember(Name="city", EmitDefaultValue=false)] public string City { get; set; } /// <summary> /// Gets or Sets State /// </summary> [DataMember(Name="state", EmitDefaultValue=false)] public string State { get; set; } /// <summary> /// Gets or Sets Country /// </summary> [DataMember(Name="country", EmitDefaultValue=false)] public string Country { get; set; } /// <summary> /// Gets or Sets ZipCode /// </summary> [DataMember(Name="zipCode", EmitDefaultValue=false)] public string ZipCode { get; set; } /// <summary> /// Gets or Sets Phone /// </summary> [DataMember(Name="phone", EmitDefaultValue=false)] public string Phone { get; set; } /// <summary> /// Gets or Sets Active /// </summary> [DataMember(Name="active", EmitDefaultValue=false)] public string Active { get; set; } /// <summary> /// Gets or Sets CreateDate /// </summary> [DataMember(Name="createDate", EmitDefaultValue=false)] public DateTime? CreateDate { get; private set; } /// <summary> /// Gets or Sets ModifyDate /// </summary> [DataMember(Name="modifyDate", EmitDefaultValue=false)] public DateTime? ModifyDate { get; private set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ThirdPartyParcelAccount {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" LobId: ").Append(LobId).Append("\n"); sb.Append(" Carrier: ").Append(Carrier).Append("\n"); sb.Append(" AccountNo: ").Append(AccountNo).Append("\n"); sb.Append(" AccountName: ").Append(AccountName).Append("\n"); sb.Append(" BillingCompany: ").Append(BillingCompany).Append("\n"); sb.Append(" Attention: ").Append(Attention).Append("\n"); sb.Append(" Street1: ").Append(Street1).Append("\n"); sb.Append(" Street2: ").Append(Street2).Append("\n"); sb.Append(" Street3: ").Append(Street3).Append("\n"); sb.Append(" City: ").Append(City).Append("\n"); sb.Append(" State: ").Append(State).Append("\n"); sb.Append(" Country: ").Append(Country).Append("\n"); sb.Append(" ZipCode: ").Append(ZipCode).Append("\n"); sb.Append(" Phone: ").Append(Phone).Append("\n"); sb.Append(" Active: ").Append(Active).Append("\n"); sb.Append(" CreateDate: ").Append(CreateDate).Append("\n"); sb.Append(" ModifyDate: ").Append(ModifyDate).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as ThirdPartyParcelAccount); } /// <summary> /// Returns true if ThirdPartyParcelAccount instances are equal /// </summary> /// <param name="other">Instance of ThirdPartyParcelAccount to be compared</param> /// <returns>Boolean</returns> public bool Equals(ThirdPartyParcelAccount other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.LobId == other.LobId || this.LobId != null && this.LobId.Equals(other.LobId) ) && ( this.Carrier == other.Carrier || this.Carrier != null && this.Carrier.Equals(other.Carrier) ) && ( this.AccountNo == other.AccountNo || this.AccountNo != null && this.AccountNo.Equals(other.AccountNo) ) && ( this.AccountName == other.AccountName || this.AccountName != null && this.AccountName.Equals(other.AccountName) ) && ( this.BillingCompany == other.BillingCompany || this.BillingCompany != null && this.BillingCompany.Equals(other.BillingCompany) ) && ( this.Attention == other.Attention || this.Attention != null && this.Attention.Equals(other.Attention) ) && ( this.Street1 == other.Street1 || this.Street1 != null && this.Street1.Equals(other.Street1) ) && ( this.Street2 == other.Street2 || this.Street2 != null && this.Street2.Equals(other.Street2) ) && ( this.Street3 == other.Street3 || this.Street3 != null && this.Street3.Equals(other.Street3) ) && ( this.City == other.City || this.City != null && this.City.Equals(other.City) ) && ( this.State == other.State || this.State != null && this.State.Equals(other.State) ) && ( this.Country == other.Country || this.Country != null && this.Country.Equals(other.Country) ) && ( this.ZipCode == other.ZipCode || this.ZipCode != null && this.ZipCode.Equals(other.ZipCode) ) && ( this.Phone == other.Phone || this.Phone != null && this.Phone.Equals(other.Phone) ) && ( this.Active == other.Active || this.Active != null && this.Active.Equals(other.Active) ) && ( this.CreateDate == other.CreateDate || this.CreateDate != null && this.CreateDate.Equals(other.CreateDate) ) && ( this.ModifyDate == other.ModifyDate || this.ModifyDate != null && this.ModifyDate.Equals(other.ModifyDate) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.LobId != null) hash = hash * 59 + this.LobId.GetHashCode(); if (this.Carrier != null) hash = hash * 59 + this.Carrier.GetHashCode(); if (this.AccountNo != null) hash = hash * 59 + this.AccountNo.GetHashCode(); if (this.AccountName != null) hash = hash * 59 + this.AccountName.GetHashCode(); if (this.BillingCompany != null) hash = hash * 59 + this.BillingCompany.GetHashCode(); if (this.Attention != null) hash = hash * 59 + this.Attention.GetHashCode(); if (this.Street1 != null) hash = hash * 59 + this.Street1.GetHashCode(); if (this.Street2 != null) hash = hash * 59 + this.Street2.GetHashCode(); if (this.Street3 != null) hash = hash * 59 + this.Street3.GetHashCode(); if (this.City != null) hash = hash * 59 + this.City.GetHashCode(); if (this.State != null) hash = hash * 59 + this.State.GetHashCode(); if (this.Country != null) hash = hash * 59 + this.Country.GetHashCode(); if (this.ZipCode != null) hash = hash * 59 + this.ZipCode.GetHashCode(); if (this.Phone != null) hash = hash * 59 + this.Phone.GetHashCode(); if (this.Active != null) hash = hash * 59 + this.Active.GetHashCode(); if (this.CreateDate != null) hash = hash * 59 + this.CreateDate.GetHashCode(); if (this.ModifyDate != null) hash = hash * 59 + this.ModifyDate.GetHashCode(); return hash; } } } }
// 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.Configuration.Assemblies; using System.Globalization; using Microsoft.Build.BackEnd; using System.IO; using System.Reflection; using Shouldly; using Xunit; namespace Microsoft.Build.UnitTests.BackEnd { /// <summary> /// Tests for the NodePacketTranslators /// </summary> public class BinaryTranslator_Tests { /// <summary> /// Tests the SerializationMode property /// </summary> [Fact] public void TestSerializationMode() { MemoryStream stream = new MemoryStream(); using ITranslator readTranslator = BinaryTranslator.GetReadTranslator(stream, null); Assert.Equal(TranslationDirection.ReadFromStream, readTranslator.Mode); using ITranslator writeTranslator = BinaryTranslator.GetWriteTranslator(stream); Assert.Equal(TranslationDirection.WriteToStream, writeTranslator.Mode); } /// <summary> /// Tests serializing bools. /// </summary> [Fact] public void TestSerializeBool() { HelperTestSimpleType(false, true); HelperTestSimpleType(true, false); } /// <summary> /// Tests serializing bytes. /// </summary> [Fact] public void TestSerializeByte() { byte val = 0x55; HelperTestSimpleType((byte)0, val); HelperTestSimpleType(val, (byte)0); } /// <summary> /// Tests serializing shorts. /// </summary> [Fact] public void TestSerializeShort() { short val = 0x55AA; HelperTestSimpleType((short)0, val); HelperTestSimpleType(val, (short)0); } /// <summary> /// Tests serializing longs. /// </summary> [Fact] public void TestSerializeLong() { long val = 0x55AABBCCDDEE; HelperTestSimpleType((long)0, val); HelperTestSimpleType(val, (long)0); } /// <summary> /// Tests serializing doubles. /// </summary> [Fact] public void TestSerializeDouble() { double val = 3.1416; HelperTestSimpleType((double)0, val); HelperTestSimpleType(val, (double)0); } /// <summary> /// Tests serializing TimeSpan. /// </summary> [Fact] public void TestSerializeTimeSpan() { TimeSpan val = TimeSpan.FromMilliseconds(123); HelperTestSimpleType(TimeSpan.Zero, val); HelperTestSimpleType(val, TimeSpan.Zero); } /// <summary> /// Tests serializing ints. /// </summary> [Fact] public void TestSerializeInt() { int val = 0x55AA55AA; HelperTestSimpleType((int)0, val); HelperTestSimpleType(val, (int)0); } /// <summary> /// Tests serializing strings. /// </summary> [Fact] public void TestSerializeString() { HelperTestSimpleType("foo", null); HelperTestSimpleType("", null); HelperTestSimpleType(null, null); } /// <summary> /// Tests serializing string arrays. /// </summary> [Fact] public void TestSerializeStringArray() { HelperTestArray(new string[] { }, StringComparer.Ordinal); HelperTestArray(new string[] { "foo", "bar" }, StringComparer.Ordinal); HelperTestArray(null, StringComparer.Ordinal); } /// <summary> /// Tests serializing string arrays. /// </summary> [Fact] public void TestSerializeStringList() { HelperTestList(new List<string>(), StringComparer.Ordinal); List<string> twoItems = new List<string>(2); twoItems.Add("foo"); twoItems.Add("bar"); HelperTestList(twoItems, StringComparer.Ordinal); HelperTestList(null, StringComparer.Ordinal); } /// <summary> /// Tests serializing DateTimes. /// </summary> [Fact] public void TestSerializeDateTime() { HelperTestSimpleType(new DateTime(), DateTime.Now); HelperTestSimpleType(DateTime.Now, new DateTime()); } /// <summary> /// Tests serializing enums. /// </summary> [Fact] public void TestSerializeEnum() { TranslationDirection value = TranslationDirection.ReadFromStream; TranslationHelpers.GetWriteTranslator().TranslateEnum(ref value, (int)value); TranslationDirection deserializedValue = TranslationDirection.WriteToStream; TranslationHelpers.GetReadTranslator().TranslateEnum(ref deserializedValue, (int)deserializedValue); Assert.Equal(value, deserializedValue); } /// <summary> /// Tests serializing using the DotNet serializer. /// </summary> [Fact] public void TestSerializeDotNet() { ArgumentNullException value = new ArgumentNullException("The argument was null", new InsufficientMemoryException()); TranslationHelpers.GetWriteTranslator().TranslateDotNet(ref value); ArgumentNullException deserializedValue = null; TranslationHelpers.GetReadTranslator().TranslateDotNet(ref deserializedValue); Assert.True(TranslationHelpers.CompareExceptions(value, deserializedValue)); } /// <summary> /// Tests serializing using the DotNet serializer passing in null. /// </summary> [Fact] public void TestSerializeDotNetNull() { ArgumentNullException value = null; TranslationHelpers.GetWriteTranslator().TranslateDotNet(ref value); ArgumentNullException deserializedValue = null; TranslationHelpers.GetReadTranslator().TranslateDotNet(ref deserializedValue); Assert.True(TranslationHelpers.CompareExceptions(value, deserializedValue)); } /// <summary> /// Tests serializing an object with a default constructor. /// </summary> [Fact] public void TestSerializeINodePacketSerializable() { DerivedClass value = new DerivedClass(1, 2); TranslationHelpers.GetWriteTranslator().Translate(ref value); DerivedClass deserializedValue = null; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue); Assert.Equal(value.BaseValue, deserializedValue.BaseValue); Assert.Equal(value.DerivedValue, deserializedValue.DerivedValue); } /// <summary> /// Tests serializing an object with a default constructor passed as null. /// </summary> [Fact] public void TestSerializeINodePacketSerializableNull() { DerivedClass value = null; TranslationHelpers.GetWriteTranslator().Translate(ref value); DerivedClass deserializedValue = null; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue); Assert.Equal(value, deserializedValue); } /// <summary> /// Tests serializing an object requiring a factory to construct. /// </summary> [Fact] public void TestSerializeWithFactory() { BaseClass value = new BaseClass(1); TranslationHelpers.GetWriteTranslator().Translate(ref value, BaseClass.FactoryForDeserialization); BaseClass deserializedValue = null; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue, BaseClass.FactoryForDeserialization); Assert.Equal(value.BaseValue, deserializedValue.BaseValue); } /// <summary> /// Tests serializing an object requiring a factory to construct, passing null for the value. /// </summary> [Fact] public void TestSerializeWithFactoryNull() { BaseClass value = null; TranslationHelpers.GetWriteTranslator().Translate(ref value, BaseClass.FactoryForDeserialization); BaseClass deserializedValue = null; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue, BaseClass.FactoryForDeserialization); Assert.Equal(value, deserializedValue); } /// <summary> /// Tests serializing an array of objects with default constructors. /// </summary> [Fact] public void TestSerializeArray() { DerivedClass[] value = new DerivedClass[] { new DerivedClass(1, 2), new DerivedClass(3, 4) }; TranslationHelpers.GetWriteTranslator().TranslateArray(ref value); DerivedClass[] deserializedValue = null; TranslationHelpers.GetReadTranslator().TranslateArray(ref deserializedValue); Assert.True(TranslationHelpers.CompareCollections(value, deserializedValue, DerivedClass.Comparer)); } /// <summary> /// Tests serializing an array of objects with default constructors, passing null for the array. /// </summary> [Fact] public void TestSerializeArrayNull() { DerivedClass[] value = null; TranslationHelpers.GetWriteTranslator().TranslateArray(ref value); DerivedClass[] deserializedValue = null; TranslationHelpers.GetReadTranslator().TranslateArray(ref deserializedValue); Assert.True(TranslationHelpers.CompareCollections(value, deserializedValue, DerivedClass.Comparer)); } /// <summary> /// Tests serializing an array of objects requiring factories to construct. /// </summary> [Fact] public void TestSerializeArrayWithFactory() { BaseClass[] value = new BaseClass[] { new BaseClass(1), new BaseClass(2) }; TranslationHelpers.GetWriteTranslator().TranslateArray(ref value, BaseClass.FactoryForDeserialization); BaseClass[] deserializedValue = null; TranslationHelpers.GetReadTranslator().TranslateArray(ref deserializedValue, BaseClass.FactoryForDeserialization); Assert.True(TranslationHelpers.CompareCollections(value, deserializedValue, BaseClass.Comparer)); } /// <summary> /// Tests serializing an array of objects requiring factories to construct, passing null for the array. /// </summary> [Fact] public void TestSerializeArrayWithFactoryNull() { BaseClass[] value = null; TranslationHelpers.GetWriteTranslator().TranslateArray(ref value, BaseClass.FactoryForDeserialization); BaseClass[] deserializedValue = null; TranslationHelpers.GetReadTranslator().TranslateArray(ref deserializedValue, BaseClass.FactoryForDeserialization); Assert.True(TranslationHelpers.CompareCollections(value, deserializedValue, BaseClass.Comparer)); } /// <summary> /// Tests serializing a dictionary of { string, string } /// </summary> [Fact] public void TestSerializeDictionaryStringString() { Dictionary<string, string> value = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); value["foo"] = "bar"; value["alpha"] = "omega"; TranslationHelpers.GetWriteTranslator().TranslateDictionary(ref value, StringComparer.OrdinalIgnoreCase); Dictionary<string, string> deserializedValue = null; TranslationHelpers.GetReadTranslator().TranslateDictionary(ref deserializedValue, StringComparer.OrdinalIgnoreCase); Assert.Equal(value.Count, deserializedValue.Count); Assert.Equal(value["foo"], deserializedValue["foo"]); Assert.Equal(value["alpha"], deserializedValue["alpha"]); Assert.Equal(value["FOO"], deserializedValue["FOO"]); } /// <summary> /// Tests serializing a dictionary of { string, string }, passing null. /// </summary> [Fact] public void TestSerializeDictionaryStringStringNull() { Dictionary<string, string> value = null; TranslationHelpers.GetWriteTranslator().TranslateDictionary(ref value, StringComparer.OrdinalIgnoreCase); Dictionary<string, string> deserializedValue = null; TranslationHelpers.GetReadTranslator().TranslateDictionary(ref deserializedValue, StringComparer.OrdinalIgnoreCase); Assert.Equal(value, deserializedValue); } /// <summary> /// Tests serializing a dictionary of { string, T } where T requires a factory to construct and the dictionary /// requires a KeyComparer initializer. /// </summary> [Fact] public void TestSerializeDictionaryStringT() { Dictionary<string, BaseClass> value = new Dictionary<string, BaseClass>(StringComparer.OrdinalIgnoreCase); value["foo"] = new BaseClass(1); value["alpha"] = new BaseClass(2); TranslationHelpers.GetWriteTranslator().TranslateDictionary(ref value, StringComparer.OrdinalIgnoreCase, BaseClass.FactoryForDeserialization); Dictionary<string, BaseClass> deserializedValue = null; TranslationHelpers.GetReadTranslator().TranslateDictionary(ref deserializedValue, StringComparer.OrdinalIgnoreCase, BaseClass.FactoryForDeserialization); Assert.Equal(value.Count, deserializedValue.Count); Assert.Equal(0, BaseClass.Comparer.Compare(value["foo"], deserializedValue["foo"])); Assert.Equal(0, BaseClass.Comparer.Compare(value["alpha"], deserializedValue["alpha"])); Assert.Equal(0, BaseClass.Comparer.Compare(value["FOO"], deserializedValue["FOO"])); } /// <summary> /// Tests serializing a dictionary of { string, T } where T requires a factory to construct and the dictionary /// requires a KeyComparer initializer, passing null for the dictionary. /// </summary> [Fact] public void TestSerializeDictionaryStringTNull() { Dictionary<string, BaseClass> value = null; TranslationHelpers.GetWriteTranslator().TranslateDictionary(ref value, StringComparer.OrdinalIgnoreCase, BaseClass.FactoryForDeserialization); Dictionary<string, BaseClass> deserializedValue = null; TranslationHelpers.GetReadTranslator().TranslateDictionary(ref deserializedValue, StringComparer.OrdinalIgnoreCase, BaseClass.FactoryForDeserialization); Assert.Equal(value, deserializedValue); } /// <summary> /// Tests serializing a dictionary of { string, T } where T requires a factory to construct and the dictionary /// has a default constructor. /// </summary> [Fact] public void TestSerializeDictionaryStringTNoComparer() { Dictionary<string, BaseClass> value = new Dictionary<string, BaseClass>(); value["foo"] = new BaseClass(1); value["alpha"] = new BaseClass(2); TranslationHelpers.GetWriteTranslator().TranslateDictionary<Dictionary<string, BaseClass>, BaseClass>(ref value, BaseClass.FactoryForDeserialization); Dictionary<string, BaseClass> deserializedValue = null; TranslationHelpers.GetReadTranslator().TranslateDictionary<Dictionary<string, BaseClass>, BaseClass>(ref deserializedValue, BaseClass.FactoryForDeserialization); Assert.Equal(value.Count, deserializedValue.Count); Assert.Equal(0, BaseClass.Comparer.Compare(value["foo"], deserializedValue["foo"])); Assert.Equal(0, BaseClass.Comparer.Compare(value["alpha"], deserializedValue["alpha"])); Assert.False(deserializedValue.ContainsKey("FOO")); } /// <summary> /// Tests serializing a dictionary of { string, T } where T requires a factory to construct and the dictionary /// has a default constructor, passing null for the dictionary. /// </summary> [Fact] public void TestSerializeDictionaryStringTNoComparerNull() { Dictionary<string, BaseClass> value = null; TranslationHelpers.GetWriteTranslator().TranslateDictionary<Dictionary<string, BaseClass>, BaseClass>(ref value, BaseClass.FactoryForDeserialization); Dictionary<string, BaseClass> deserializedValue = null; TranslationHelpers.GetReadTranslator().TranslateDictionary<Dictionary<string, BaseClass>, BaseClass>(ref deserializedValue, BaseClass.FactoryForDeserialization); Assert.Equal(value, deserializedValue); } [Theory] [InlineData("en")] [InlineData("en-US")] [InlineData("en-CA")] [InlineData("zh-HK")] [InlineData("sr-Cyrl-CS")] public void CultureInfo(string name) { CultureInfo value = new CultureInfo(name); TranslationHelpers.GetWriteTranslator().Translate(ref value); CultureInfo deserializedValue = null; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue); deserializedValue.ShouldBe(value); } [Fact] public void CultureInfoAsNull() { CultureInfo value = null; TranslationHelpers.GetWriteTranslator().Translate(ref value); CultureInfo deserializedValue = null; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue); deserializedValue.ShouldBeNull(); } [Theory] [InlineData("1.2")] [InlineData("1.2.3")] [InlineData("1.2.3.4")] public void Version(string version) { Version value = new Version(version); TranslationHelpers.GetWriteTranslator().Translate(ref value); Version deserializedValue = null; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue); deserializedValue.ShouldBe(value); } [Fact] public void VersionAsNull() { Version value = null; TranslationHelpers.GetWriteTranslator().Translate(ref value); Version deserializedValue = null; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue); deserializedValue.ShouldBeNull(); } [Fact] public void HashSetOfT() { HashSet<BaseClass> values = new() { new BaseClass(1), new BaseClass(2), null }; TranslationHelpers.GetWriteTranslator().TranslateHashSet(ref values, BaseClass.FactoryForDeserialization, capacity => new()); HashSet<BaseClass> deserializedValues = null; TranslationHelpers.GetReadTranslator().TranslateHashSet(ref deserializedValues, BaseClass.FactoryForDeserialization, capacity => new()); deserializedValues.ShouldBe(values, ignoreOrder: true); } [Fact] public void HashSetOfTAsNull() { HashSet<BaseClass> value = null; TranslationHelpers.GetWriteTranslator().TranslateHashSet(ref value, BaseClass.FactoryForDeserialization, capacity => new()); HashSet<BaseClass> deserializedValue = null; TranslationHelpers.GetReadTranslator().TranslateHashSet(ref deserializedValue, BaseClass.FactoryForDeserialization, capacity => new()); deserializedValue.ShouldBeNull(); } [Fact] public void AssemblyNameAsNull() { AssemblyName value = null; TranslationHelpers.GetWriteTranslator().Translate(ref value); AssemblyName deserializedValue = null; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue); deserializedValue.ShouldBeNull(); } [Fact] public void AssemblyNameWithAllFields() { AssemblyName value = new() { Name = "a", Version = new Version(1, 2, 3), Flags = AssemblyNameFlags.PublicKey, ProcessorArchitecture = ProcessorArchitecture.X86, CultureInfo = new CultureInfo("zh-HK"), HashAlgorithm = System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA256, VersionCompatibility = AssemblyVersionCompatibility.SameMachine, CodeBase = "C:\\src", ContentType = AssemblyContentType.WindowsRuntime, CultureName = "zh-HK", }; value.SetPublicKey(new byte[]{ 3, 2, 1}); value.SetPublicKeyToken(new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 }); TranslationHelpers.GetWriteTranslator().Translate(ref value); AssemblyName deserializedValue = null; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue); HelperAssertAssemblyNameEqual(value, deserializedValue); } [Fact] public void AssemblyNameWithMinimalFields() { AssemblyName value = new(); TranslationHelpers.GetWriteTranslator().Translate(ref value); AssemblyName deserializedValue = null; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue); HelperAssertAssemblyNameEqual(value, deserializedValue); } /// <summary> /// Assert two AssemblyName objects values are same. /// Ignoring KeyPair, ContentType, CultureName as those are not serialized /// </summary> private static void HelperAssertAssemblyNameEqual(AssemblyName expected, AssemblyName actual) { actual.Name.ShouldBe(expected.Name); actual.Version.ShouldBe(expected.Version); actual.Flags.ShouldBe(expected.Flags); actual.ProcessorArchitecture.ShouldBe(expected.ProcessorArchitecture); actual.CultureInfo.ShouldBe(expected.CultureInfo); actual.HashAlgorithm.ShouldBe(expected.HashAlgorithm); actual.VersionCompatibility.ShouldBe(expected.VersionCompatibility); actual.CodeBase.ShouldBe(expected.CodeBase); actual.GetPublicKey().ShouldBe(expected.GetPublicKey()); actual.GetPublicKeyToken().ShouldBe(expected.GetPublicKeyToken()); } /// <summary> /// Helper for bool serialization. /// </summary> private void HelperTestSimpleType(bool initialValue, bool deserializedInitialValue) { bool value = initialValue; TranslationHelpers.GetWriteTranslator().Translate(ref value); bool deserializedValue = deserializedInitialValue; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue); Assert.Equal(value, deserializedValue); } /// <summary> /// Helper for long serialization. /// </summary> private void HelperTestSimpleType(long initialValue, long deserializedInitialValue) { long value = initialValue; TranslationHelpers.GetWriteTranslator().Translate(ref value); long deserializedValue = deserializedInitialValue; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue); Assert.Equal(value, deserializedValue); } /// <summary> /// Helper for double serialization. /// </summary> private void HelperTestSimpleType(double initialValue, double deserializedInitialValue) { double value = initialValue; TranslationHelpers.GetWriteTranslator().Translate(ref value); double deserializedValue = deserializedInitialValue; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue); Assert.Equal(value, deserializedValue); } /// <summary> /// Helper for TimeSpan serialization. /// </summary> private void HelperTestSimpleType(TimeSpan initialValue, TimeSpan deserializedInitialValue) { TimeSpan value = initialValue; TranslationHelpers.GetWriteTranslator().Translate(ref value); TimeSpan deserializedValue = deserializedInitialValue; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue); Assert.Equal(value, deserializedValue); } /// <summary> /// Helper for byte serialization. /// </summary> private void HelperTestSimpleType(byte initialValue, byte deserializedInitialValue) { byte value = initialValue; TranslationHelpers.GetWriteTranslator().Translate(ref value); byte deserializedValue = deserializedInitialValue; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue); Assert.Equal(value, deserializedValue); } /// <summary> /// Helper for short serialization. /// </summary> private void HelperTestSimpleType(short initialValue, short deserializedInitialValue) { short value = initialValue; TranslationHelpers.GetWriteTranslator().Translate(ref value); short deserializedValue = deserializedInitialValue; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue); Assert.Equal(value, deserializedValue); } /// <summary> /// Helper for int serialization. /// </summary> private void HelperTestSimpleType(int initialValue, int deserializedInitialValue) { int value = initialValue; TranslationHelpers.GetWriteTranslator().Translate(ref value); int deserializedValue = deserializedInitialValue; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue); Assert.Equal(value, deserializedValue); } /// <summary> /// Helper for string serialization. /// </summary> private void HelperTestSimpleType(string initialValue, string deserializedInitialValue) { string value = initialValue; TranslationHelpers.GetWriteTranslator().Translate(ref value); string deserializedValue = deserializedInitialValue; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue); Assert.Equal(value, deserializedValue); } /// <summary> /// Helper for DateTime serialization. /// </summary> private void HelperTestSimpleType(DateTime initialValue, DateTime deserializedInitialValue) { DateTime value = initialValue; TranslationHelpers.GetWriteTranslator().Translate(ref value); DateTime deserializedValue = deserializedInitialValue; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue); Assert.Equal(value, deserializedValue); } /// <summary> /// Helper for array serialization. /// </summary> private void HelperTestArray(string[] initialValue, IComparer<string> comparer) { string[] value = initialValue; TranslationHelpers.GetWriteTranslator().Translate(ref value); string[] deserializedValue = null; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue); Assert.True(TranslationHelpers.CompareCollections(value, deserializedValue, comparer)); } /// <summary> /// Helper for list serialization. /// </summary> private void HelperTestList(List<string> initialValue, IComparer<string> comparer) { List<string> value = initialValue; TranslationHelpers.GetWriteTranslator().Translate(ref value); List<string> deserializedValue = null; TranslationHelpers.GetReadTranslator().Translate(ref deserializedValue); Assert.True(TranslationHelpers.CompareCollections(value, deserializedValue, comparer)); } /// <summary> /// Base class for testing /// </summary> private class BaseClass : ITranslatable { /// <summary> /// A field. /// </summary> private int _baseValue; /// <summary> /// Constructor with value. /// </summary> public BaseClass(int val) { _baseValue = val; } /// <summary> /// Constructor /// </summary> protected BaseClass() { } protected bool Equals(BaseClass other) { return _baseValue == other._baseValue; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((BaseClass) obj); } public override int GetHashCode() { return _baseValue; } /// <summary> /// Gets a comparer. /// </summary> static public IComparer<BaseClass> Comparer { get { return new BaseClassComparer(); } } /// <summary> /// Gets the value. /// </summary> public int BaseValue { get { return _baseValue; } } #region INodePacketTranslatable Members /// <summary> /// Factory for serialization. /// </summary> public static BaseClass FactoryForDeserialization(ITranslator translator) { BaseClass packet = new BaseClass(); packet.Translate(translator); return packet; } /// <summary> /// Serializes the class. /// </summary> public virtual void Translate(ITranslator translator) { translator.Translate(ref _baseValue); } #endregion /// <summary> /// Comparer for BaseClass. /// </summary> private class BaseClassComparer : IComparer<BaseClass> { /// <summary> /// Constructor. /// </summary> public BaseClassComparer() { } #region IComparer<BaseClass> Members /// <summary> /// Compare two BaseClass objects. /// </summary> public int Compare(BaseClass x, BaseClass y) { if (x._baseValue == y._baseValue) { return 0; } return -1; } #endregion } } /// <summary> /// Derived class for testing. /// </summary> private class DerivedClass : BaseClass { /// <summary> /// A field. /// </summary> private int _derivedValue; /// <summary> /// Default constructor. /// </summary> public DerivedClass() { } /// <summary> /// Constructor taking two values. /// </summary> public DerivedClass(int derivedValue, int baseValue) : base(baseValue) { _derivedValue = derivedValue; } /// <summary> /// Gets a comparer. /// </summary> static new public IComparer<DerivedClass> Comparer { get { return new DerivedClassComparer(); } } /// <summary> /// Returns the value. /// </summary> public int DerivedValue { get { return _derivedValue; } } #region INodePacketTranslatable Members /// <summary> /// Serializes the class. /// </summary> public override void Translate(ITranslator translator) { base.Translate(translator); translator.Translate(ref _derivedValue); } #endregion /// <summary> /// Comparer for DerivedClass. /// </summary> private class DerivedClassComparer : IComparer<DerivedClass> { /// <summary> /// Constructor /// </summary> public DerivedClassComparer() { } #region IComparer<DerivedClass> Members /// <summary> /// Compares two DerivedClass objects. /// </summary> public int Compare(DerivedClass x, DerivedClass y) { if (x._derivedValue == y._derivedValue) { return BaseClass.Comparer.Compare(x, y); } return -1; } #endregion } } } }