context
stringlengths
2.52k
185k
gt
stringclasses
1 value
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 Wallet.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; } } }
// // MenuItemBackend.cs // // Author: // Lluis Sanchez <[email protected]> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using AppKit; using Xwt.Backends; namespace Xwt.Mac { public class MenuItemBackend : IMenuItemBackend { NSMenuItem item; IMenuItemEventSink eventSink; List<MenuItemEvent> enabledEvents; ApplicationContext context; string label; bool useMnemonic; private NSEventModifierMask GetModifierMask(KeyShortcut accel) { NSEventModifierMask mask = default(NSEventModifierMask); if(accel.Modifiers.HasFlag(KeyboardKeyModifiers.Command)) { mask |= NSEventModifierMask.CommandKeyMask; } if(accel.Modifiers.HasFlag(KeyboardKeyModifiers.Shift)) { mask |= NSEventModifierMask.ShiftKeyMask; } if(accel.Modifiers.HasFlag(KeyboardKeyModifiers.Alt)) { mask |= NSEventModifierMask.AlternateKeyMask; } if(accel.Modifiers.HasFlag(KeyboardKeyModifiers.Control)) { mask |= NSEventModifierMask.ControlKeyMask; } return mask; } private KeyShortcut shortcut; public KeyShortcut Shortcut { get { return shortcut; } set { shortcut = value; if(value.Modifiers.HasFlag(KeyboardKeyModifiers.Shift)) { item.KeyEquivalent = value.Key.MacMenuCharacter.ToString(); } else { item.KeyEquivalent = value.Key.MacMenuCharacter.ToString().ToLower(); } item.KeyEquivalentModifierMask = GetModifierMask(value); } } public MenuItemBackend (): this (new NSMenuItem ()) { } public MenuItemBackend(NSMenuItem item) { this.item = item; } public NSMenuItem Item { get { return item; } } public void Initialize(IMenuItemEventSink eventSink) { this.eventSink = eventSink; } public void SetSubmenu(IMenuBackend menu) { if (menu == null) item.Submenu = null; else item.Submenu = ((MenuBackend)menu); } public string Label { get { return label; } set { item.Title = UseMnemonic ? value.RemoveMnemonic() : value; label = value; } } public string TooltipText { get { return item.ToolTip; } set { item.ToolTip = value; } } public bool UseMnemonic { get { return useMnemonic; } set { useMnemonic = value; Label = label ?? string.Empty; } } public void SetImage(ImageDescription image) { item.Image = image.ToNSImage(); } public bool Visible { get { return !item.Hidden; } set { item.Hidden = !value; } } public bool IsSubMenuOpen { get { // sorry - can't do this on macOS - listen to the opened/closed events instead (they don't work properly on Windows, but this function does, which is why it exists) throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public bool Sensitive { get { return item.Enabled; } set { item.Enabled = value; } } public bool Checked { get { return item.State == NSCellStateValue.On; } set { if (value) item.State = NSCellStateValue.On; else item.State = NSCellStateValue.Off; } } public string ToolTip { get { return item.ToolTip; } set { item.ToolTip = value; } } #region IBackend implementation public void InitializeBackend(object frontend, ApplicationContext context) { this.context = context; } public void EnableEvent(object eventId) { if (eventId is MenuItemEvent) { if (enabledEvents == null) enabledEvents = new List<MenuItemEvent>(); enabledEvents.Add((MenuItemEvent)eventId); if ((MenuItemEvent)eventId == MenuItemEvent.Clicked) item.Activated += HandleItemActivated; } } public void DisableEvent(object eventId) { if (eventId is MenuItemEvent) { enabledEvents.Remove((MenuItemEvent)eventId); if ((MenuItemEvent)eventId == MenuItemEvent.Clicked) item.Activated -= HandleItemActivated; } } #endregion void HandleItemActivated(object sender, EventArgs e) { context.InvokeUserCode(delegate { eventSink.OnClicked(); }); } } }
using System; using System.Globalization; using System.Text; using Raksha.Utilities; namespace Raksha.Asn1 { /** * UTC time object. */ public class DerUtcTime : Asn1Object { private readonly string time; /** * return an UTC Time from the passed in object. * * @exception ArgumentException if the object cannot be converted. */ public static DerUtcTime GetInstance( object obj) { if (obj == null || obj is DerUtcTime) { return (DerUtcTime)obj; } throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name); } /** * return an UTC Time from a tagged object. * * @param obj the tagged object holding the object we want * @param explicitly true if the object is meant to be explicitly * tagged false otherwise. * @exception ArgumentException if the tagged object cannot * be converted. */ public static DerUtcTime GetInstance( Asn1TaggedObject obj, bool isExplicit) { Asn1Object o = obj.GetObject(); if (isExplicit || o is DerUtcTime) { return GetInstance(o); } return new DerUtcTime(((Asn1OctetString)o).GetOctets()); } /** * The correct format for this is YYMMDDHHMMSSZ (it used to be that seconds were * never encoded. When you're creating one of these objects from scratch, that's * what you want to use, otherwise we'll try to deal with whatever Gets read from * the input stream... (this is why the input format is different from the GetTime() * method output). * <p> * @param time the time string.</p> */ public DerUtcTime( string time) { if (time == null) throw new ArgumentNullException("time"); this.time = time; try { ToDateTime(); } catch (FormatException e) { throw new ArgumentException("invalid date string: " + e.Message); } } /** * base constructor from a DateTime object */ public DerUtcTime( DateTime time) { this.time = time.ToString("yyMMddHHmmss") + "Z"; } internal DerUtcTime( byte[] bytes) { // // explicitly convert to characters // this.time = Strings.FromAsciiByteArray(bytes); } // public DateTime ToDateTime() // { // string tm = this.AdjustedTimeString; // // return new DateTime( // Int16.Parse(tm.Substring(0, 4)), // Int16.Parse(tm.Substring(4, 2)), // Int16.Parse(tm.Substring(6, 2)), // Int16.Parse(tm.Substring(8, 2)), // Int16.Parse(tm.Substring(10, 2)), // Int16.Parse(tm.Substring(12, 2))); // } /** * return the time as a date based on whatever a 2 digit year will return. For * standardised processing use ToAdjustedDateTime(). * * @return the resulting date * @exception ParseException if the date string cannot be parsed. */ public DateTime ToDateTime() { return ParseDateString(TimeString, @"yyMMddHHmmss'GMT'zzz"); } /** * return the time as an adjusted date * in the range of 1950 - 2049. * * @return a date in the range of 1950 to 2049. * @exception ParseException if the date string cannot be parsed. */ public DateTime ToAdjustedDateTime() { return ParseDateString(AdjustedTimeString, @"yyyyMMddHHmmss'GMT'zzz"); } private DateTime ParseDateString( string dateStr, string formatStr) { DateTime dt = DateTime.ParseExact( dateStr, formatStr, DateTimeFormatInfo.InvariantInfo); return dt.ToUniversalTime(); } /** * return the time - always in the form of * YYMMDDhhmmssGMT(+hh:mm|-hh:mm). * <p> * Normally in a certificate we would expect "Z" rather than "GMT", * however adding the "GMT" means we can just use: * <pre> * dateF = new SimpleDateFormat("yyMMddHHmmssz"); * </pre> * To read in the time and Get a date which is compatible with our local * time zone.</p> * <p> * <b>Note:</b> In some cases, due to the local date processing, this * may lead to unexpected results. If you want to stick the normal * convention of 1950 to 2049 use the GetAdjustedTime() method.</p> */ public string TimeString { get { // // standardise the format. // if (time.IndexOf('-') < 0 && time.IndexOf('+') < 0) { if (time.Length == 11) { return time.Substring(0, 10) + "00GMT+00:00"; } else { return time.Substring(0, 12) + "GMT+00:00"; } } else { int index = time.IndexOf('-'); if (index < 0) { index = time.IndexOf('+'); } string d = time; if (index == time.Length - 3) { d += "00"; } if (index == 10) { return d.Substring(0, 10) + "00GMT" + d.Substring(10, 3) + ":" + d.Substring(13, 2); } else { return d.Substring(0, 12) + "GMT" + d.Substring(12, 3) + ":" + d.Substring(15, 2); } } } } [Obsolete("Use 'AdjustedTimeString' property instead")] public string AdjustedTime { get { return AdjustedTimeString; } } /// <summary> /// Return a time string as an adjusted date with a 4 digit year. /// This goes in the range of 1950 - 2049. /// </summary> public string AdjustedTimeString { get { string d = TimeString; string c = d[0] < '5' ? "20" : "19"; return c + d; } } private byte[] GetOctets() { return Strings.ToAsciiByteArray(time); } internal override void Encode( DerOutputStream derOut) { derOut.WriteEncoded(Asn1Tags.UtcTime, GetOctets()); } protected override bool Asn1Equals( Asn1Object asn1Object) { DerUtcTime other = asn1Object as DerUtcTime; if (other == null) return false; return this.time.Equals(other.time); } protected override int Asn1GetHashCode() { return time.GetHashCode(); } public override string ToString() { return time; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Configuration; using Orleans.GrainDirectory; using Orleans.SystemTargetInterfaces; using Orleans.Runtime.Scheduler; using OutcomeState = Orleans.Runtime.GrainDirectory.GlobalSingleInstanceResponseOutcome.OutcomeState; using Orleans.Runtime.MultiClusterNetwork; using Orleans.MultiCluster; using System.Threading; using Orleans.Internal; namespace Orleans.Runtime.GrainDirectory { internal class GlobalSingleInstanceActivationMaintainer : DedicatedAsynchAgent, IMultiClusterConfigurationListener { private readonly object lockable = new object(); private readonly LocalGrainDirectory router; private readonly ILogger logger; private readonly IInternalGrainFactory grainFactory; private readonly TimeSpan period; private readonly IMultiClusterOracle multiClusterOracle; private readonly ILocalSiloDetails siloDetails; private readonly MultiClusterOptions multiClusterOptions; private readonly RegistrarManager registrarManager; // scanning the entire directory for doubtful activations is too slow. // therefore, we maintain a list of potentially doubtful activations on the side. // maintainer periodically takes and processes this list. private List<GrainId> doubtfulGrains = new List<GrainId>(); // used to cut short the waiting time before next run private ManualResetEvent runNow = new ManualResetEvent(false); public GlobalSingleInstanceActivationMaintainer( LocalGrainDirectory router, ILogger logger, IInternalGrainFactory grainFactory, IMultiClusterOracle multiClusterOracle, ExecutorService executorService, ILocalSiloDetails siloDetails, IOptions<MultiClusterOptions> multiClusterOptions, ILoggerFactory loggerFactory, RegistrarManager registrarManager) : base(executorService, loggerFactory) { this.router = router; this.logger = logger; this.grainFactory = grainFactory; this.multiClusterOracle = multiClusterOracle; this.siloDetails = siloDetails; this.multiClusterOptions = multiClusterOptions.Value; this.period = multiClusterOptions.Value.GlobalSingleInstanceRetryInterval; this.registrarManager = registrarManager; multiClusterOracle.SubscribeToMultiClusterConfigurationEvents(this); logger.Debug("GSIP:M GlobalSingleInstanceActivationMaintainer Started, Period = {0}", period); } public void TrackDoubtfulGrain(GrainId grain) { lock (lockable) doubtfulGrains.Add(grain); } public void TrackDoubtfulGrains(Dictionary<GrainId, IGrainInfo> newstuff) { var newdoubtful = FilterByMultiClusterStatus(newstuff, GrainDirectoryEntryStatus.Doubtful) .Select(kvp => kvp.Key) .ToList(); lock (lockable) { doubtfulGrains.AddRange(newdoubtful); } } public static IEnumerable<KeyValuePair<GrainId, IGrainInfo>> FilterByMultiClusterStatus(Dictionary<GrainId, IGrainInfo> collection, GrainDirectoryEntryStatus status) { foreach (var kvp in collection) { if (!kvp.Value.SingleInstance) continue; var act = kvp.Value.Instances.FirstOrDefault(); if (act.Key == null) continue; if (act.Value.RegistrationStatus == status) yield return kvp; } } // the following method runs for the whole lifetime of the silo, doing the periodic maintenance protected override void Run() { if (!this.multiClusterOptions.HasMultiClusterNetwork) return; var myClusterId = this.siloDetails.ClusterId; Cts.Token.Register(this.Prod); while (router.Running && !Cts.IsCancellationRequested) { try { // wait until it is time, or someone prodded us to continue runNow.WaitOne(period); runNow.Reset(); if (!router.Running || Cts.IsCancellationRequested) break; logger.Debug("GSIP:M running check"); // examine the multicluster configuration var multiClusterConfig = this.multiClusterOracle.GetMultiClusterConfiguration(); if (multiClusterConfig == null || !multiClusterConfig.Clusters.Contains(myClusterId)) { // we are not joined to the cluster yet/anymore. // go through all owned entries and make them doubtful // this will not happen under normal operation // (because nodes are supposed to shut down before being removed from the multi cluster) // but if it happens anyway, this is the correct thing to do var allEntries = router.DirectoryPartition.GetItems(); var ownedEntries = FilterByMultiClusterStatus(allEntries, GrainDirectoryEntryStatus.Owned) .Select(kp => Tuple.Create(kp.Key, kp.Value.Instances.FirstOrDefault())) .ToList(); logger.Debug("GSIP:M Not joined to multicluster. Make {0} owned entries doubtful {1}", ownedEntries.Count, logger.IsEnabled(LogLevel.Trace) ? string.Join(",", ownedEntries.Select(s => s.Item1)) : ""); router.Scheduler.QueueTask( () => RunBatchedDemotion(ownedEntries), router.CacheValidator.SchedulingContext ).Wait(); } else { // we are joined to the multicluster. List<KeyValuePair<string, SiloAddress>> remoteClusters = multiClusterConfig.Clusters .Where(id => id != myClusterId) .Select(id => new KeyValuePair<string, SiloAddress>(id, this.multiClusterOracle.GetRandomClusterGateway(id))) .ToList(); // validate entries that point to remote clusters router.Scheduler.QueueTask( () => RunBatchedValidation(), router.CacheValidator.SchedulingContext ).Wait(); if (!remoteClusters.Any(kvp => kvp.Value == null)) { // all clusters have at least one gateway reporting. // go through all doubtful entries and broadcast ownership requests for each List<GrainId> grains; lock (lockable) { grains = doubtfulGrains; doubtfulGrains = new List<GrainId>(); } logger.Debug("GSIP:M retry {0} doubtful entries {1}", grains.Count, logger.IsEnabled(LogLevel.Trace) ? string.Join(",", grains) : ""); router.Scheduler.QueueTask( () => RunBatchedActivationRequests(remoteClusters, grains), router.CacheValidator.SchedulingContext ).Wait(); } } } catch (Exception e) { logger.Error(ErrorCode.GlobalSingleInstance_MaintainerException, "GSIP:M caught exception", e); } } } private Task RunBatchedDemotion(List<Tuple<GrainId, KeyValuePair<ActivationId, IActivationInfo>>> entries) { foreach (var entry in entries) { router.DirectoryPartition.UpdateClusterRegistrationStatus(entry.Item1, entry.Item2.Key, GrainDirectoryEntryStatus.Doubtful, GrainDirectoryEntryStatus.Owned); TrackDoubtfulGrain(entry.Item1); } return Task.CompletedTask; } private Task RunBatchedValidation() { // organize remote references by silo var allEntries = router.DirectoryPartition.GetItems(); var cachedEntries = FilterByMultiClusterStatus(allEntries, GrainDirectoryEntryStatus.Cached).ToList(); var entriesBySilo = new Dictionary<SiloAddress, List<KeyValuePair<GrainId, IGrainInfo>>>(); logger.Debug("GSIP:M validating {count} cache entries", cachedEntries.Count); foreach (var entry in cachedEntries) { var silo = entry.Value.Instances.FirstOrDefault().Value.SiloAddress; if (!entriesBySilo.TryGetValue(silo, out var list)) { list = entriesBySilo[silo] = new List<KeyValuePair<GrainId, IGrainInfo>>(); } list.Add(entry); } // process by silo var tasks = new List<Task>(); foreach (var kvp in entriesBySilo) { tasks.Add(RunBatchedValidation(kvp.Key, kvp.Value)); } return Task.WhenAll(tasks); } private async Task RunBatchedValidation(SiloAddress silo, List<KeyValuePair<GrainId, IGrainInfo>> list) { var multiClusterConfig = this.multiClusterOracle.GetMultiClusterConfiguration(); string clusterId = null; // If this silo is a part of a multi-cluster, try to find out which cluster the target silo belongs to. // The check here is a simple ping used to check if the remote silo is available and, if so, which cluster // it belongs to. // This is a used to determine whether or not the local silo should invalidate directory cache entries // pointing to the remote silo. // A preferable approach would be to flow cluster membership or grain directory information from the remote // cluster to the local one. That would avoid heuristic checks such as this. Additionally, information // about which cluster a particular silo belongs (or belonged) to could be maintained. That would allow // us to skip this first step. if (multiClusterConfig != null) { try { var validator = this.grainFactory.GetSystemTarget<IClusterGrainDirectory>( Constants.ClusterDirectoryServiceId, silo); clusterId = await validator.Ping(); } catch (Exception exception) { // A failure here may indicate a transient error, but for simplicity we will continue as though // the remote silo is no longer a part of the multi-cluster. this.logger.LogWarning("Failed to ping remote silo {Silo}: {Exception}", silo, exception); } } // if the silo could not be contacted or is not part of the multicluster, unregister if (clusterId == null || !multiClusterConfig.Clusters.Contains(clusterId)) { this.logger.Debug("GSIP:M removing {Count} cache entries pointing to {Silo}", list.Count, silo); var registrar = this.registrarManager.GetRegistrar(GlobalSingleInstanceRegistration.Singleton); foreach (var kvp in list) { registrar.InvalidateCache(ActivationAddress.GetAddress(silo, kvp.Key, kvp.Value.Instances.FirstOrDefault().Key)); } } } private async Task RunBatchedActivationRequests(List<KeyValuePair<string, SiloAddress>> remoteClusters, List<GrainId> grains) { var addresses = new List<ActivationAddress>(); foreach (var grain in grains) { // retrieve activation ActivationAddress address; int version; var mcstate = router.DirectoryPartition.TryGetActivation(grain, out address, out version); // work on the doubtful ones only if (mcstate == GrainDirectoryEntryStatus.Doubtful) { // try to start retry by moving into requested_ownership state if (router.DirectoryPartition.UpdateClusterRegistrationStatus(grain, address.Activation, GrainDirectoryEntryStatus.RequestedOwnership, GrainDirectoryEntryStatus.Doubtful)) { addresses.Add(address); } } } if (addresses.Count == 0) return; var batchResponses = new List<RemoteClusterActivationResponse[]>(); var tasks = remoteClusters.Select(async remotecluster => { // find gateway and send batched request try { var clusterGrainDir = this.grainFactory.GetSystemTarget<IClusterGrainDirectory>(Constants.ClusterDirectoryServiceId, remotecluster.Value); var r = await clusterGrainDir.ProcessActivationRequestBatch(addresses.Select(a => a.Grain).ToArray(), this.siloDetails.ClusterId).WithCancellation(Cts.Token); batchResponses.Add(r); } catch (Exception e) { batchResponses.Add( Enumerable.Repeat<RemoteClusterActivationResponse>( new RemoteClusterActivationResponse(ActivationResponseStatus.Faulted) { ResponseException = e }, addresses.Count).ToArray()); } }).ToList(); // wait for all the responses to arrive or fail await Task.WhenAll(tasks); if (logger.IsEnabled(LogLevel.Debug)) { foreach (var br in batchResponses) { var summary = br.Aggregate(new { Pass = 0, Failed = 0, FailedA = 0, FailedOwned = 0, Faulted = 0 }, (agg, r) => { switch (r.ResponseStatus) { case ActivationResponseStatus.Pass: return new { Pass = agg.Pass + 1, agg.Failed, agg.FailedA, agg.FailedOwned, agg.Faulted }; case ActivationResponseStatus.Failed: if (!r.Owned) { return r.ExistingActivationAddress.Address == null ? new { agg.Pass, Failed = agg.Failed + 1, agg.FailedA, agg.FailedOwned, agg.Faulted } : new { agg.Pass, agg.Failed, FailedA = agg.FailedA + 1, agg.FailedOwned, agg.Faulted }; } else { return new { agg.Pass, agg.Failed, agg.FailedA, FailedOwned = agg.FailedOwned + 1, agg.Faulted }; } default: return new { agg.Pass, agg.Failed, agg.FailedA, agg.FailedOwned, Faulted = agg.Faulted + 1 }; } }); logger.Debug("GSIP:M batchresponse PASS:{0} FAILED:{1} FAILED(a){2}: FAILED(o){3}: FAULTED:{4}", summary.Pass, summary.Failed, summary.FailedA, summary.FailedOwned, summary.Faulted); } } // process each address var loser_activations_per_silo = new Dictionary<SiloAddress, List<ActivationAddress>>(); for (int i = 0; i < addresses.Count; i++) { var address = addresses[i]; // array that holds the responses var responses = new RemoteClusterActivationResponse[remoteClusters.Count]; for (int j = 0; j < batchResponses.Count; j++) responses[j] = batchResponses[j][i]; // response processor var outcomeDetails = GlobalSingleInstanceResponseTracker.GetOutcome(responses, address.Grain, logger); var outcome = outcomeDetails.State; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("GSIP:M {0} Result={1}", address.Grain, outcomeDetails); switch (outcome) { case OutcomeState.RemoteOwner: case OutcomeState.RemoteOwnerLikely: { // record activations that lost and need to be deactivated List<ActivationAddress> losers; if (!loser_activations_per_silo.TryGetValue(address.Silo, out losers)) loser_activations_per_silo[address.Silo] = losers = new List<ActivationAddress>(); losers.Add(address); router.DirectoryPartition.CacheOrUpdateRemoteClusterRegistration(address.Grain, address.Activation, outcomeDetails.RemoteOwnerAddress.Address); continue; } case OutcomeState.Succeed: { var ok = (router.DirectoryPartition.UpdateClusterRegistrationStatus(address.Grain, address.Activation, GrainDirectoryEntryStatus.Owned, GrainDirectoryEntryStatus.RequestedOwnership)); if (ok) continue; else break; } case OutcomeState.Inconclusive: { break; } } // we were not successful, reread state to determine what is going on int version; var mcstatus = router.DirectoryPartition.TryGetActivation(address.Grain, out address, out version); // in each case, go back to DOUBTFUL if (mcstatus == GrainDirectoryEntryStatus.RequestedOwnership) { // we failed because of inconclusive answers var success = router.DirectoryPartition.UpdateClusterRegistrationStatus(address.Grain, address.Activation, GrainDirectoryEntryStatus.Doubtful, GrainDirectoryEntryStatus.RequestedOwnership); if (!success) ProtocolError(address, "unable to transition from REQUESTED_OWNERSHIP to DOUBTFUL"); } else if (mcstatus == GrainDirectoryEntryStatus.RaceLoser) { // we failed because an external request moved us to RACE_LOSER var success = router.DirectoryPartition.UpdateClusterRegistrationStatus(address.Grain, address.Activation, GrainDirectoryEntryStatus.Doubtful, GrainDirectoryEntryStatus.RaceLoser); if (!success) ProtocolError(address, "unable to transition from RACE_LOSER to DOUBTFUL"); } else { ProtocolError(address, "unhandled protocol state"); } TrackDoubtfulGrain(address.Grain); } // remove loser activations foreach (var kvp in loser_activations_per_silo) { var catalog = this.grainFactory.GetSystemTarget<ICatalog>(Constants.CatalogId, kvp.Key); catalog.DeleteActivations(kvp.Value).Ignore(); } } private void ProtocolError(ActivationAddress address, string msg) { logger.Error((int) ErrorCode.GlobalSingleInstance_ProtocolError, string.Format("GSIP:Req {0} {1}", address.Grain.ToString(), msg)); } public void OnMultiClusterConfigurationChange(MultiClusterConfiguration next) { logger.Debug($"GSIP:M MultiClusterConfiguration {next}"); Prod(); } public void Prod() { // cancel the waiting, to proceed immediately runNow.Set(); } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Core.Objects; using System.Data.Entity.Infrastructure; using System.Threading.Tasks; using System.Transactions; using Abp.Dependency; using Abp.Domain.Uow; using Abp.EntityFramework.Utils; using Abp.MultiTenancy; using Abp.Reflection; using Castle.Core.Internal; using EntityFramework.DynamicFilters; namespace Abp.EntityFramework.Uow { /// <summary> /// Implements Unit of work for Entity Framework. /// </summary> public class EfUnitOfWork : UnitOfWorkBase, ITransientDependency { protected IDictionary<string, DbContext> ActiveDbContexts { get; private set; } protected IIocResolver IocResolver { get; private set; } protected TransactionScope CurrentTransaction; private readonly IDbContextResolver _dbContextResolver; private readonly IDbContextTypeMatcher _dbContextTypeMatcher; /// <summary> /// Creates a new <see cref="EfUnitOfWork"/>. /// </summary> public EfUnitOfWork( IIocResolver iocResolver, IConnectionStringResolver connectionStringResolver, IDbContextResolver dbContextResolver, IUnitOfWorkDefaultOptions defaultOptions, IDbContextTypeMatcher dbContextTypeMatcher) : base(connectionStringResolver, defaultOptions) { IocResolver = iocResolver; _dbContextResolver = dbContextResolver; _dbContextTypeMatcher = dbContextTypeMatcher; ActiveDbContexts = new Dictionary<string, DbContext>(); } protected override void BeginUow() { if (Options.IsTransactional == true) { var transactionOptions = new TransactionOptions { IsolationLevel = Options.IsolationLevel.GetValueOrDefault(IsolationLevel.ReadUncommitted), }; if (Options.Timeout.HasValue) { transactionOptions.Timeout = Options.Timeout.Value; } CurrentTransaction = new TransactionScope( Options.Scope.GetValueOrDefault(TransactionScopeOption.Required), transactionOptions, Options.AsyncFlowOption.GetValueOrDefault(TransactionScopeAsyncFlowOption.Enabled) ); } } public override void SaveChanges() { ActiveDbContexts.Values.ForEach(SaveChangesInDbContext); } public override async Task SaveChangesAsync() { foreach (var dbContext in ActiveDbContexts.Values) { await SaveChangesInDbContextAsync(dbContext); } } protected override void CompleteUow() { SaveChanges(); if (CurrentTransaction != null) { CurrentTransaction.Complete(); } DisposeUow(); } protected override async Task CompleteUowAsync() { await SaveChangesAsync(); if (CurrentTransaction != null) { CurrentTransaction.Complete(); } DisposeUow(); } protected override void ApplyDisableFilter(string filterName) { foreach (var activeDbContext in ActiveDbContexts.Values) { activeDbContext.DisableFilter(filterName); } } protected override void ApplyEnableFilter(string filterName) { foreach (var activeDbContext in ActiveDbContexts.Values) { activeDbContext.EnableFilter(filterName); } } protected override void ApplyFilterParameterValue(string filterName, string parameterName, object value) { foreach (var activeDbContext in ActiveDbContexts.Values) { if (TypeHelper.IsFunc<object>(value)) { activeDbContext.SetFilterScopedParameterValue(filterName, parameterName, (Func<object>)value); } else { activeDbContext.SetFilterScopedParameterValue(filterName, parameterName, value); } } } public virtual TDbContext GetOrCreateDbContext<TDbContext>(MultiTenancySides? multiTenancySide = null) where TDbContext : DbContext { var concreteDbContextType = _dbContextTypeMatcher.GetConcreteType(typeof(TDbContext)); var connectionStringResolveArgs = new ConnectionStringResolveArgs(multiTenancySide); connectionStringResolveArgs["DbContextType"] = typeof(TDbContext); connectionStringResolveArgs["DbContextConcreteType"] = concreteDbContextType; var connectionString = ResolveConnectionString(connectionStringResolveArgs); var dbContextKey = concreteDbContextType.FullName + "#" + connectionString; DbContext dbContext; if (!ActiveDbContexts.TryGetValue(dbContextKey, out dbContext)) { dbContext = _dbContextResolver.Resolve<TDbContext>(connectionString); ((IObjectContextAdapter)dbContext).ObjectContext.ObjectMaterialized += (sender, args) => { ObjectContext_ObjectMaterialized(dbContext, args); }; foreach (var filter in Filters) { if (filter.IsEnabled) { dbContext.EnableFilter(filter.FilterName); } else { dbContext.DisableFilter(filter.FilterName); } foreach (var filterParameter in filter.FilterParameters) { if (TypeHelper.IsFunc<object>(filterParameter.Value)) { dbContext.SetFilterScopedParameterValue(filter.FilterName, filterParameter.Key, (Func<object>)filterParameter.Value); } else { dbContext.SetFilterScopedParameterValue(filter.FilterName, filterParameter.Key, filterParameter.Value); } } } ActiveDbContexts[dbContextKey] = dbContext; } return (TDbContext)dbContext; } protected override void DisposeUow() { ActiveDbContexts.Values.ForEach(Release); ActiveDbContexts.Clear(); if (CurrentTransaction != null) { CurrentTransaction.Dispose(); CurrentTransaction = null; } } protected virtual void SaveChangesInDbContext(DbContext dbContext) { dbContext.SaveChanges(); } protected virtual async Task SaveChangesInDbContextAsync(DbContext dbContext) { await dbContext.SaveChangesAsync(); } protected virtual void Release(DbContext dbContext) { dbContext.Dispose(); IocResolver.Release(dbContext); } private static void ObjectContext_ObjectMaterialized(DbContext dbContext, ObjectMaterializedEventArgs e) { var entityType = ObjectContext.GetObjectType(e.Entity.GetType()); dbContext.Configuration.AutoDetectChangesEnabled = false; var previousState = dbContext.Entry(e.Entity).State; DateTimePropertyInfoHelper.NormalizeDatePropertyKinds(e.Entity, entityType); dbContext.Entry(e.Entity).State = previousState; dbContext.Configuration.AutoDetectChangesEnabled = true; } } }
// 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.Insights { using Azure; using Management; using Rest; using Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// ServiceDiagnosticSettingsOperations operations. /// </summary> internal partial class ServiceDiagnosticSettingsOperations : IServiceOperations<MonitorManagementClient>, IServiceDiagnosticSettingsOperations { /// <summary> /// Initializes a new instance of the ServiceDiagnosticSettingsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ServiceDiagnosticSettingsOperations(MonitorManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the MonitorManagementClient /// </summary> public MonitorManagementClient Client { get; private set; } /// <summary> /// Gets the active diagnostic settings for the specified resource. /// </summary> /// <param name='resourceUri'> /// The identifier of the resource. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ServiceDiagnosticSettingsResource>> GetWithHttpMessagesAsync(string resourceUri, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceUri == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceUri"); } string apiVersion = "2015-07-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceUri", resourceUri); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{resourceUri}/providers/microsoft.insights/diagnosticSettings/service").ToString(); _url = _url.Replace("{resourceUri}", System.Uri.EscapeDataString(resourceUri)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ServiceDiagnosticSettingsResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ServiceDiagnosticSettingsResource>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Create or update new diagnostic settings for the specified resource. /// </summary> /// <param name='resourceUri'> /// The identifier of the resource. /// </param> /// <param name='parameters'> /// Parameters supplied to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ServiceDiagnosticSettingsResource>> CreateOrUpdateWithHttpMessagesAsync(string resourceUri, ServiceDiagnosticSettingsResource parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceUri == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceUri"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } string apiVersion = "2015-07-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceUri", resourceUri); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{resourceUri}/providers/microsoft.insights/diagnosticSettings/service").ToString(); _url = _url.Replace("{resourceUri}", System.Uri.EscapeDataString(resourceUri)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ServiceDiagnosticSettingsResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ServiceDiagnosticSettingsResource>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Amplify Shader Editor - Visual Shader Editing Tool // Copyright (c) Amplify Creations, Lda <[email protected]> using System.Collections.Generic; using UnityEngine; using UnityEditor; namespace AmplifyShaderEditor { public class NodeGrid { private bool m_debugGrid = false; private const float GRID_SIZE_X = 100; private const float GRID_SIZE_Y = 100; private const float GRID_AREA_X = 1000; private const float GRID_AREA_Y = 1000; private Dictionary<int, Dictionary<int, List<ParentNode>>> m_grid; private int m_xMin = int.MaxValue; private int m_yMin = int.MaxValue; private int m_xMax = int.MinValue; private int m_yMax = int.MinValue; public NodeGrid() { m_grid = new Dictionary<int, Dictionary<int, List<ParentNode>>>(); } public void AddNodeToGrid( ParentNode node ) { Rect pos = node.Position; if ( Mathf.Abs( pos.width ) < 0.001f || Mathf.Abs( pos.height ) < 0.001f ) { return; } float initialXf = pos.x / GRID_SIZE_X; float initialYf = pos.y / GRID_SIZE_Y; int endX = Mathf.CeilToInt( initialXf + pos.width / GRID_SIZE_X ); int endY = Mathf.CeilToInt( initialYf + pos.height / GRID_SIZE_Y ); int initialX = Mathf.FloorToInt( initialXf ); int initialY = Mathf.FloorToInt( initialYf ); if ( initialX < m_xMin ) { m_xMin = initialX; } if ( initialY < m_yMin ) { m_yMin = initialY; } if ( endX > m_xMax ) { m_xMax = endX; } if ( endY > m_yMax ) { m_yMax = endY; } for ( int x = initialX; x < endX; x += 1 ) { for ( int y = initialY; y < endY; y += 1 ) { if ( !m_grid.ContainsKey( x ) ) { m_grid.Add( x, new Dictionary<int, List<ParentNode>>() ); } if ( !m_grid[ x ].ContainsKey( y ) ) { m_grid[ x ].Add( y, new List<ParentNode>() ); } m_grid[ x ][ y ].Add( node ); } } node.IsOnGrid = true; //DebugLimits(); } public void RemoveNodeFromGrid( ParentNode node, bool useCachedPos ) { Rect pos = useCachedPos ? node.CachedPos : node.Position; if ( Mathf.Abs( pos.width ) < 0.001f || Mathf.Abs( pos.height ) < 0.001f ) { return; } float initialXf = pos.x / GRID_SIZE_X; float initialYf = pos.y / GRID_SIZE_Y; int endX = Mathf.CeilToInt( initialXf + pos.width / GRID_SIZE_X ); int endY = Mathf.CeilToInt( initialYf + pos.height / GRID_SIZE_Y ); int initialX = Mathf.FloorToInt( initialXf ); int initialY = Mathf.FloorToInt( initialYf ); bool testLimits = false; int xMinCount = 0; int xMaxCount = 0; int yMinCount = 0; int yMaxCount = 0; for ( int x = initialX; x < endX; x += 1 ) { for ( int y = initialY; y < endY; y += 1 ) { if ( m_grid.ContainsKey( x ) ) { if ( m_grid[ x ].ContainsKey( y ) ) { m_grid[ x ][ y ].Remove( node ); node.IsOnGrid = false; if ( initialX == m_xMin && x == initialX ) { testLimits = true; if ( m_grid[ x ][ y ].Count != 0 ) { xMinCount += 1; } } if ( endX == m_xMax && x == endX ) { testLimits = true; if ( m_grid[ x ][ y ].Count != 0 ) { xMaxCount += 1; } } if ( initialY == m_yMin && y == initialY ) { testLimits = true; if ( m_grid[ x ][ y ].Count != 0 ) { yMinCount += 1; } } if ( endY == m_yMax && y == endY ) { testLimits = true; if ( m_grid[ x ][ y ].Count != 0 ) { yMaxCount += 1; } } } } } } if ( testLimits ) { if ( xMinCount == 0 || xMaxCount == 0 || yMinCount == 0 || yMaxCount == 0 ) { m_xMin = int.MaxValue; m_yMin = int.MaxValue; m_xMax = int.MinValue; m_yMax = int.MinValue; foreach ( KeyValuePair<int, Dictionary<int, List<ParentNode>>> entryX in m_grid ) { foreach ( KeyValuePair<int, List<ParentNode>> entryY in entryX.Value ) { if ( entryY.Value.Count > 0 ) { if ( entryX.Key < m_xMin ) { m_xMin = entryX.Key; } if ( entryY.Key < m_yMin ) { m_yMin = entryY.Key; } if ( entryX.Key > m_xMax ) { m_xMax = entryX.Key; } if ( entryY.Key > m_yMax ) { m_yMax = entryY.Key; } } } } // The += 1 is to maintain consistence with AddNodeToGrid() ceil op on max values m_xMax += 1; m_yMax += 1; } } //DebugLimits(); } public void DebugLimits() { Debug.Log( "[ " + m_xMin + " , " + m_yMin + " ] " + "[ " + m_xMax + " , " + m_yMax + " ] " ); } //pos must be the transformed mouse position to local canvas coordinates public List<ParentNode> GetNodesOn( Vector2 pos ) { int x = Mathf.FloorToInt( pos.x / GRID_SIZE_X ); int y = Mathf.FloorToInt( pos.y / GRID_SIZE_Y ); if ( m_grid.ContainsKey( x ) ) { if ( m_grid[ x ].ContainsKey( y ) ) { return m_grid[ x ][ y ]; } } return null; } public List<ParentNode> GetNodesOn( int x, int y ) { if ( m_grid.ContainsKey( x ) ) { if ( m_grid[ x ].ContainsKey( y ) ) { return m_grid[ x ][ y ]; } } return null; } public void DrawGrid( DrawInfo drawInfo ) { if ( m_debugGrid ) { #if UNITY_5_5_OR_NEWER Handles.CircleHandleCap( 0, drawInfo.InvertedZoom * ( new Vector3( drawInfo.CameraOffset.x, drawInfo.CameraOffset.y, 0f ) ), Quaternion.identity, 5,EventType.layout ); #else Handles.CircleCap( 0, drawInfo.InvertedZoom * ( new Vector3( drawInfo.CameraOffset.x, drawInfo.CameraOffset.y, 0f ) ), Quaternion.identity, 5 ); #endif for ( int x = -( int ) GRID_AREA_X; x < GRID_AREA_X; x += ( int ) GRID_SIZE_X ) { Handles.DrawLine( drawInfo.InvertedZoom * ( new Vector3( x + drawInfo.CameraOffset.x, drawInfo.CameraOffset.y - GRID_AREA_Y, 0 ) ), drawInfo.InvertedZoom * ( new Vector3( drawInfo.CameraOffset.x + x, drawInfo.CameraOffset.y + GRID_AREA_Y, 0 ) ) ); } for ( int y = -( int ) GRID_AREA_Y; y < GRID_AREA_X; y += ( int ) GRID_SIZE_Y ) { Handles.DrawLine( drawInfo.InvertedZoom * ( new Vector3( drawInfo.CameraOffset.x - GRID_AREA_X, drawInfo.CameraOffset.y + y, 0 ) ), drawInfo.InvertedZoom * ( new Vector3( drawInfo.CameraOffset.x + GRID_AREA_X, drawInfo.CameraOffset.y + y, 0 ) ) ); } } } public void Destroy() { foreach ( KeyValuePair<int, Dictionary<int, List<ParentNode>>> entryX in m_grid ) { foreach ( KeyValuePair<int, List<ParentNode>> entryY in entryX.Value ) { entryY.Value.Clear(); } entryX.Value.Clear(); } m_grid.Clear(); } public float MaxNodeDist { get { return Mathf.Max( ( m_xMax - m_xMin )*GRID_SIZE_X, ( m_yMax - m_yMin )*GRID_SIZE_Y ); } } } }
// // Dispatch.cs: Support for Grand Central Dispatch framework // // Authors: // Miguel de Icaza ([email protected]) // // Copyright 2010 Novell, Inc. // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Runtime.InteropServices; using MonoMac.ObjCRuntime; using MonoMac.Foundation; namespace MonoMac.CoreFoundation { public enum DispatchQueuePriority { High = 2, Default = 0, Low = -2, } public class DispatchObject : INativeObject, IDisposable { internal IntPtr handle; // // Constructors and lifecycle // [Preserve (Conditional = true)] internal DispatchObject (IntPtr handle, bool owns) { if (handle == IntPtr.Zero) throw new ArgumentNullException ("handle"); this.handle = handle; if (!owns) dispatch_retain (handle); } internal DispatchObject () { } [DllImport ("libc")] extern static IntPtr dispatch_release (IntPtr o); [DllImport ("libc")] extern static IntPtr dispatch_retain (IntPtr o); ~DispatchObject () { Dispose (false); } public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } public IntPtr Handle { get { return handle; } } protected virtual void Dispose (bool disposing) { if (handle != IntPtr.Zero){ dispatch_release (handle); handle = IntPtr.Zero; } } public static bool operator == (DispatchObject a, DispatchObject b) { var oa = a as object; var ob = b as object; if (oa == null){ if (ob == null) return true; return false; } else { if (ob == null) return false; return a.handle == b.handle; } } public static bool operator != (DispatchObject a, DispatchObject b) { var oa = a as object; var ob = b as object; if (oa == null){ if (ob == null) return false; return true; } else { if (ob == null) return true; return a.handle != b.handle; } } public override bool Equals (object other) { if (other == null) return false; var od = other as DispatchQueue; return od.handle == handle; } public override int GetHashCode () { return (int) handle; } void Check () { if (handle == IntPtr.Zero) throw new ObjectDisposedException ("DispatchQueue"); } // // Properties and methods // [DllImport ("libc")] extern static void dispatch_suspend (IntPtr o); public void Suspend () { Check (); dispatch_suspend (handle); } [DllImport ("libc")] extern static void dispatch_resume (IntPtr o); public void Resume () { Check (); dispatch_resume (handle); } [DllImport ("libc")] extern static IntPtr dispatch_get_context (IntPtr o); [DllImport ("libc")] extern static void dispatch_set_context (IntPtr o, IntPtr ctx); public IntPtr Context { get { Check (); return dispatch_get_context (handle); } set { Check (); dispatch_set_context (handle, value); } } } public class DispatchQueue : DispatchObject { [Preserve (Conditional = true)] internal DispatchQueue (IntPtr handle, bool owns) : base (handle, owns) { } public DispatchQueue (IntPtr handle) : base (handle, false) { } public DispatchQueue (string label) : base () { // Initialized in owned state for the queue. handle = dispatch_queue_create (label, IntPtr.Zero); if (handle == IntPtr.Zero) throw new Exception ("Error creating dispatch queue"); } // // Properties and methods // public string Label { get { if (handle == IntPtr.Zero) throw new ObjectDisposedException ("DispatchQueue"); return dispatch_queue_get_label (handle); } } public static DispatchQueue CurrentQueue { get { return new DispatchQueue (dispatch_get_current_queue (), false); } } public static DispatchQueue GetGlobalQueue (DispatchQueuePriority priority) { return new DispatchQueue (dispatch_get_global_queue ((IntPtr) priority, IntPtr.Zero), false); } public static DispatchQueue DefaultGlobalQueue { get { return new DispatchQueue (dispatch_get_global_queue ((IntPtr) DispatchQueuePriority.Default, IntPtr.Zero), false); } } #if !MONOMAC static IntPtr main_q; #endif static object lockobj = new object (); public static DispatchQueue MainQueue { get { #if !MONOMAC if (Runtime.Arch == Arch.DEVICE) { lock (lockobj) { if (main_q == IntPtr.Zero) { var h = Dlfcn.dlopen ("/usr/lib/libSystem.dylib", 0x0); main_q = Dlfcn.GetIndirect (h, "_dispatch_main_q"); Dlfcn.dlclose (h); } } return new DispatchQueue (main_q, false); } else #endif return new DispatchQueue (dispatch_get_main_queue (), false); } } // // Dispatching // delegate void dispatch_callback_t (IntPtr context); static dispatch_callback_t static_dispatch = new dispatch_callback_t (static_dispatcher_to_managed); [MonoPInvokeCallback (typeof (dispatch_callback_t))] static void static_dispatcher_to_managed (IntPtr context) { GCHandle gch = GCHandle.FromIntPtr (context); var action = gch.Target as NSAction; if (action != null) action (); gch.Free (); } public void DispatchAsync (NSAction action) { if (action == null) throw new ArgumentNullException ("action"); dispatch_async_f (handle, (IntPtr) GCHandle.Alloc (action), static_dispatch); } public void DispatchSync (NSAction action) { if (action == null) throw new ArgumentNullException ("action"); dispatch_sync_f (handle, (IntPtr) GCHandle.Alloc (action), static_dispatch); } // // Native methods // [DllImport ("libc")] extern static IntPtr dispatch_queue_create (string label, IntPtr attr); [DllImport ("libc")] extern static void dispatch_async_f (IntPtr queue, IntPtr context, dispatch_callback_t dispatch); [DllImport ("libc")] extern static void dispatch_sync_f (IntPtr queue, IntPtr context, dispatch_callback_t dispatch); [DllImport ("libc")] extern static IntPtr dispatch_get_current_queue (); [DllImport ("libc")] extern static IntPtr dispatch_get_global_queue (IntPtr priority, IntPtr flags); [DllImport ("libc")] extern static IntPtr dispatch_get_main_queue (); [DllImport ("libc")] extern static string dispatch_queue_get_label (IntPtr queue); #if MONOMAC // // Not to be used by apps that use UIApplicationMain, NSApplicationMain or CFRunLoopRun, // so not available on Monotouch // [DllImport ("libc")] static extern IntPtr dispatch_main (); public static void MainIteration () { dispatch_main (); } #endif } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Graph.RBAC { using Microsoft.Azure; using Microsoft.Azure.Graph; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Azure.OData; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// ApplicationsOperations operations. /// </summary> public partial interface IApplicationsOperations { /// <summary> /// Create a new application. /// </summary> /// <param name='parameters'> /// The parameters for creating an application. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<Application>> CreateWithHttpMessagesAsync(ApplicationCreateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists applications by filter parameters. /// </summary> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Application>>> ListWithHttpMessagesAsync(ODataQuery<Application> odataQuery = default(ODataQuery<Application>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Delete an application. /// </summary> /// <param name='applicationObjectId'> /// Application object ID. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string applicationObjectId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an application by object ID. /// </summary> /// <param name='applicationObjectId'> /// Application object ID. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<Application>> GetWithHttpMessagesAsync(string applicationObjectId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Update an existing application. /// </summary> /// <param name='applicationObjectId'> /// Application object ID. /// </param> /// <param name='parameters'> /// Parameters to update an existing application. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> PatchWithHttpMessagesAsync(string applicationObjectId, ApplicationUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get the keyCredentials associated with an application. /// </summary> /// <param name='applicationObjectId'> /// Application object ID. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<KeyCredential>>> ListKeyCredentialsWithHttpMessagesAsync(string applicationObjectId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Update the keyCredentials associated with an application. /// </summary> /// <param name='applicationObjectId'> /// Application object ID. /// </param> /// <param name='parameters'> /// Parameters to update the keyCredentials of an existing application. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> UpdateKeyCredentialsWithHttpMessagesAsync(string applicationObjectId, KeyCredentialsUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get the passwordCredentials associated with an application. /// </summary> /// <param name='applicationObjectId'> /// Application object ID. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IEnumerable<PasswordCredential>>> ListPasswordCredentialsWithHttpMessagesAsync(string applicationObjectId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Update passwordCredentials associated with an application. /// </summary> /// <param name='applicationObjectId'> /// Application object ID. /// </param> /// <param name='parameters'> /// Parameters to update passwordCredentials of an existing /// application. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> UpdatePasswordCredentialsWithHttpMessagesAsync(string applicationObjectId, PasswordCredentialsUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a list of applications from the current tenant. /// </summary> /// <param name='nextLink'> /// Next link for the list operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Application>>> ListNextWithHttpMessagesAsync(string nextLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
namespace VRTK { using UnityEngine; using Valve.VR; public class SDK_SteamVR : SDK_Base { private SteamVR_ControllerManager cachedControllerManager; public override string GetControllerElementPath(ControllerElelements element, VRTK_DeviceFinder.ControllerHand hand) { switch (element) { case ControllerElelements.AttachPoint: return "Model/tip/attach"; case ControllerElelements.Trigger: return "Model/trigger"; case ControllerElelements.GripLeft: return "Model/lgrip"; case ControllerElelements.GripRight: return "Model/rgrip"; case ControllerElelements.Touchpad: return "Model/trackpad"; case ControllerElelements.ApplicationMenu: return "Model/button"; case ControllerElelements.SystemMenu: return "Model/sys_button"; case ControllerElelements.Body: return "Model/body"; } return null; } public override GameObject GetTrackedObject(GameObject obj, out uint index) { var trackedObject = obj.GetComponent<SteamVR_TrackedObject>(); index = 0; if (trackedObject) { index = (uint)trackedObject.index; return trackedObject.gameObject; } return null; } public override GameObject GetTrackedObjectByIndex(uint index) { //attempt to get from cache first if (VRTK_ObjectCache.trackedControllers.ContainsKey(index)) { return VRTK_ObjectCache.trackedControllers[index]; } //if not found in cache then brute force check foreach (SteamVR_TrackedObject trackedObject in FindObjectsOfType<SteamVR_TrackedObject>()) { if ((uint)trackedObject.index == index) { return trackedObject.gameObject; } } return null; } public override uint GetIndexOfTrackedObject(GameObject trackedObject) { uint index = 0; GetTrackedObject(trackedObject, out index); return index; } public override Transform GetTrackedObjectOrigin(GameObject obj) { var trackedObject = obj.GetComponent<SteamVR_TrackedObject>(); if (trackedObject) { return trackedObject.origin ? trackedObject.origin : trackedObject.transform.parent; } return null; } public override bool TrackedIndexIsController(uint index) { var system = OpenVR.System; if (system != null && system.GetTrackedDeviceClass(index) == ETrackedDeviceClass.Controller) { return true; } return false; } public override GameObject GetControllerLeftHand() { var controllerManager = GetControllerManager(); if (controllerManager) { return controllerManager.left; } return null; } public override GameObject GetControllerRightHand() { var controllerManager = GetControllerManager(); if (controllerManager) { return controllerManager.right; } return null; } public override bool IsControllerLeftHand(GameObject controller) { var controllerManager = GetControllerManager(); if (controllerManager && controller == controllerManager.left) { return true; } return false; } public override bool IsControllerRightHand(GameObject controller) { var controllerManager = GetControllerManager(); if (controllerManager && controller == controllerManager.right) { return true; } return false; } public override Transform GetHeadset() { if (cachedHeadset == null) { #if (UNITY_5_4_OR_NEWER) cachedHeadset = FindObjectOfType<SteamVR_Camera>().transform; #else cachedHeadset = FindObjectOfType<SteamVR_GameView>().transform; #endif } return cachedHeadset; } public override Transform GetHeadsetCamera() { if (cachedHeadsetCamera == null) { cachedHeadsetCamera = FindObjectOfType<SteamVR_Camera>().transform; } return cachedHeadsetCamera; } public override GameObject GetHeadsetCamera(GameObject obj) { return obj.GetComponent<SteamVR_Camera>().gameObject; } public override Transform GetPlayArea() { if (cachedPlayArea == null) { cachedPlayArea = FindObjectOfType<SteamVR_PlayArea>().transform; } return cachedPlayArea; } public override Vector3[] GetPlayAreaVertices(GameObject playArea) { var area = playArea.GetComponent<SteamVR_PlayArea>(); if (area) { return area.vertices; } return null; } public override float GetPlayAreaBorderThickness(GameObject playArea) { var area = playArea.GetComponent<SteamVR_PlayArea>(); if (area) { return area.borderThickness; } return 0f; } public override bool IsPlayAreaSizeCalibrated(GameObject playArea) { var area = playArea.GetComponent<SteamVR_PlayArea>(); return (area.size == SteamVR_PlayArea.Size.Calibrated); } public override bool IsDisplayOnDesktop() { return (OpenVR.System == null || OpenVR.System.IsDisplayOnDesktop()); } public override bool ShouldAppRenderWithLowResources() { return (OpenVR.Compositor != null && OpenVR.Compositor.ShouldAppRenderWithLowResources()); } public override void ForceInterleavedReprojectionOn(bool force) { if (OpenVR.Compositor != null) { OpenVR.Compositor.ForceInterleavedReprojectionOn(force); } } public override GameObject GetControllerRenderModel(GameObject controller) { var renderModel = (controller.GetComponent<SteamVR_RenderModel>() ? controller.GetComponent<SteamVR_RenderModel>() : controller.GetComponentInChildren<SteamVR_RenderModel>()); return (renderModel ? renderModel.gameObject : null); } public override void SetControllerRenderModelWheel(GameObject renderModel, bool state) { var model = renderModel.GetComponent<SteamVR_RenderModel>(); if (model) { model.controllerModeState.bScrollWheelVisible = state; } } public override void HeadsetFade(Color color, float duration, bool fadeOverlay = false) { SteamVR_Fade.Start(color, duration, fadeOverlay); } public override bool HasHeadsetFade(GameObject obj) { if (obj.GetComponentInChildren<SteamVR_Fade>()) { return true; } return false; } public override void AddHeadsetFade(Transform camera) { if (camera && !camera.gameObject.GetComponent<SteamVR_Fade>()) { camera.gameObject.AddComponent<SteamVR_Fade>(); } } public override void HapticPulseOnIndex(uint index, ushort durationMicroSec = 500) { if (index < uint.MaxValue) { var device = SteamVR_Controller.Input((int)index); device.TriggerHapticPulse(durationMicroSec, EVRButtonId.k_EButton_Axis0); } } public override Vector3 GetVelocityOnIndex(uint index) { if (index >= uint.MaxValue) { return Vector3.zero; } var device = SteamVR_Controller.Input((int)index); return device.velocity; } public override Vector3 GetAngularVelocityOnIndex(uint index) { if (index >= uint.MaxValue) { return Vector3.zero; } var device = SteamVR_Controller.Input((int)index); return device.angularVelocity; } public override Vector2 GetTouchpadAxisOnIndex(uint index) { if (index >= uint.MaxValue) { return Vector2.zero; } var device = SteamVR_Controller.Input((int)index); return device.GetAxis(); } public override Vector2 GetTriggerAxisOnIndex(uint index) { if (index >= uint.MaxValue) { return Vector2.zero; } var device = SteamVR_Controller.Input((int)index); return device.GetAxis(EVRButtonId.k_EButton_SteamVR_Trigger); } public override float GetTriggerHairlineDeltaOnIndex(uint index) { if (index >= uint.MaxValue) { return 0f; } var device = SteamVR_Controller.Input((int)index); return device.hairTriggerDelta; } //Trigger public override bool IsTriggerPressedOnIndex(uint index) { return IsButtonPressed(index, ButtonPressTypes.Press, SteamVR_Controller.ButtonMask.Trigger); } public override bool IsTriggerPressedDownOnIndex(uint index) { return IsButtonPressed(index, ButtonPressTypes.PressDown, SteamVR_Controller.ButtonMask.Trigger); } public override bool IsTriggerPressedUpOnIndex(uint index) { return IsButtonPressed(index, ButtonPressTypes.PressUp, SteamVR_Controller.ButtonMask.Trigger); } public override bool IsTriggerTouchedOnIndex(uint index) { return IsButtonPressed(index, ButtonPressTypes.Touch, SteamVR_Controller.ButtonMask.Trigger); } public override bool IsTriggerTouchedDownOnIndex(uint index) { return IsButtonPressed(index, ButtonPressTypes.TouchDown, SteamVR_Controller.ButtonMask.Trigger); } public override bool IsTriggerTouchedUpOnIndex(uint index) { return IsButtonPressed(index, ButtonPressTypes.TouchUp, SteamVR_Controller.ButtonMask.Trigger); } public override bool IsHairTriggerDownOnIndex(uint index) { if (index >= uint.MaxValue) { return false; } var device = SteamVR_Controller.Input((int)index); return device.GetHairTriggerDown(); } public override bool IsHairTriggerUpOnIndex(uint index) { if (index >= uint.MaxValue) { return false; } var device = SteamVR_Controller.Input((int)index); return device.GetHairTriggerUp(); } //Grip public override bool IsGripPressedOnIndex(uint index) { return IsButtonPressed(index, ButtonPressTypes.Press, SteamVR_Controller.ButtonMask.Grip); } public override bool IsGripPressedDownOnIndex(uint index) { return IsButtonPressed(index, ButtonPressTypes.PressDown, SteamVR_Controller.ButtonMask.Grip); } public override bool IsGripPressedUpOnIndex(uint index) { return IsButtonPressed(index, ButtonPressTypes.PressUp, SteamVR_Controller.ButtonMask.Grip); } public override bool IsGripTouchedOnIndex(uint index) { return IsButtonPressed(index, ButtonPressTypes.Touch, SteamVR_Controller.ButtonMask.Grip); } public override bool IsGripTouchedDownOnIndex(uint index) { return IsButtonPressed(index, ButtonPressTypes.TouchDown, SteamVR_Controller.ButtonMask.Grip); } public override bool IsGripTouchedUpOnIndex(uint index) { return IsButtonPressed(index, ButtonPressTypes.TouchUp, SteamVR_Controller.ButtonMask.Grip); } //Touchpad public override bool IsTouchpadPressedOnIndex(uint index) { return IsButtonPressed(index, ButtonPressTypes.Press, SteamVR_Controller.ButtonMask.Touchpad); } public override bool IsTouchpadPressedDownOnIndex(uint index) { return IsButtonPressed(index, ButtonPressTypes.PressDown, SteamVR_Controller.ButtonMask.Touchpad); } public override bool IsTouchpadPressedUpOnIndex(uint index) { return IsButtonPressed(index, ButtonPressTypes.PressUp, SteamVR_Controller.ButtonMask.Touchpad); } public override bool IsTouchpadTouchedOnIndex(uint index) { return IsButtonPressed(index, ButtonPressTypes.Touch, SteamVR_Controller.ButtonMask.Touchpad); } public override bool IsTouchpadTouchedDownOnIndex(uint index) { return IsButtonPressed(index, ButtonPressTypes.TouchDown, SteamVR_Controller.ButtonMask.Touchpad); } public override bool IsTouchpadTouchedUpOnIndex(uint index) { return IsButtonPressed(index, ButtonPressTypes.TouchUp, SteamVR_Controller.ButtonMask.Touchpad); } //Application Menu public override bool IsApplicationMenuPressedOnIndex(uint index) { return IsButtonPressed(index, ButtonPressTypes.Press, SteamVR_Controller.ButtonMask.ApplicationMenu); } public override bool IsApplicationMenuPressedDownOnIndex(uint index) { return IsButtonPressed(index, ButtonPressTypes.PressDown, SteamVR_Controller.ButtonMask.ApplicationMenu); } public override bool IsApplicationMenuPressedUpOnIndex(uint index) { return IsButtonPressed(index, ButtonPressTypes.PressUp, SteamVR_Controller.ButtonMask.ApplicationMenu); } public override bool IsApplicationMenuTouchedOnIndex(uint index) { return IsButtonPressed(index, ButtonPressTypes.Touch, SteamVR_Controller.ButtonMask.ApplicationMenu); } public override bool IsApplicationMenuTouchedDownOnIndex(uint index) { return IsButtonPressed(index, ButtonPressTypes.TouchDown, SteamVR_Controller.ButtonMask.ApplicationMenu); } public override bool IsApplicationMenuTouchedUpOnIndex(uint index) { return IsButtonPressed(index, ButtonPressTypes.TouchUp, SteamVR_Controller.ButtonMask.ApplicationMenu); } [RuntimeInitializeOnLoadMethod] private void Initialise() { SteamVR_Utils.Event.Listen("TrackedDeviceRoleChanged", OnTrackedDeviceRoleChanged); } private void OnTrackedDeviceRoleChanged(params object[] args) { cachedControllerManager = null; VRTK_ObjectCache.trackedControllers.Clear(); } private SteamVR_ControllerManager GetControllerManager() { if (cachedControllerManager == null || !cachedControllerManager.isActiveAndEnabled) { foreach (var manager in FindObjectsOfType<SteamVR_ControllerManager>()) { if (manager.left && manager.right) { cachedControllerManager = manager; } } } return cachedControllerManager; } private enum ButtonPressTypes { Press, PressDown, PressUp, Touch, TouchDown, TouchUp } private static bool IsButtonPressed(uint index, ButtonPressTypes type, ulong button) { if (index >= uint.MaxValue) { return false; } var device = SteamVR_Controller.Input((int)index); switch (type) { case ButtonPressTypes.Press: return device.GetPress(button); case ButtonPressTypes.PressDown: return device.GetPressDown(button); case ButtonPressTypes.PressUp: return device.GetPressUp(button); case ButtonPressTypes.Touch: return device.GetTouch(button); case ButtonPressTypes.TouchDown: return device.GetTouchDown(button); case ButtonPressTypes.TouchUp: return device.GetTouchUp(button); } return false; } } }
//! \file ImageAGF.cs //! \date Sun Sep 20 16:17:19 2015 //! \brief Eushully image format. // // Copyright (C) 2015 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using GameRes.Compression; using GameRes.Utility; using System; using System.ComponentModel.Composition; using System.IO; using System.Windows.Media; namespace GameRes.Formats.Eushully { internal class AgfMetaData : ImageMetaData { public int SourceBPP; public uint DataOffset; public Color[] Palette; } [Export(typeof(ImageFormat))] public class AgfFormat : ImageFormat { public override string Tag { get { return "AGF"; } } public override string Description { get { return "Eushully image format"; } } public override uint Signature { get { return 0x46474341; } } // 'ACGF' public AgfFormat () { Signatures = new uint[] { 0x46474341, 0 }; } public override ImageMetaData ReadMetaData (IBinaryStream stream) { uint id = stream.Signature; if (Signature != id && 0 != id) return null; var header = new byte[0x20]; if (0x18 != stream.Read (header, 0, 0x18)) return null; int type = LittleEndian.ToInt32 (header, 4); if (type != 1 && type != 2) return null; int unpacked_size = LittleEndian.ToInt32 (header, 0xC); int packed_size = LittleEndian.ToInt32 (header, 0x14); using (var unpacked = AgfReader.OpenSection (stream.AsStream, unpacked_size, packed_size)) using (var reader = new BinaryReader (unpacked)) { if (0x20 != reader.Read (header, 0, 0x20)) return null; var info = new AgfMetaData { Width = LittleEndian.ToUInt32 (header, 0x14), Height = LittleEndian.ToUInt32 (header, 0x18), BPP = 1 == type ? 24 : 32, SourceBPP = LittleEndian.ToInt16 (header, 0x1E), DataOffset = 0x18 + (uint)packed_size, }; if (0 == info.SourceBPP) return null; if (info.SourceBPP <= 8) { reader.Read (header, 0, 0x18); // skip rest of the header info.Palette = ReadColorMap (reader.BaseStream); } return info; } } public override ImageData Read (IBinaryStream stream, ImageMetaData info) { using (var reader = new AgfReader (stream, (AgfMetaData)info)) { reader.Unpack(); return ImageData.Create (info, reader.Format, null, reader.Data); } } public override void Write (Stream file, ImageData image) { throw new System.NotImplementedException ("AgfFormat.Write not implemented"); } } internal sealed class AgfReader : IDisposable { IBinaryStream m_input; byte[] m_output; int m_width; int m_height; int m_bpp; int m_source_bpp; Color[] m_palette; public PixelFormat Format { get; private set; } public byte[] Data { get { return m_output; } } public AgfReader (IBinaryStream input, AgfMetaData info) { m_input = input; m_bpp = info.BPP; m_source_bpp = info.SourceBPP; input.Position = info.DataOffset; m_width = (int)info.Width; m_height = (int)info.Height; m_output = new byte[m_height * m_width * m_bpp / 8]; m_palette = info.Palette; } public static Stream OpenSection (Stream stream, int unpacked_size, int packed_size) { if (unpacked_size != packed_size) return new LzssStream (stream, LzssMode.Decompress, true); else return new StreamRegion (stream, stream.Position, packed_size, true); } public void Unpack () { m_input.ReadInt32(); int data_size = m_input.ReadInt32(); int packed_size = m_input.ReadInt32(); var data_pos = m_input.Position; var bmp_data = new byte[data_size]; using (var unpacked = OpenSection (m_input.AsStream, data_size, packed_size)) if (data_size != unpacked.Read (bmp_data, 0, data_size)) throw new EndOfStreamException(); byte[] alpha = null; if (32 == m_bpp) { m_input.Position = data_pos + packed_size; alpha = ReadAlphaChannel(); if (null == alpha) m_bpp = 24; } Format = 32 == m_bpp ? PixelFormats.Bgra32 : PixelFormats.Bgr24; int src_pixel_size = m_source_bpp / 8; // not used for 4bpp bitmaps int dst_pixel_size = m_bpp / 8; int src_stride = (m_width * m_source_bpp / 8 + 3) & ~3; int dst_stride = m_width * dst_pixel_size; int src_row = (m_height - 1) * src_stride; int dst_row = 0; int src_alpha = 0; RowUnpacker repack_row = RepackRowTrue; if (8 == m_source_bpp) repack_row = RepackRow8; else if (4 == m_source_bpp) repack_row = RepackRow4; while (src_row >= 0) { repack_row (bmp_data, src_row, src_pixel_size, dst_row, dst_pixel_size, alpha, src_alpha); src_row -= src_stride; dst_row += dst_stride; src_alpha += m_width; } } delegate void RowUnpacker (byte[] bmp, int src, int src_pixel_size, int dst, int dst_pixel_size, byte[] alpha, int src_alpha); void RepackRow4 (byte[] bmp, int src, int src_pixel_size, int dst, int dst_pixel_size, byte[] alpha, int src_alpha) { for (int x = 0; x < m_width; ) { byte px = bmp[src++]; for (int j = 0; j < 2; ++j) { var color = m_palette[(px >> 4) & 0xF]; m_output[dst] = color.B; m_output[dst+1] = color.G; m_output[dst+2] = color.R; if (null != alpha) m_output[dst+3] = alpha[src_alpha++]; dst += dst_pixel_size; if (++x >= m_width) break; px <<= 4; } } } void RepackRow8 (byte[] bmp, int src, int src_pixel_size, int dst, int dst_pixel_size, byte[] alpha, int src_alpha) { for (int i = 0; i < m_width; ++i) { var color = m_palette[bmp[src++]]; m_output[dst] = color.B; m_output[dst+1] = color.G; m_output[dst+2] = color.R; if (null != alpha) m_output[dst+3] = alpha[src_alpha++]; dst += dst_pixel_size; } } void RepackRowTrue (byte[] bmp, int src, int src_pixel_size, int dst, int dst_pixel_size, byte[] alpha, int src_alpha) { for (int i = 0; i < m_width; ++i) { m_output[dst] = bmp[src]; m_output[dst+1] = bmp[src+1]; m_output[dst+2] = bmp[src+2]; if (null != alpha) m_output[dst+3] = alpha[src_alpha++]; src += src_pixel_size; dst += dst_pixel_size; } } byte[] ReadAlphaChannel () { var header = new byte[0x24]; if (0x24 != m_input.Read (header, 0, header.Length)) return null; if (!Binary.AsciiEqual (header, 0, "ACIF")) return null; int unpacked_size = LittleEndian.ToInt32 (header, 0x1C); int packed_size = LittleEndian.ToInt32 (header, 0x20); if (m_width*m_height != unpacked_size) return null; var alpha = new byte[unpacked_size]; using (var unpacked = OpenSection (m_input.AsStream, unpacked_size, packed_size)) if (unpacked_size != unpacked.Read (alpha, 0, unpacked_size)) return null; return alpha; } #region IDisposable methods public void Dispose () { } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Diagnostics.Contracts; using Microsoft.Research.ClousotRegression; internal class Test { [ClousotRegressionTest] #if FIRST [RegressionOutcome("No entry found in the cache")] #else [RegressionOutcome("An entry has been found in the cache")] #endif private void F() { Console.WriteLine("Hello"); } [ClousotRegressionTest] #if FIRST [RegressionOutcome("No entry found in the cache")] #else [RegressionOutcome("An entry has been found in the cache")] #endif [RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"assert unproven", PrimaryILOffset = 13, MethodILOffset = 0)] private void Fx(int x) // With outcome { F(); Contract.Assert(x != 0); Console.WriteLine("{0}", x); } [ClousotRegressionTest] #if FIRST [RegressionOutcome("No entry found in the cache")] #else [RegressionOutcome("An entry has been found in the cache")] #endif [RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"ensures unproven: Contract.Result<object>() != null", PrimaryILOffset = 11, MethodILOffset = 17)] private object Fo(object o) // With suggestion { Contract.Ensures(Contract.Result<object>() != null); return o; } [ClousotRegressionTest] #if FIRST [RegressionOutcome("No entry found in the cache")] #else [RegressionOutcome("An entry has been found in the cache")] #endif private void UseFo() // We try to use the non-null post condition inference { object o = Fo(1); Contract.Assert(o != null); } [ClousotRegressionTest] #if FIRST [RegressionOutcome("No entry found in the cache")] #else [RegressionOutcome("An entry has been found in the cache")] #endif private object G0(object o) { Contract.Requires(o != null); return o; } [ClousotRegressionTest] #if FIRST [RegressionOutcome("No entry found in the cache")] #else [RegressionOutcome("An entry has been found in the cache")] #endif private void G() // With requires imported from another method, and an imported infered ensure { object o = G0(0); Contract.Assert(o != null); } // We now know how to cache pre/prost-conditions inferences private int P { [ClousotRegressionTest] #if FIRST [RegressionOutcome("No entry found in the cache")] #else [RegressionOutcome("An entry has been found in the cache")] #endif get { return 1; } } [ClousotRegressionTest] #if FIRST [RegressionOutcome("No entry found in the cache")] #else [RegressionOutcome("An entry has been found in the cache")] #endif [RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"Possibly unboxing a null reference", PrimaryILOffset = 28, MethodILOffset = 0)] public static T GetService<T>(IServiceProvider serviceProvider) { Contract.Requires(serviceProvider != null); return (T)serviceProvider.GetService(typeof(T)); } } namespace CacheBugs { public class ExampleWithPure { public object field; [ClousotRegressionTest] #if FIRST [RegressionOutcome("No entry found in the cache")] #else [RegressionOutcome("An entry has been found in the cache")] #endif [RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"assert unproven", PrimaryILOffset = 35, MethodILOffset = 0)] public void Use() { Contract.Assume(field != null); IAmPure(); Contract.Assert(field != null); } public void IAmPure() { } } public class ExamplesWithPure { [ClousotRegressionTest] #if FIRST [RegressionOutcome("No entry found in the cache")] #else [RegressionOutcome("An entry has been found in the cache")] #endif public string PureMethod(object x) { Contract.Requires(x != null); return x.ToString(); } [ClousotRegressionTest] #if FIRST [RegressionOutcome("No entry found in the cache")] #else [RegressionOutcome("An entry has been found in the cache")] #endif public string PureParameter(object[] x) { Contract.Requires(x != null); return x.ToString(); } [ClousotRegressionTest] #if FIRST [RegressionOutcome("No entry found in the cache")] #else [RegressionOutcome("An entry has been found in the cache")] #endif public void CallPureParameter(object[] x) { Contract.Requires(x != null); PureParameter(x); } } } // For the tests below, Clousot2 was seeing the three occurrences of M as the same method, so it analyzed the first one, and read the other two from the cache. // The reason is that the generics were not in the Full name namespace CacheBugsWithClousot2 { internal class C { [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = "assert unproven", PrimaryILOffset = 4, MethodILOffset = 0)] #if FIRST [RegressionOutcome("No entry found in the cache")] #else [RegressionOutcome("An entry has been found in the cache")] #endif private void M(int x) { Contract.Assert(x > 0); } } internal class C<T> { [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = "assert unproven", PrimaryILOffset = 4, MethodILOffset = 0)] #if FIRST [RegressionOutcome("No entry found in the cache")] #else [RegressionOutcome("An entry has been found in the cache")] #endif private void M(int x) { Contract.Assert(x > 0); } } internal class C<X, Y> { [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = "assert unproven", PrimaryILOffset = 4, MethodILOffset = 0)] #if FIRST [RegressionOutcome("No entry found in the cache")] #else [RegressionOutcome("An entry has been found in the cache")] #endif private void M(int x) { Contract.Assert(x > 0); } } public class TryLambda { private delegate TResult MyFunc<T, TResult>(T arg); [ClousotRegressionTest] #if FIRST [RegressionOutcome("No entry found in the cache")] #else [RegressionOutcome("An entry has been found in the cache")] #endif public int SomeLambda(string mystr) { MyFunc<string, int> lengthPlusTwo = (string s) => (s.Length + 2); return lengthPlusTwo(mystr); } } } namespace WithReadonly { public class ReadonlyTest { private string field; // not readonly #if FIRST [RegressionOutcome("No entry found in the cache")] #else [RegressionOutcome("An entry has been found in the cache")] #endif public ReadonlyTest(string s) { this.field = s; } #if FIRST [RegressionOutcome("No entry found in the cache")] #else [RegressionOutcome("An entry has been found in the cache")] #endif public string DoSomething() { return this.field; } } } namespace EnumValues { public static class Helper { [ContractVerification(false)] static public Exception FailedAssertion() { Contract.Requires(false, "Randy wants you to handle all the enums ;-)"); throw new Exception(); } } public class Foo { public enum MyEnum { One, Two, Three, Quattro }; #if FIRST [RegressionOutcome("No entry found in the cache")] #else [RegressionOutcome("An entry has been found in the cache")] #endif public int Test(MyEnum e) { var i = 0; switch (e) { case MyEnum.One: i += 1; break; case MyEnum.Two: i += 2; break; case MyEnum.Three: i += 3; break; default: throw Helper.FailedAssertion(); } return i; } } }
using System; using UIKit; using System.Threading.Tasks; using System.Collections.Generic; using System.Linq; using static zsquared.C_MessageBox; using Xamarin.Forms.Maps; using zsquared; namespace vitavol { public partial class VC_AdminSiteLocation : UIViewController { C_Global Global; C_VitaUser LoggedInUser; C_ItemPicker<string> StatePicker; public VC_AdminSiteLocation (IntPtr handle) : base (handle) { } public override void ViewDidLoad() { base.ViewDidLoad(); AppDelegate myAppDelegate = (AppDelegate)UIApplication.SharedApplication.Delegate; Global = myAppDelegate.Global; LoggedInUser = Global.GetUserFromCacheNoFetch(Global.LoggedInUserId); B_Back.TouchUpInside += HandleBack; B_Save.TouchUpInside += HandleSave; UITapGestureRecognizer labelTap = new UITapGestureRecognizer(() => { C_Common.DropFirstResponder(View); //TB_Name.ResignFirstResponder(); }); L_SiteName.UserInteractionEnabled = true; L_SiteName.AddGestureRecognizer(labelTap); L_SiteLocation.UserInteractionEnabled = true; L_SiteLocation.AddGestureRecognizer(labelTap); B_GetLatLong.TouchUpInside += (sender, e) => { AI_Busy.StartAnimating(); EnableUI(false); string address = TB_Street.Text + "," + TB_City.Text + "," + TB_State.Text + "," + TB_Zip.Text; Task.Run(async () => { Xamarin.FormsMaps.Init(); Geocoder gc = new Geocoder(); IEnumerable<Position> result = await gc.GetPositionsForAddressAsync(address); void p() { AI_Busy.StopAnimating(); EnableUI(true); foreach (Position pos in result) { TB_Latitude.Text = pos.Latitude.ToString(); TB_Longitude.Text = pos.Longitude.ToString(); Global.SelectedSiteTemp.Dirty = true; break; } } UIApplication.SharedApplication.InvokeOnMainThread(p); }); }; TB_Name.AddTarget((sender, e) => { Global.SelectedSiteTemp.Dirty = true; }, UIControlEvent.AllEditingEvents); TB_Street.AddTarget((sender, e) => { Global.SelectedSiteTemp.Dirty = true; }, UIControlEvent.AllEditingEvents); TB_City.AddTarget((sender, e) => { Global.SelectedSiteTemp.Dirty = true; }, UIControlEvent.AllEditingEvents); TB_State.AddTarget((sender, e) => { Global.SelectedSiteTemp.Dirty = true; }, UIControlEvent.AllEditingEvents); TB_Zip.AddTarget((sender, e) => { Global.SelectedSiteTemp.Dirty = true; }, UIControlEvent.AllEditingEvents); TB_Latitude.AddTarget((sender, e) => { Global.SelectedSiteTemp.Dirty = true; }, UIControlEvent.AllEditingEvents); TB_Longitude.AddTarget((sender, e) => { Global.SelectedSiteTemp.Dirty = true; }, UIControlEvent.AllEditingEvents); } public override void ViewDidAppear(bool animated) { base.ViewDidAppear(animated); C_Common.SetUIColors(View); TB_Name.Text = Global.SelectedSiteTemp.Name; TB_Street.Text = Global.SelectedSiteTemp.Street; TB_City.Text = Global.SelectedSiteTemp.City; TB_Zip.Text = Global.SelectedSiteTemp.Zip; List<string> statesList = new List<string>(C_Global.StateNames); StatePicker = new C_ItemPicker<string>(TB_State, statesList); StatePicker.SetSelection(Global.SelectedSiteTemp.State); TB_Latitude.Text = Global.SelectedSiteTemp.Latitude; TB_Longitude.Text = Global.SelectedSiteTemp.Longitude; L_SiteName.Text = Global.SelectedSiteTemp.Name; } async void HandleBack(object sender, EventArgs e) { if (TB_Name.Text.Length == 0) { PerformSegue("Segue_AdminSiteLocationToAdminSite", this); return; } if (!ChangesMade()) { PerformSegue("Segue_AdminSiteLocationToAdminSite", this); return; } E_MessageBoxResults mbres1 = await MessageBox(this, "Changes", "Changes were made. Save?", E_MessageBoxButtons.YesNoCancel); if (mbres1 == E_MessageBoxResults.Cancel) return; if (mbres1 != E_MessageBoxResults.Yes) { PerformSegue("Segue_AdminSiteLocationToAdminSite", this); return; } HandleSave(sender, e); } async void HandleSave(object sender, EventArgs e) { if (TB_Name.Text.Length < 4) { E_MessageBoxResults mbres1 = await MessageBox(this, "Error", "A site name is required (3 or more characters).", E_MessageBoxButtons.Ok); return; } if (Global.SelectedSiteTemp.id == -1) { var ou = Global.SiteCache.Where(s => s.Name.ToLower() == TB_Name.Text.ToLower()); if (ou.Any()) { E_MessageBoxResults mbres1 = await MessageBox(this, "Error", "A site name with that name already exists. Choose another name.", E_MessageBoxButtons.Ok); return; } } SaveLocation(); // if this a new site, go ahead and do the create so that the other functions can work (like calendar) if (Global.SelectedSiteTemp.id == -1) { C_IOResult ior = await Global.CreateSite(Global.SelectedSiteTemp, Global.SelectedSiteTemp.ToJson(false), LoggedInUser.Token); if (!ior.Success) { E_MessageBoxResults mbres1 = await MessageBox(this, "Error", "Unable to save the changes.", E_MessageBoxButtons.Ok); return; } else { Global.SelectedSiteTemp = ior.Site; Global.SelectedSiteSlug = ior.Site.Slug; Global.SelectedSiteName = ior.Site.Name; } } PerformSegue("Segue_AdminSiteLocationToAdminSite", this); } private void SaveLocation() { Global.SelectedSiteTemp.Name = TB_Name.Text; Global.SelectedSiteTemp.Street = TB_Street.Text; Global.SelectedSiteTemp.City = TB_City.Text; Global.SelectedSiteTemp.State = StatePicker.Selection; Global.SelectedSiteTemp.Zip = TB_Zip.Text; Global.SelectedSiteTemp.Latitude = TB_Latitude.Text; Global.SelectedSiteTemp.Longitude = TB_Longitude.Text; } private bool ChangesMade() { bool c_name = Global.SelectedSiteTemp.Name != TB_Name.Text; bool c_street = Global.SelectedSiteTemp.Street != TB_Street.Text; bool c_city = Global.SelectedSiteTemp.City != TB_City.Text; bool c_state = Global.SelectedSiteTemp.State != TB_State.Text; bool c_zip = Global.SelectedSiteTemp.Zip != TB_Zip.Text; bool c_lat = Global.SelectedSiteTemp.Latitude != TB_Latitude.Text; bool c_long = Global.SelectedSiteTemp.Longitude != TB_Longitude.Text; return c_name || c_street || c_city || c_state || c_zip || c_lat || c_long; } private void EnableUI(bool en) => C_Common.EnableUI(View, en); } }
namespace android.speech { [global::MonoJavaBridge.JavaClass()] public partial class RecognizerIntent : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected RecognizerIntent(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public static global::android.content.Intent getVoiceDetailsIntent(android.content.Context arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.speech.RecognizerIntent._m0.native == global::System.IntPtr.Zero) global::android.speech.RecognizerIntent._m0 = @__env.GetStaticMethodIDNoThrow(global::android.speech.RecognizerIntent.staticClass, "getVoiceDetailsIntent", "(Landroid/content/Context;)Landroid/content/Intent;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.speech.RecognizerIntent.staticClass, global::android.speech.RecognizerIntent._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.content.Intent; } public static global::java.lang.String EXTRA_CALLING_PACKAGE { get { return "calling_package"; } } public static global::java.lang.String ACTION_RECOGNIZE_SPEECH { get { return "android.speech.action.RECOGNIZE_SPEECH"; } } public static global::java.lang.String ACTION_WEB_SEARCH { get { return "android.speech.action.WEB_SEARCH"; } } public static global::java.lang.String EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS { get { return "android.speech.extras.SPEECH_INPUT_MINIMUM_LENGTH_MILLIS"; } } public static global::java.lang.String EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS { get { return "android.speech.extras.SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS"; } } public static global::java.lang.String EXTRA_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS { get { return "android.speech.extras.SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS"; } } public static global::java.lang.String EXTRA_LANGUAGE_MODEL { get { return "android.speech.extra.LANGUAGE_MODEL"; } } public static global::java.lang.String LANGUAGE_MODEL_FREE_FORM { get { return "free_form"; } } public static global::java.lang.String LANGUAGE_MODEL_WEB_SEARCH { get { return "web_search"; } } public static global::java.lang.String EXTRA_PROMPT { get { return "android.speech.extra.PROMPT"; } } public static global::java.lang.String EXTRA_LANGUAGE { get { return "android.speech.extra.LANGUAGE"; } } public static global::java.lang.String EXTRA_MAX_RESULTS { get { return "android.speech.extra.MAX_RESULTS"; } } public static global::java.lang.String EXTRA_PARTIAL_RESULTS { get { return "android.speech.extra.PARTIAL_RESULTS"; } } public static global::java.lang.String EXTRA_RESULTS_PENDINGINTENT { get { return "android.speech.extra.RESULTS_PENDINGINTENT"; } } public static global::java.lang.String EXTRA_RESULTS_PENDINGINTENT_BUNDLE { get { return "android.speech.extra.RESULTS_PENDINGINTENT_BUNDLE"; } } public static int RESULT_NO_MATCH { get { return 1; } } public static int RESULT_CLIENT_ERROR { get { return 2; } } public static int RESULT_SERVER_ERROR { get { return 3; } } public static int RESULT_NETWORK_ERROR { get { return 4; } } public static int RESULT_AUDIO_ERROR { get { return 5; } } public static global::java.lang.String EXTRA_RESULTS { get { return "android.speech.extra.RESULTS"; } } public static global::java.lang.String DETAILS_META_DATA { get { return "android.speech.DETAILS"; } } public static global::java.lang.String ACTION_GET_LANGUAGE_DETAILS { get { return "android.speech.action.GET_LANGUAGE_DETAILS"; } } public static global::java.lang.String EXTRA_ONLY_RETURN_LANGUAGE_PREFERENCE { get { return "android.speech.extra.ONLY_RETURN_LANGUAGE_PREFERENCE"; } } public static global::java.lang.String EXTRA_LANGUAGE_PREFERENCE { get { return "android.speech.extra.LANGUAGE_PREFERENCE"; } } public static global::java.lang.String EXTRA_SUPPORTED_LANGUAGES { get { return "android.speech.extra.SUPPORTED_LANGUAGES"; } } static RecognizerIntent() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.speech.RecognizerIntent.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/speech/RecognizerIntent")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Globalization; using System.Linq; using System.Reflection; using Xunit; using Xunit.Sdk; namespace System.Numerics.Tests { /// <summary> /// Vector{T} tests that use random number generation and a unified generic test structure /// </summary> public partial class GenericVectorTests { #region Constructor Tests #region Tests for Span based constructor [Fact] public void ConstructorWithSpanByte() => TestConstructorWithSpan<byte>(); [Fact] public void ConstructorWithSpanSByte() => TestConstructorWithSpan<sbyte>(); [Fact] public void ConstructorWithSpanUInt16() => TestConstructorWithSpan<ushort>(); [Fact] public void ConstructorWithSpanInt16() => TestConstructorWithSpan<short>(); [Fact] public void ConstructorWithSpanUInt32() => TestConstructorWithSpan<uint>(); [Fact] public void ConstructorWithSpanInt32() => TestConstructorWithSpan<int>(); [Fact] public void ConstructorWithSpanUInt64() => TestConstructorWithSpan<ulong>(); [Fact] public void ConstructorWithSpanInt64() => TestConstructorWithSpan<long>(); [Fact] public void ConstructorWithSpanSingle() => TestConstructorWithSpan<float>(); [Fact] public void ConstructorWithSpanDouble() => TestConstructorWithSpan<double>(); private void TestConstructorWithSpan<T>() where T : struct { T[] values = GenerateRandomValuesForVector<T>().ToArray(); var valueSpan = new Span<T>(values); var vector = new Vector<T>(valueSpan); ValidateVector(vector, (index, val) => { Assert.Equal(values[index], val); }); } [Fact] public void SpanBasedConstructorWithLessElements_Byte() => Assert.Throws<IndexOutOfRangeException>(() => TestSpanBasedConstructorWithLessElements<byte>()); [Fact] public void SpanBasedConstructorWithLessElements_SByte() => Assert.Throws<IndexOutOfRangeException>(() => TestSpanBasedConstructorWithLessElements<sbyte>()); [Fact] public void SpanBasedConstructorWithLessElements_UInt16() => Assert.Throws<IndexOutOfRangeException>(() => TestSpanBasedConstructorWithLessElements<ushort>()); [Fact] public void SpanBasedConstructorWithLessElements_Int16() => Assert.Throws<IndexOutOfRangeException>(() => TestSpanBasedConstructorWithLessElements<short>()); [Fact] public void SpanBasedConstructorWithLessElements_UInt32() => Assert.Throws<IndexOutOfRangeException>(() => TestSpanBasedConstructorWithLessElements<uint>()); [Fact] public void SpanBasedConstructorWithLessElements_Int32() => Assert.Throws<IndexOutOfRangeException>(() => TestSpanBasedConstructorWithLessElements<int>()); [Fact] public void SpanBasedConstructorWithLessElements_UInt64() => Assert.Throws<IndexOutOfRangeException>(() => TestSpanBasedConstructorWithLessElements<ulong>()); [Fact] public void SpanBasedConstructorWithLessElements_Int64() => Assert.Throws<IndexOutOfRangeException>(() => TestSpanBasedConstructorWithLessElements<long>()); [Fact] public void SpanBasedConstructorWithLessElements_Single() => Assert.Throws<IndexOutOfRangeException>(() => TestSpanBasedConstructorWithLessElements<float>()); [Fact] public void SpanBasedConstructorWithLessElements_Double() => Assert.Throws<IndexOutOfRangeException>(() => TestSpanBasedConstructorWithLessElements<double>()); private void TestSpanBasedConstructorWithLessElements<T>() where T : struct { T[] values = GenerateRandomValuesForVector<T>(Vector<T>.Count - 1).ToArray(); var vector = new Vector<T>(new Span<T>(values)); } #endregion Tests for Span based constructor #region Tests for Array based constructor [Fact] public void ArrayBasedConstructor_Byte() => TestArrayBasedConstructor<byte>(); [Fact] public void ArrayBasedConstructor_SByte() => TestArrayBasedConstructor<sbyte>(); [Fact] public void ArrayBasedConstructor_UInt16() => TestArrayBasedConstructor<ushort>(); [Fact] public void ArrayBasedConstructor_Int16() => TestArrayBasedConstructor<short>(); [Fact] public void ArrayBasedConstructor_UInt32() => TestArrayBasedConstructor<uint>(); [Fact] public void ArrayBasedConstructor_Int32() => TestArrayBasedConstructor<int>(); [Fact] public void ArrayBasedConstructor_UInt64() => TestArrayBasedConstructor<ulong>(); [Fact] public void ArrayBasedConstructor_Int64() => TestArrayBasedConstructor<long>(); [Fact] public void ArrayBasedConstructor_Single() => TestArrayBasedConstructor<float>(); [Fact] public void ArrayBasedConstructor_Double() => TestArrayBasedConstructor<double>(); private void TestArrayBasedConstructor<T>() where T : struct { T[] values = GenerateRandomValuesForVector<T>(Vector<T>.Count).ToArray(); var vector = new Vector<T>(values); ValidateVector(vector, (index, val) => { Assert.Equal(values[index], val); }); } [Fact] public void ArrayIndexBasedConstructor_Byte() => TestArrayIndexBasedConstructor<byte>(); [Fact] public void ArrayIndexBasedConstructor_SByte() => TestArrayIndexBasedConstructor<sbyte>(); [Fact] public void ArrayIndexBasedConstructor_UInt16() => TestArrayIndexBasedConstructor<ushort>(); [Fact] public void ArrayIndexBasedConstructor_Int16() => TestArrayIndexBasedConstructor<short>(); [Fact] public void ArrayIndexBasedConstructor_UInt32() => TestArrayIndexBasedConstructor<uint>(); [Fact] public void ArrayIndexBasedConstructor_Int32() => TestArrayIndexBasedConstructor<int>(); [Fact] public void ArrayIndexBasedConstructor_UInt64() => TestArrayIndexBasedConstructor<ulong>(); [Fact] public void ArrayIndexBasedConstructor_Int64() => TestArrayIndexBasedConstructor<long>(); [Fact] public void ArrayIndexBasedConstructor_Single() => TestArrayIndexBasedConstructor<float>(); [Fact] public void ArrayIndexBasedConstructor_Double() => TestArrayIndexBasedConstructor<double>(); private void TestArrayIndexBasedConstructor<T>() where T : struct { T[] values = GenerateRandomValuesForVector<T>(Vector<T>.Count * 2).ToArray(); int offset = Vector<T>.Count - 1; var vector = new Vector<T>(values, offset); ValidateVector(vector, (index, val) => { Assert.Equal(values[offset + index], val); }); } [Fact] public void ArrayBasedConstructorWithLessElements_Byte() => TestArrayBasedConstructorWithLessElements<byte>(); [Fact] public void ArrayBasedConstructorWithLessElements_SByte() => TestArrayBasedConstructorWithLessElements<sbyte>(); [Fact] public void ArrayBasedConstructorWithLessElements_UInt16() => TestArrayBasedConstructorWithLessElements<ushort>(); [Fact] public void ArrayBasedConstructorWithLessElements_Int16() => TestArrayBasedConstructorWithLessElements<short>(); [Fact] public void ArrayBasedConstructorWithLessElements_UInt32() => TestArrayBasedConstructorWithLessElements<uint>(); [Fact] public void ArrayBasedConstructorWithLessElements_Int32() => TestArrayBasedConstructorWithLessElements<int>(); [Fact] public void ArrayBasedConstructorWithLessElements_UInt64() => TestArrayBasedConstructorWithLessElements<ulong>(); [Fact] public void ArrayBasedConstructorWithLessElements_Int64() => TestArrayBasedConstructorWithLessElements<long>(); [Fact] public void ArrayBasedConstructorWithLessElements_Single() => TestArrayBasedConstructorWithLessElements<float>(); [Fact] public void ArrayBasedConstructorWithLessElements_Double() => TestArrayBasedConstructorWithLessElements<double>(); private void TestArrayBasedConstructorWithLessElements<T>() where T : struct { T[] values = GenerateRandomValuesForVector<T>(Vector<T>.Count - 1).ToArray(); Assert.Throws<IndexOutOfRangeException>(() => new Vector<T>(values)); } [Fact] public void ArrayIndexBasedConstructorLessElements_Byte() => TestArrayIndexBasedConstructorLessElements<byte>(); [Fact] public void ArrayIndexBasedConstructorLessElements_SByte() => TestArrayIndexBasedConstructorLessElements<sbyte>(); [Fact] public void ArrayIndexBasedConstructorLessElements_UInt16() => TestArrayIndexBasedConstructorLessElements<ushort>(); [Fact] public void ArrayIndexBasedConstructorLessElements_Int16() => TestArrayIndexBasedConstructorLessElements<short>(); [Fact] public void ArrayIndexBasedConstructorLessElements_UInt32() => TestArrayIndexBasedConstructorLessElements<uint>(); [Fact] public void ArrayIndexBasedConstructorLessElements_Int32() => TestArrayIndexBasedConstructorLessElements<int>(); [Fact] public void ArrayIndexBasedConstructorLessElements_UInt64() => TestArrayIndexBasedConstructorLessElements<ulong>(); [Fact] public void ArrayIndexBasedConstructorLessElements_Int64() => TestArrayIndexBasedConstructorLessElements<long>(); [Fact] public void ArrayIndexBasedConstructorLessElements_Single() => TestArrayIndexBasedConstructorLessElements<float>(); [Fact] public void ArrayIndexBasedConstructorLessElements_Double() => TestArrayIndexBasedConstructorLessElements<double>(); private void TestArrayIndexBasedConstructorLessElements<T>() where T : struct { T[] values = GenerateRandomValuesForVector<T>(Vector<T>.Count * 2).ToArray(); Assert.Throws<IndexOutOfRangeException>(() => new Vector<T>(values, Vector<T>.Count + 1)); } #endregion Tests for Array based constructor #region Tests for constructors using unsupported types [Fact] public void ConstructorWithUnsupportedTypes_Guid() => TestConstructorWithUnsupportedTypes<Guid>(); [Fact] public void ConstructorWithUnsupportedTypes_DateTime() => TestConstructorWithUnsupportedTypes<DateTime>(); [Fact] public void ConstructorWithUnsupportedTypes_Char() => TestConstructorWithUnsupportedTypes<char>(); private void TestConstructorWithUnsupportedTypes<T>() where T : struct { Assert.Throws<NotSupportedException>(() => new Vector<T>(new Span<T>(new T[4]))); } #endregion Tests for constructors using unsupported types #endregion Constructor Tests } }
using System; using OpenTK.Platform.iPhoneOS; using OpenTK.Graphics.ES11; using MonoTouch.UIKit; using MonoTouch.Foundation; using System.Drawing; using MonoTouch.ObjCRuntime; using MonoTouch.OpenGLES; using System.Runtime.InteropServices; using MonoTouch.CoreGraphics; using DropBoxSync.iOS; using System.Collections.Generic; using System.Linq; namespace DropboxPaint { public class PaintingView : iPhoneOSGameView { public const float BrushOpacity = 1.0f / 3.0f; public const int BrushPixelStep = 3; public const int BrushScale = 2; public const float Luminosity = 0.75f; public const float Saturation = 1.0f; uint brushTexture, drawingTexture; bool firstTouch; PointF Location; PointF PreviousLocation; Line _line; [Export ("layerClass")] public static Class LayerClass () { return iPhoneOSGameView.GetLayerClass (); } public PaintingView (RectangleF frame) : base (frame) { LayerRetainsBacking = true; LayerColorFormat = EAGLColorFormat.RGBA8; ContextRenderingApi = EAGLRenderingAPI.OpenGLES1; CreateFrameBuffer(); MakeCurrent(); var brushImage = UIImage.FromFile ("Particle.png").CGImage; var width = brushImage.Width; var height = brushImage.Height; if (brushImage != null) { IntPtr brushData = Marshal.AllocHGlobal (width * height * 4); if (brushData == IntPtr.Zero) throw new OutOfMemoryException (); try { using (var brushContext = new CGBitmapContext (brushData, width, width, 8, width * 4, brushImage.ColorSpace, CGImageAlphaInfo.PremultipliedLast)) { brushContext.DrawImage (new RectangleF (0.0f, 0.0f, (float) width, (float) height), brushImage); } GL.GenTextures (1, ref brushTexture); GL.BindTexture (All.Texture2D, brushTexture); GL.TexImage2D (All.Texture2D, 0, (int) All.Rgba, width, height, 0, All.Rgba, All.UnsignedByte, brushData); } finally { Marshal.FreeHGlobal (brushData); } GL.TexParameter (All.Texture2D, All.TextureMinFilter, (int) All.Linear); GL.Enable (All.Texture2D); GL.BlendFunc (All.SrcAlpha, All.One); GL.Enable (All.Blend); } GL.Disable (All.Dither); GL.MatrixMode (All.Projection); GL.Ortho (0, frame.Width, 0, frame.Height, -1, 1); GL.MatrixMode (All.Modelview); GL.Enable (All.Texture2D); GL.EnableClientState (All.VertexArray); GL.Enable (All.Blend); GL.BlendFunc (All.SrcAlpha, All.One); GL.Enable (All.PointSpriteOes); GL.TexEnv (All.PointSpriteOes, All.CoordReplaceOes, (float) All.True); GL.PointSize (width / BrushScale); Erase (); // Set EventHandlers DropboxDatabase.Shared.LinesUpdated += HandleLinesUpdated; DropboxDatabase.Shared.ClearLines += HandleClearLines; } protected override void Dispose (bool disposing) { base.Dispose (disposing); GL.DeleteTextures (1, ref drawingTexture); } public void Erase () { GL.Clear ((uint) All.ColorBufferBit); SwapBuffers (); } float[] vertexBuffer; int vertexMax = 64; private void RenderLineFromPoint (PointF start, PointF end) { int vertexCount = 0; if (vertexBuffer == null) { vertexBuffer = new float [vertexMax * 2]; } var count = Math.Max (Math.Ceiling (Math.Sqrt ((end.X - start.X) * (end.X - start.X) + (end.Y - start.Y) * (end.Y - start.Y)) / BrushPixelStep), 1); for (int i = 0; i < count; ++i, ++vertexCount) { if (vertexCount == vertexMax) { vertexMax *= 2; Array.Resize (ref vertexBuffer, vertexMax * 2); } vertexBuffer [2 * vertexCount + 0] = start.X + (end.X - start.X) * (float) i / (float) count; vertexBuffer [2 * vertexCount + 1] = start.Y + (end.Y - start.Y) * (float) i / (float) count; } GL.VertexPointer (2, All.Float, 0, vertexBuffer); GL.DrawArrays (All.Points, 0, vertexCount); SwapBuffers (); } int dataofs = 0; void HandleLinesUpdated (object sender, EventArgs e) { dataofs = 0; PerformSelector (new Selector ("playback"), null, 0.2f); } void HandleClearLines (object sender, EventArgs e) { Erase (); DropboxDatabase.Shared.DeleteAll (); } [Export ("playback")] void Playback () { if (DropboxDatabase.Shared.AddedLines.Count > 0) { Line line = DropboxDatabase.Shared.AddedLines [dataofs]; if (line != null) { List<PointF> points = line.Points; if (DropboxDatabase.Shared.DrawnLines.SingleOrDefault (l => l.Id == line.Id) == null) { DropboxDatabase.Shared.DrawnLines.Add (line); Console.WriteLine ("Drawing line {0}", line.Id); Color.ChangeBrushColor (line.Color); for (int i = 0; i < points.Count - 1; i++) RenderLineFromPoint (points [i], points [i + 1]); } if (dataofs < DropboxDatabase.Shared.AddedLines.Count - 1) { dataofs ++; PerformSelector (new Selector ("playback"), null, 0.01f); } } else { Console.WriteLine ("NULL found"); dataofs ++; } } } public override void TouchesBegan (MonoTouch.Foundation.NSSet touches, MonoTouch.UIKit.UIEvent e) { var bounds = Bounds; var touch = (UITouch) e.TouchesForView (this).AnyObject; firstTouch = true; Location = touch.LocationInView (this); Location.Y = bounds.Height - Location.Y; _line = new Line (); _line.Color = Color.Selected; // Change back as it might have changed on recieved line Color.ChangeBrushColor (Color.Selected); } public override void TouchesMoved (MonoTouch.Foundation.NSSet touches, MonoTouch.UIKit.UIEvent e) { var bounds = Bounds; var touch = (UITouch) e.TouchesForView (this).AnyObject; if (firstTouch) { firstTouch = false; PreviousLocation = touch.PreviousLocationInView (this); PreviousLocation.Y = bounds.Height - PreviousLocation.Y; } else { Location = touch.LocationInView (this); Location.Y = bounds.Height - Location.Y; PreviousLocation = touch.PreviousLocationInView (this); PreviousLocation.Y = bounds.Height - PreviousLocation.Y; } if (_line.Points == null) _line.Points = new List<PointF> (); _line.Points.Add (new PointF (Location.X, Location.Y)); RenderLineFromPoint (PreviousLocation, Location); } public override void TouchesEnded (MonoTouch.Foundation.NSSet touches, MonoTouch.UIKit.UIEvent e) { var bounds = Bounds; var touch = (UITouch) e.TouchesForView (this).AnyObject; if (firstTouch) { firstTouch = false; PreviousLocation = touch.PreviousLocationInView (this); PreviousLocation.Y = bounds.Height - PreviousLocation.Y; RenderLineFromPoint (PreviousLocation, Location); if (_line.Points == null) _line.Points = new List<PointF> (); _line.Points.Add (new PointF (Location.X, Location.Y)); } DropboxDatabase.Shared.InsertLine (_line); } public override void TouchesCancelled (MonoTouch.Foundation.NSSet touches, MonoTouch.UIKit.UIEvent e) { } } }
#region PDFsharp - A .NET library for processing PDF // // Authors: // Stefan Lange (mailto:[email protected]) // // Copyright (c) 2005-2009 empira Software GmbH, Cologne (Germany) // // http://www.pdfsharp.com // http://sourceforge.net/projects/pdfsharp // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion using System; using System.Diagnostics; using System.Resources; using System.Reflection; using System.Text.RegularExpressions; using PdfSharp.Drawing; using PdfSharp.Pdf; #pragma warning disable 1591 namespace PdfSharp { /// <summary> /// The Pdf-Sharp-XPS-String-Resources. /// </summary> static class PSXSR { #region General messages public static string IndexOutOfRange { get { return "The index is out of range."; } } public static string InvalidValue(int val, string name, int min, int max) { return Format("{0} is not a valid value for {1}. {1} should be greater than or equal to {2} and less than or equal to {3}.", val, name, min, max); } public static string PageMustBelongToPdfDocument { get { return "The page do not belong to the PDF document."; } } #endregion #region XPS Parser /// <summary> /// "Content must start with element or comment." /// </summary> public static string ElementExpected { get { return "Content must start with element or comment."; } } /// <summary> /// "Must stand on element." /// </summary> public static string MustStandOnElement { get { return "Must stand on element."; } } ///// <summary> ///// "Unexpected element." ///// </summary> //public static string UnexpectedElement //{ // get { return "Unexpected element."; } //} /// <summary> /// "Unexpected attribute '{0}'." /// </summary> public static string UnexpectedAttribute(string name) { return String.Format("Unexpected attribute '{0}'.", name); } /// <summary> /// "Unexpected element. Expected '{0}', but found '{1}'" /// </summary> public static string UnexpectedElement(string expected, string found) { return String.Format("Unexpected element. Expected '{0}', but found '{1}'", expected, found); } #endregion #region Helper functions /// <summary> /// Loads the message from the resource associated with the enum type and formats it /// using 'String.Format'. Because this function is intended to be used during error /// handling it never raises an exception. /// </summary> /// <param name="id">The type of the parameter identifies the resource /// and the name of the enum identifies the message in the resource.</param> /// <param name="args">Parameters passed through 'String.Format'.</param> /// <returns>The formatted message.</returns> public static string Format(PSXMsgID id, params object[] args) { string message; try { message = PSXSR.GetString(id); if (message != null) message = Format(message, args); else message = "INTERNAL ERROR: Message not found in resources."; return message; } catch (Exception ex) { message = String.Format("UNEXPECTED ERROR while formatting message with ID {0}: {1}", id.ToString(), ex.ToString()); } return message; } public static string Format(string format, params object[] args) { if (format == null) throw new ArgumentNullException("format"); string message; try { message = String.Format(format, args); } catch (Exception ex) { message = String.Format("UNEXPECTED ERROR while formatting message '{0}': {1}", format, ex.ToString()); } return message; } /// <summary> /// Gets the localized message identified by the specified DomMsgID. /// </summary> public static string GetString(PSXMsgID id) { return PSXSR.ResMngr.GetString(id.ToString()); } #endregion #region Resource manager /// <summary> /// Gets the resource manager for this module. /// </summary> public static ResourceManager ResMngr { get { if (PSXSR.resmngr == null) { #if true_ // Force the english language, even on a German PC. System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture; #endif PSXSR.resmngr = new ResourceManager("PdfSharp.Resources.Messages", Assembly.GetExecutingAssembly()); } return PSXSR.resmngr; } } static ResourceManager resmngr; /// <summary> /// Writes all messages defined by PSXMsgID. /// </summary> [Conditional("DEBUG")] public static void TestResourceMessages() { string[] names = Enum.GetNames(typeof(PSXMsgID)); foreach (string name in names) { string message = String.Format("{0}: '{1}'", name, ResMngr.GetString(name)); Debug.Assert(message != null); Debug.WriteLine(message); } } static PSXSR() { TestResourceMessages(); } #endregion } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.Sql.LegacySdk; using Microsoft.Azure.Management.Sql.LegacySdk.Models; namespace Microsoft.Azure.Management.Sql.LegacySdk { /// <summary> /// The Windows Azure SQL Database management API provides a RESTful set of /// web services that interact with Windows Azure SQL Database services to /// manage your databases. The API enables users to create, retrieve, /// update, and delete databases and servers. /// </summary> public static partial class ImportExportOperationsExtensions { /// <summary> /// Exports a Azure SQL Database to bacpac. To determine the status of /// the operation call GetImportExportOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.LegacySdk.IImportExportOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server on which the database is /// hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database to export. /// </param> /// <param name='parameters'> /// Required. The required parameters for exporting a database. /// </param> /// <returns> /// Response Azure Sql Import/Export operations. /// </returns> public static ImportExportResponse Export(this IImportExportOperations operations, string resourceGroupName, string serverName, string databaseName, ExportRequestParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IImportExportOperations)s).ExportAsync(resourceGroupName, serverName, databaseName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Exports a Azure SQL Database to bacpac. To determine the status of /// the operation call GetImportExportOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.LegacySdk.IImportExportOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server on which the database is /// hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database to export. /// </param> /// <param name='parameters'> /// Required. The required parameters for exporting a database. /// </param> /// <returns> /// Response Azure Sql Import/Export operations. /// </returns> public static Task<ImportExportResponse> ExportAsync(this IImportExportOperations operations, string resourceGroupName, string serverName, string databaseName, ExportRequestParameters parameters) { return operations.ExportAsync(resourceGroupName, serverName, databaseName, parameters, CancellationToken.None); } /// <summary> /// Gets the status of an Azure Sql Database import/export operation. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.LegacySdk.IImportExportOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation /// </param> /// <returns> /// Response for Azure Sql Import/Export Status operation. /// </returns> public static ImportExportOperationStatusResponse GetImportExportOperationStatus(this IImportExportOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((IImportExportOperations)s).GetImportExportOperationStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the status of an Azure Sql Database import/export operation. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.LegacySdk.IImportExportOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation /// </param> /// <returns> /// Response for Azure Sql Import/Export Status operation. /// </returns> public static Task<ImportExportOperationStatusResponse> GetImportExportOperationStatusAsync(this IImportExportOperations operations, string operationStatusLink) { return operations.GetImportExportOperationStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// Imports a bacpac to Azure SQL Database. To determine the status of /// the operation call GetImportExportOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.LegacySdk.IImportExportOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server on which the database is /// hosted. /// </param> /// <param name='parameters'> /// Required. The required parameters for importing to a database. /// </param> /// <returns> /// Response Azure Sql Import/Export operations. /// </returns> public static ImportExportResponse Import(this IImportExportOperations operations, string resourceGroupName, string serverName, ImportRequestParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IImportExportOperations)s).ImportAsync(resourceGroupName, serverName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Imports a bacpac to Azure SQL Database. To determine the status of /// the operation call GetImportExportOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.LegacySdk.IImportExportOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server on which the database is /// hosted. /// </param> /// <param name='parameters'> /// Required. The required parameters for importing to a database. /// </param> /// <returns> /// Response Azure Sql Import/Export operations. /// </returns> public static Task<ImportExportResponse> ImportAsync(this IImportExportOperations operations, string resourceGroupName, string serverName, ImportRequestParameters parameters) { return operations.ImportAsync(resourceGroupName, serverName, parameters, CancellationToken.None); } /// <summary> /// Imports a bacpac to an empty Azure SQL Database. To determine the /// status of the operation call GetImportExportOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.LegacySdk.IImportExportOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server on which the database is /// hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database to import to. /// </param> /// <param name='parameters'> /// Required. The required parameters for importing to a database. /// </param> /// <returns> /// Response Azure Sql Import/Export operations. /// </returns> public static ImportExportResponse ImportToExistingDatabase(this IImportExportOperations operations, string resourceGroupName, string serverName, string databaseName, ImportExtensionRequestParameteres parameters) { return Task.Factory.StartNew((object s) => { return ((IImportExportOperations)s).ImportToExistingDatabaseAsync(resourceGroupName, serverName, databaseName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Imports a bacpac to an empty Azure SQL Database. To determine the /// status of the operation call GetImportExportOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.LegacySdk.IImportExportOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server on which the database is /// hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database to import to. /// </param> /// <param name='parameters'> /// Required. The required parameters for importing to a database. /// </param> /// <returns> /// Response Azure Sql Import/Export operations. /// </returns> public static Task<ImportExportResponse> ImportToExistingDatabaseAsync(this IImportExportOperations operations, string resourceGroupName, string serverName, string databaseName, ImportExtensionRequestParameteres parameters) { return operations.ImportToExistingDatabaseAsync(resourceGroupName, serverName, databaseName, parameters, CancellationToken.None); } } }
using System; using System.IO; using System.Collections; using System.Runtime.InteropServices; namespace Trinet.Networking { #region Share Type /// <summary> /// Type of share /// </summary> [Flags] public enum ShareType { /// <summary>Disk share</summary> Disk = 0, /// <summary>Printer share</summary> Printer = 1, /// <summary>Device share</summary> Device = 2, /// <summary>IPC share</summary> IPC = 3, /// <summary>Special share</summary> Special = -2147483648, // 0x80000000, } #endregion #region Share /// <summary> /// Information about a local share /// </summary> public class Share { #region Private data private string _server; private string _netName; private string _path; private ShareType _shareType; private string _remark; #endregion #region Constructor /// <summary> /// Constructor /// </summary> /// <param name="Server"></param> /// <param name="shi"></param> public Share(string server, string netName, string path, ShareType shareType, string remark) { if (ShareType.Special == shareType && "IPC$" == netName) { shareType |= ShareType.IPC; } _server = server; _netName = netName; _path = path; _shareType = shareType; _remark = remark; } #endregion #region Properties /// <summary> /// The name of the computer that this share belongs to /// </summary> public string Server { get { return _server; } } /// <summary> /// Share name /// </summary> public string NetName { get { return _netName; } } /// <summary> /// Local path /// </summary> public string Path { get { return _path; } } /// <summary> /// Share type /// </summary> public ShareType ShareType { get { return _shareType; } } /// <summary> /// Comment /// </summary> public string Remark { get { return _remark; } } /// <summary> /// Returns true if this is a file system share /// </summary> public bool IsFileSystem { get { // Shared device if (0 != (_shareType & ShareType.Device)) return false; // IPC share if (0 != (_shareType & ShareType.IPC)) return false; // Shared printer if (0 != (_shareType & ShareType.Printer)) return false; // Standard disk share if (0 == (_shareType & ShareType.Special)) return true; // Special disk share (e.g. C$) if (ShareType.Special == _shareType && null != _netName && 0 != _netName.Length) return true; else return false; } } /// <summary> /// Get the root of a disk-based share /// </summary> public DirectoryInfo Root { get { if (IsFileSystem) { if (null == _server || 0 == _server.Length) if (null == _path || 0 == _path.Length) return new DirectoryInfo(ToString()); else return new DirectoryInfo(_path); else return new DirectoryInfo(ToString()); } else return null; } } #endregion /// <summary> /// Returns the path to this share /// </summary> /// <returns></returns> public override string ToString() { if (null == _server || 0 == _server.Length) { return string.Format(@"\\{0}\{1}", Environment.MachineName, _netName); } else return string.Format(@"\\{0}\{1}", _server, _netName); } /// <summary> /// Returns true if this share matches the local path /// </summary> /// <param name="path"></param> /// <returns></returns> public bool MatchesPath(string path) { if (!IsFileSystem) return false; if (null == path || 0 == path.Length) return true; return path.ToLower().StartsWith(_path.ToLower()); } } #endregion #region Share Collection /// <summary> /// A collection of shares /// </summary> public class ShareCollection : ReadOnlyCollectionBase { #region Platform /// <summary> /// Is this an NT platform? /// </summary> protected static bool IsNT { get { return (PlatformID.Win32NT == Environment.OSVersion.Platform); } } /// <summary> /// Returns true if this is Windows 2000 or higher /// </summary> protected static bool IsW2KUp { get { OperatingSystem os = Environment.OSVersion; if (PlatformID.Win32NT == os.Platform && os.Version.Major >= 5) return true; else return false; } } #endregion #region Interop #region Constants /// <summary>Maximum path length</summary> protected const int MAX_PATH = 260; /// <summary>No error</summary> protected const int NO_ERROR = 0; /// <summary>Access denied</summary> protected const int ERROR_ACCESS_DENIED = 5; /// <summary>Access denied</summary> protected const int ERROR_WRONG_LEVEL = 124; /// <summary>More data available</summary> protected const int ERROR_MORE_DATA = 234; /// <summary>Not connected</summary> protected const int ERROR_NOT_CONNECTED = 2250; /// <summary>Level 1</summary> protected const int UNIVERSAL_NAME_INFO_LEVEL = 1; /// <summary>Max extries (9x)</summary> protected const int MAX_SI50_ENTRIES = 20; #endregion #region Structures /// <summary>Unc name</summary> [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] protected struct UNIVERSAL_NAME_INFO { [MarshalAs(UnmanagedType.LPTStr)] public string lpUniversalName; } /// <summary>Share information, NT, level 2</summary> /// <remarks> /// Requires admin rights to work. /// </remarks> [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] protected struct SHARE_INFO_2 { [MarshalAs(UnmanagedType.LPWStr)] public string NetName; public ShareType ShareType; [MarshalAs(UnmanagedType.LPWStr)] public string Remark; public int Permissions; public int MaxUsers; public int CurrentUsers; [MarshalAs(UnmanagedType.LPWStr)] public string Path; [MarshalAs(UnmanagedType.LPWStr)] public string Password; } /// <summary>Share information, NT, level 1</summary> /// <remarks> /// Fallback when no admin rights. /// </remarks> [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] protected struct SHARE_INFO_1 { [MarshalAs(UnmanagedType.LPWStr)] public string NetName; public ShareType ShareType; [MarshalAs(UnmanagedType.LPWStr)] public string Remark; } /// <summary>Share information, Win9x</summary> [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack=1)] protected struct SHARE_INFO_50 { [MarshalAs(UnmanagedType.ByValTStr, SizeConst=13)] public string NetName; public byte bShareType; public ushort Flags; [MarshalAs(UnmanagedType.LPTStr)] public string Remark; [MarshalAs(UnmanagedType.LPTStr)] public string Path; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=9)] public string PasswordRW; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=9)] public string PasswordRO; public ShareType ShareType { get { return (ShareType)((int)bShareType & 0x7F); } } } /// <summary>Share information level 1, Win9x</summary> [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack=1)] protected struct SHARE_INFO_1_9x { [MarshalAs(UnmanagedType.ByValTStr, SizeConst=13)] public string NetName; public byte Padding; public ushort bShareType; [MarshalAs(UnmanagedType.LPTStr)] public string Remark; public ShareType ShareType { get { return (ShareType)((int)bShareType & 0x7FFF); } } } #endregion #region Functions /// <summary>Get a UNC name</summary> [DllImport("mpr", CharSet=CharSet.Auto)] protected static extern int WNetGetUniversalName (string lpLocalPath, int dwInfoLevel, ref UNIVERSAL_NAME_INFO lpBuffer, ref int lpBufferSize); /// <summary>Get a UNC name</summary> [DllImport("mpr", CharSet=CharSet.Auto)] protected static extern int WNetGetUniversalName (string lpLocalPath, int dwInfoLevel, IntPtr lpBuffer, ref int lpBufferSize); /// <summary>Enumerate shares (NT)</summary> [DllImport("netapi32", CharSet=CharSet.Unicode)] protected static extern int NetShareEnum (string lpServerName, int dwLevel, out IntPtr lpBuffer, int dwPrefMaxLen, out int entriesRead, out int totalEntries, ref int hResume); /// <summary>Enumerate shares (9x)</summary> [DllImport("svrapi", CharSet=CharSet.Ansi)] protected static extern int NetShareEnum( [MarshalAs(UnmanagedType.LPTStr)] string lpServerName, int dwLevel, IntPtr lpBuffer, ushort cbBuffer, out ushort entriesRead, out ushort totalEntries); /// <summary>Free the buffer (NT)</summary> [DllImport("netapi32")] protected static extern int NetApiBufferFree(IntPtr lpBuffer); #endregion #region Enumerate shares /// <summary> /// Enumerates the shares on Windows NT /// </summary> /// <param name="server">The server name</param> /// <param name="shares">The ShareCollection</param> protected static void EnumerateSharesNT(string server, ShareCollection shares) { int level = 2; int entriesRead, totalEntries, nRet, hResume = 0; IntPtr pBuffer = IntPtr.Zero; try { nRet = NetShareEnum(server, level, out pBuffer, -1, out entriesRead, out totalEntries, ref hResume); if (ERROR_ACCESS_DENIED == nRet) { //Need admin for level 2, drop to level 1 level = 1; nRet = NetShareEnum(server, level, out pBuffer, -1, out entriesRead, out totalEntries, ref hResume); } if (NO_ERROR == nRet && entriesRead > 0) { Type t = (2 == level) ? typeof(SHARE_INFO_2) : typeof(SHARE_INFO_1); int offset = Marshal.SizeOf(t); for (int i=0, lpItem=pBuffer.ToInt32(); i<entriesRead; i++, lpItem+=offset) { IntPtr pItem = new IntPtr(lpItem); if (1 == level) { SHARE_INFO_1 si = (SHARE_INFO_1)Marshal.PtrToStructure(pItem, t); shares.Add(si.NetName, string.Empty, si.ShareType, si.Remark); } else { SHARE_INFO_2 si = (SHARE_INFO_2)Marshal.PtrToStructure(pItem, t); shares.Add(si.NetName, si.Path, si.ShareType, si.Remark); } } } } finally { // Clean up buffer allocated by system if (IntPtr.Zero != pBuffer) NetApiBufferFree(pBuffer); } } /// <summary> /// Enumerates the shares on Windows 9x /// </summary> /// <param name="server">The server name</param> /// <param name="shares">The ShareCollection</param> protected static void EnumerateShares9x(string server, ShareCollection shares) { int level = 50; int nRet = 0; ushort entriesRead, totalEntries; Type t = typeof(SHARE_INFO_50); int size = Marshal.SizeOf(t); ushort cbBuffer = (ushort)(MAX_SI50_ENTRIES * size); //On Win9x, must allocate buffer before calling API IntPtr pBuffer = Marshal.AllocHGlobal(cbBuffer); try { nRet = NetShareEnum(server, level, pBuffer, cbBuffer, out entriesRead, out totalEntries); if (ERROR_WRONG_LEVEL == nRet) { level = 1; t = typeof(SHARE_INFO_1_9x); size = Marshal.SizeOf(t); nRet = NetShareEnum(server, level, pBuffer, cbBuffer, out entriesRead, out totalEntries); } if (NO_ERROR == nRet || ERROR_MORE_DATA == nRet) { for (int i=0, lpItem=pBuffer.ToInt32(); i<entriesRead; i++, lpItem+=size) { IntPtr pItem = new IntPtr(lpItem); if (1 == level) { SHARE_INFO_1_9x si = (SHARE_INFO_1_9x)Marshal.PtrToStructure(pItem, t); shares.Add(si.NetName, string.Empty, si.ShareType, si.Remark); } else { SHARE_INFO_50 si = (SHARE_INFO_50)Marshal.PtrToStructure(pItem, t); shares.Add(si.NetName, si.Path, si.ShareType, si.Remark); } } } else Console.WriteLine(nRet); } finally { //Clean up buffer Marshal.FreeHGlobal(pBuffer); } } /// <summary> /// Enumerates the shares /// </summary> /// <param name="server">The server name</param> /// <param name="shares">The ShareCollection</param> protected static void EnumerateShares(string server, ShareCollection shares) { if (null != server && 0 != server.Length && !IsW2KUp) { server = server.ToUpper(); // On NT4, 9x and Me, server has to start with "\\" if (!('\\' == server[0] && '\\' == server[1])) server = @"\\" + server; } if (IsNT) EnumerateSharesNT(server, shares); else EnumerateShares9x(server, shares); } #endregion #endregion #region Static methods /// <summary> /// Returns true if fileName is a valid local file-name of the form: /// X:\, where X is a drive letter from A-Z /// </summary> /// <param name="fileName">The filename to check</param> /// <returns></returns> public static bool IsValidFilePath(string fileName) { if (null == fileName || 0 == fileName.Length) return false; char drive = char.ToUpper(fileName[0]); if ('A' > drive || drive > 'Z') return false; else if (Path.VolumeSeparatorChar != fileName[1]) return false; else if (Path.DirectorySeparatorChar != fileName[2]) return false; else return true; } /// <summary> /// Returns the UNC path for a mapped drive or local share. /// </summary> /// <param name="fileName">The path to map</param> /// <returns>The UNC path (if available)</returns> public static string PathToUnc(string fileName) { if (null == fileName || 0 == fileName.Length) return string.Empty; fileName = Path.GetFullPath(fileName); if (!IsValidFilePath(fileName)) return fileName; int nRet = 0; UNIVERSAL_NAME_INFO rni = new UNIVERSAL_NAME_INFO(); int bufferSize = Marshal.SizeOf(rni); nRet = WNetGetUniversalName( fileName, UNIVERSAL_NAME_INFO_LEVEL, ref rni, ref bufferSize); if (ERROR_MORE_DATA == nRet) { IntPtr pBuffer = Marshal.AllocHGlobal(bufferSize);; try { nRet = WNetGetUniversalName( fileName, UNIVERSAL_NAME_INFO_LEVEL, pBuffer, ref bufferSize); if (NO_ERROR == nRet) { rni = (UNIVERSAL_NAME_INFO)Marshal.PtrToStructure(pBuffer, typeof(UNIVERSAL_NAME_INFO)); } } finally { Marshal.FreeHGlobal(pBuffer); } } switch (nRet) { case NO_ERROR: return rni.lpUniversalName; case ERROR_NOT_CONNECTED: //Local file-name ShareCollection shi = LocalShares; if (null != shi) { Share share = shi[fileName]; if (null != share) { string path = share.Path; if (null != path && 0 != path.Length) { int index = path.Length; if (Path.DirectorySeparatorChar != path[path.Length - 1]) index++; if (index < fileName.Length) fileName = fileName.Substring(index); else fileName = string.Empty; fileName = Path.Combine(share.ToString(), fileName); } } } return fileName; default: Console.WriteLine("Unknown return value: {0}", nRet); return string.Empty; } } /// <summary> /// Returns the local <see cref="Share"/> object with the best match /// to the specified path. /// </summary> /// <param name="fileName"></param> /// <returns></returns> public static Share PathToShare(string fileName) { if (null == fileName || 0 == fileName.Length) return null; fileName = Path.GetFullPath(fileName); if (!IsValidFilePath(fileName)) return null; ShareCollection shi = LocalShares; if (null == shi) return null; else return shi[fileName]; } #endregion #region Local shares /// <summary>The local shares</summary> private static ShareCollection _local = null; /// <summary> /// Return the local shares /// </summary> public static ShareCollection LocalShares { get { if (null == _local) _local = new ShareCollection(); return _local; } } /// <summary> /// Return the shares for a specified machine /// </summary> /// <param name="server"></param> /// <returns></returns> public static ShareCollection GetShares(string server) { return new ShareCollection(server); } #endregion #region Private Data /// <summary>The name of the server this collection represents</summary> private string _server; #endregion #region Constructor /// <summary> /// Default constructor - local machine /// </summary> public ShareCollection() { _server = string.Empty; EnumerateShares(_server, this); } /// <summary> /// Constructor /// </summary> /// <param name="Server"></param> public ShareCollection(string server) { _server = server; EnumerateShares(_server, this); } #endregion #region Add protected void Add(Share share) { InnerList.Add(share); } protected void Add(string netName, string path, ShareType shareType, string remark) { InnerList.Add(new Share(_server, netName, path, shareType, remark)); } #endregion #region Properties /// <summary> /// Returns the name of the server this collection represents /// </summary> public string Server { get { return _server; } } /// <summary> /// Returns the <see cref="Share"/> at the specified index. /// </summary> public Share this[int index] { get { return (Share)InnerList[index]; } } /// <summary> /// Returns the <see cref="Share"/> which matches a given local path /// </summary> /// <param name="path">The path to match</param> public Share this[string path] { get { if (null == path || 0 == path.Length) return null; path = Path.GetFullPath(path); if (!IsValidFilePath(path)) return null; Share match = null; for(int i=0; i<InnerList.Count; i++) { Share s = (Share)InnerList[i]; if (s.IsFileSystem && s.MatchesPath(path)) { //Store first match if (null == match) match = s; // If this has a longer path, // and this is a disk share or match is a special share, // then this is a better match else if (match.Path.Length < s.Path.Length) { if (ShareType.Disk == s.ShareType || ShareType.Disk != match.ShareType) match = s; } } } return match; } } #endregion #region Implementation of ICollection /// <summary> /// Copy this collection to an array /// </summary> /// <param name="array"></param> /// <param name="index"></param> public void CopyTo(Share[] array, int index) { InnerList.CopyTo(array, index); } #endregion } #endregion }
//! \file ArcEncrypted.cs //! \date Thu Jan 14 03:27:52 2016 //! \brief Encrypted AZ system resource archives. // // Copyright (C) 2016 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using GameRes.Compression; using GameRes.Utility; using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.IO; using System.Linq; namespace GameRes.Formats.AZSys { [Serializable] public class EncryptionScheme { public readonly uint IndexKey; public readonly uint? ContentKey; public static readonly uint[] DefaultSeed = { 0x2F4D7DFE, 0x47345292, 0x1BA5FE82, 0x7BC04525 }; public EncryptionScheme (uint ikey, uint ckey) { IndexKey = ikey; ContentKey = ckey; } public EncryptionScheme (uint[] iseed) { IndexKey = GenerateKey (iseed); ContentKey = null; } public EncryptionScheme (uint[] iseed, byte[] cseed) { IndexKey = GenerateKey (iseed); ContentKey = GenerateContentKey (cseed); } public static uint GenerateKey (uint[] seed) { if (null == seed) throw new ArgumentNullException ("seed"); if (seed.Length < 4) throw new ArgumentException(); byte[] seed_bytes = new byte[0x10]; Buffer.BlockCopy (seed, 0, seed_bytes, 0, 0x10); uint key = Crc32.UpdateCrc (~seed[0], seed_bytes, 0, seed_bytes.Length) ^ Crc32.UpdateCrc (~(seed[1] & 0xFFFF), seed_bytes, 0, seed_bytes.Length) ^ Crc32.UpdateCrc (~(seed[1] >> 16), seed_bytes, 0, seed_bytes.Length) ^ Crc32.UpdateCrc (~seed[2], seed_bytes, 0, seed_bytes.Length) ^ Crc32.UpdateCrc (~seed[3], seed_bytes, 0, seed_bytes.Length); return seed[0] ^ ~key; } public static uint GenerateContentKey (byte[] env_bytes) { if (null == env_bytes) throw new ArgumentNullException ("env_bytes"); if (env_bytes.Length < 0x10) throw new ArgumentException(); uint crc = Crc32.Compute (env_bytes, 0, 0x10); var sfmt = new FastMersenneTwister (crc); var seed = new uint[4]; seed[0] = sfmt.GetRand32(); seed[1] = sfmt.GetRand32() & 0xFFFF; seed[1] |= sfmt.GetRand32() << 16; seed[2] = sfmt.GetRand32(); seed[3] = sfmt.GetRand32(); return GenerateKey (seed); } } [Serializable] public class AzScheme : ResourceScheme { public Dictionary<string, EncryptionScheme> KnownSchemes; } internal class AzArchive : ArcFile { public readonly uint SysenvKey; public readonly uint RegularKey; public AzArchive (ArcView arc, ArchiveFormat impl, ICollection<Entry> dir, uint syskey, uint regkey) : base (arc, impl, dir) { SysenvKey = syskey; RegularKey = regkey; } } [Export(typeof(ArchiveFormat))] public class ArcEncryptedOpener : ArchiveFormat { public override string Tag { get { return "ARC/AZ/encrypted"; } } public override string Description { get { return "AZ system encrypted resource archive"; } } public override uint Signature { get { return 0; } } public override bool IsHierarchic { get { return false; } } public override bool CanCreate { get { return false; } } public static Dictionary<string, EncryptionScheme> KnownSchemes = new Dictionary<string, EncryptionScheme> { { "Default", new EncryptionScheme (EncryptionScheme.DefaultSeed) }, }; public override ResourceScheme Scheme { get { return new AzScheme { KnownSchemes = KnownSchemes }; } set { KnownSchemes = ((AzScheme)value).KnownSchemes; } } public ArcEncryptedOpener () { Extensions = new string[] { "arc" }; Signatures = new uint[] { 0x53EA06EB, 0x74F98F2F }; } EncryptionScheme CurrentScheme; public override ArcFile TryOpen (ArcView file) { byte[] header_encrypted = file.View.ReadBytes (0, 0x30); if (header_encrypted.Length < 0x30) return null; byte[] header = new byte[header_encrypted.Length]; if (CurrentScheme != null) { try { Buffer.BlockCopy (header_encrypted, 0, header, 0, header.Length); Decrypt (header, 0, CurrentScheme.IndexKey); if (Binary.AsciiEqual (header, 0, "ARC\0")) { var arc = ReadIndex (file, header, CurrentScheme); if (null != arc) return arc; } } catch { /* ignore parse errors */ } } foreach (var scheme in KnownSchemes.Values) { Buffer.BlockCopy (header_encrypted, 0, header, 0, header.Length); Decrypt (header, 0, scheme.IndexKey); if (Binary.AsciiEqual (header, 0, "ARC\0")) { var arc = ReadIndex (file, header, scheme); if (null != arc) CurrentScheme = new EncryptionScheme (arc.SysenvKey, arc.RegularKey); return arc; } } return null; } public override Stream OpenEntry (ArcFile arc, Entry entry) { var azarc = arc as AzArchive; if (null == azarc) return base.OpenEntry (arc, entry); var data = arc.File.View.ReadBytes (entry.Offset, entry.Size); if (entry.Name.Equals ("sysenv.tbl", StringComparison.InvariantCultureIgnoreCase)) { Decrypt (data, entry.Offset, azarc.SysenvKey); return UnpackData (data); } Decrypt (data, entry.Offset, azarc.RegularKey); if (data.Length > 0x14 && Binary.AsciiEqual (data, 0, "ASB\0")) { return OpenAsb (data); } return new MemoryStream (data); } Stream OpenAsb (byte[] data) { int packed_size = LittleEndian.ToInt32 (data, 4); if (packed_size <= 4 || packed_size > data.Length-0x10) return new MemoryStream (data); uint unpacked_size = LittleEndian.ToUInt32 (data, 8); uint key = unpacked_size ^ 0x9E370001; unsafe { fixed (byte* raw = &data[0x10]) { uint* data32 = (uint*)raw; for (int i = packed_size/4; i > 0; --i) *data32++ -= key; } } var asb = UnpackData (data, 0x10); var header = new byte[0x10]; Buffer.BlockCopy (data, 0, header, 0, 0x10); return new PrefixStream (header, asb); } byte[] ReadSysenvSeed (ArcView file, Entry entry, uint key) { var data = file.View.ReadBytes (entry.Offset, entry.Size); if (data.Length <= 4) throw new InvalidFormatException ("Invalid sysenv.tbl size"); Decrypt (data, entry.Offset, key); uint adler32 = LittleEndian.ToUInt32 (data, 0); if (adler32 != Adler32.Compute (data, 4, data.Length-4)) throw new InvalidEncryptionScheme(); using (var input = new MemoryStream (data, 4, data.Length-4)) using (var sysenv_stream = new ZLibStream (input, CompressionMode.Decompress)) { var seed = new byte[0x10]; if (0x10 != sysenv_stream.Read (seed, 0, 0x10)) throw new InvalidFormatException ("Invalid sysenv.tbl size"); return seed; } } Stream UnpackData (byte[] data, int index = 0) { int length = data.Length - index; if (length <= 4) return new MemoryStream (data, index, length); uint adler32 = LittleEndian.ToUInt32 (data, index); if (adler32 != Adler32.Compute (data, index+4, length-4)) return new MemoryStream (data, index, length); var input = new MemoryStream (data, index+4, length-4); return new ZLibStream (input, CompressionMode.Decompress); } AzArchive ReadIndex (ArcView file, byte[] header, EncryptionScheme scheme) { int ext_count = LittleEndian.ToInt32 (header, 4); int count = LittleEndian.ToInt32 (header, 8); uint index_length = LittleEndian.ToUInt32 (header, 12); if (ext_count < 1 || ext_count > 8 || !IsSaneCount (count) || index_length >= file.MaxOffset) return null; var packed_index = file.View.ReadBytes (header.Length, index_length); if (packed_index.Length != index_length) return null; Decrypt (packed_index, header.Length, scheme.IndexKey); uint checksum = LittleEndian.ToUInt32 (packed_index, 0); if (checksum != Adler32.Compute (packed_index, 4, packed_index.Length-4)) { if (checksum != Crc32.Compute (packed_index, 4, packed_index.Length-4)) throw new InvalidFormatException ("Index checksum mismatch"); } uint base_offset = (uint)header.Length + index_length; using (var input = new MemoryStream (packed_index, 4, packed_index.Length-4)) using (var zstream = new ZLibStream (input, CompressionMode.Decompress)) using (var index = new BinaryReader (zstream)) { var dir = new List<Entry> (count); var name_buffer = new byte[0x20]; for (int i = 0; i < count; ++i) { uint offset = index.ReadUInt32(); uint size = index.ReadUInt32(); uint crc = index.ReadUInt32(); index.ReadInt32(); if (name_buffer.Length != index.Read (name_buffer, 0, name_buffer.Length)) return null; var name = Binary.GetCString (name_buffer, 0, 0x20); if (0 == name.Length) return null; var entry = FormatCatalog.Instance.Create<Entry> (name); entry.Offset = base_offset + offset; entry.Size = size; if (!entry.CheckPlacement (file.MaxOffset)) return null; dir.Add (entry); } uint content_key = GetContentKey (file, dir, scheme); return new AzArchive (file, this, dir, scheme.IndexKey, content_key); } } static void Decrypt (byte[] data, long offset, uint key) { ulong hash = key * 0x9E370001ul; if (0 != (offset & 0x3F)) { hash = Binary.RotL (hash, (int)offset); } for (uint i = 0; i < data.Length; ++i) { data[i] ^= (byte)hash; hash = Binary.RotL (hash, 1); } } uint GetContentKey (ArcView file, List<Entry> dir, EncryptionScheme scheme) { if (null != scheme.ContentKey) return scheme.ContentKey.Value; if ("system.arc".Equals (Path.GetFileName (file.Name), StringComparison.InvariantCultureIgnoreCase)) { var sysenv = dir.FirstOrDefault (e => e.Name.Equals ("sysenv.tbl", StringComparison.InvariantCultureIgnoreCase)); if (null != sysenv) { var seed = ReadSysenvSeed (file, sysenv, scheme.IndexKey); return EncryptionScheme.GenerateContentKey (seed); } } else { var system_arc = VFS.CombinePath (Path.GetDirectoryName (file.Name), "system.arc"); using (var arc = VFS.OpenView (system_arc)) { var header = arc.View.ReadBytes (0, 0x30); Decrypt (header, 0, scheme.IndexKey); using (var arc_file = ReadIndex (arc, header, scheme)) { var sysenv = arc_file.Dir.FirstOrDefault (e => e.Name.Equals ("sysenv.tbl", StringComparison.InvariantCultureIgnoreCase)); if (null != sysenv) { var seed = ReadSysenvSeed (arc, sysenv, scheme.IndexKey); return EncryptionScheme.GenerateContentKey (seed); } } } } return scheme.IndexKey; } } }
// 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 gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using proto = Google.Protobuf; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Dialogflow.V2.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedDocumentsClientTest { [xunit::FactAttribute] public void GetDocumentRequestObject() { moq::Mock<Documents.DocumentsClient> mockGrpcClient = new moq::Mock<Documents.DocumentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDocumentRequest request = new GetDocumentRequest { DocumentName = DocumentName.FromProjectKnowledgeBaseDocument("[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]"), }; Document expectedResponse = new Document { DocumentName = DocumentName.FromProjectKnowledgeBaseDocument("[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]"), DisplayName = "display_name137f65c2", MimeType = "mime_type606a0ffc", KnowledgeTypes = { Document.Types.KnowledgeType.Unspecified, }, ContentUri = "content_uriaf560198", Metadata = { { "key8a0b6e3c", "value60c16320" }, }, RawContent = proto::ByteString.CopyFromUtf8("raw_content4f67d498"), EnableAutoReload = true, LatestReloadStatus = new Document.Types.ReloadStatus(), }; mockGrpcClient.Setup(x => x.GetDocument(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DocumentsClient client = new DocumentsClientImpl(mockGrpcClient.Object, null); Document response = client.GetDocument(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetDocumentRequestObjectAsync() { moq::Mock<Documents.DocumentsClient> mockGrpcClient = new moq::Mock<Documents.DocumentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDocumentRequest request = new GetDocumentRequest { DocumentName = DocumentName.FromProjectKnowledgeBaseDocument("[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]"), }; Document expectedResponse = new Document { DocumentName = DocumentName.FromProjectKnowledgeBaseDocument("[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]"), DisplayName = "display_name137f65c2", MimeType = "mime_type606a0ffc", KnowledgeTypes = { Document.Types.KnowledgeType.Unspecified, }, ContentUri = "content_uriaf560198", Metadata = { { "key8a0b6e3c", "value60c16320" }, }, RawContent = proto::ByteString.CopyFromUtf8("raw_content4f67d498"), EnableAutoReload = true, LatestReloadStatus = new Document.Types.ReloadStatus(), }; mockGrpcClient.Setup(x => x.GetDocumentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Document>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DocumentsClient client = new DocumentsClientImpl(mockGrpcClient.Object, null); Document responseCallSettings = await client.GetDocumentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Document responseCancellationToken = await client.GetDocumentAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetDocument() { moq::Mock<Documents.DocumentsClient> mockGrpcClient = new moq::Mock<Documents.DocumentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDocumentRequest request = new GetDocumentRequest { DocumentName = DocumentName.FromProjectKnowledgeBaseDocument("[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]"), }; Document expectedResponse = new Document { DocumentName = DocumentName.FromProjectKnowledgeBaseDocument("[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]"), DisplayName = "display_name137f65c2", MimeType = "mime_type606a0ffc", KnowledgeTypes = { Document.Types.KnowledgeType.Unspecified, }, ContentUri = "content_uriaf560198", Metadata = { { "key8a0b6e3c", "value60c16320" }, }, RawContent = proto::ByteString.CopyFromUtf8("raw_content4f67d498"), EnableAutoReload = true, LatestReloadStatus = new Document.Types.ReloadStatus(), }; mockGrpcClient.Setup(x => x.GetDocument(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DocumentsClient client = new DocumentsClientImpl(mockGrpcClient.Object, null); Document response = client.GetDocument(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetDocumentAsync() { moq::Mock<Documents.DocumentsClient> mockGrpcClient = new moq::Mock<Documents.DocumentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDocumentRequest request = new GetDocumentRequest { DocumentName = DocumentName.FromProjectKnowledgeBaseDocument("[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]"), }; Document expectedResponse = new Document { DocumentName = DocumentName.FromProjectKnowledgeBaseDocument("[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]"), DisplayName = "display_name137f65c2", MimeType = "mime_type606a0ffc", KnowledgeTypes = { Document.Types.KnowledgeType.Unspecified, }, ContentUri = "content_uriaf560198", Metadata = { { "key8a0b6e3c", "value60c16320" }, }, RawContent = proto::ByteString.CopyFromUtf8("raw_content4f67d498"), EnableAutoReload = true, LatestReloadStatus = new Document.Types.ReloadStatus(), }; mockGrpcClient.Setup(x => x.GetDocumentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Document>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DocumentsClient client = new DocumentsClientImpl(mockGrpcClient.Object, null); Document responseCallSettings = await client.GetDocumentAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Document responseCancellationToken = await client.GetDocumentAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetDocumentResourceNames() { moq::Mock<Documents.DocumentsClient> mockGrpcClient = new moq::Mock<Documents.DocumentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDocumentRequest request = new GetDocumentRequest { DocumentName = DocumentName.FromProjectKnowledgeBaseDocument("[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]"), }; Document expectedResponse = new Document { DocumentName = DocumentName.FromProjectKnowledgeBaseDocument("[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]"), DisplayName = "display_name137f65c2", MimeType = "mime_type606a0ffc", KnowledgeTypes = { Document.Types.KnowledgeType.Unspecified, }, ContentUri = "content_uriaf560198", Metadata = { { "key8a0b6e3c", "value60c16320" }, }, RawContent = proto::ByteString.CopyFromUtf8("raw_content4f67d498"), EnableAutoReload = true, LatestReloadStatus = new Document.Types.ReloadStatus(), }; mockGrpcClient.Setup(x => x.GetDocument(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); DocumentsClient client = new DocumentsClientImpl(mockGrpcClient.Object, null); Document response = client.GetDocument(request.DocumentName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetDocumentResourceNamesAsync() { moq::Mock<Documents.DocumentsClient> mockGrpcClient = new moq::Mock<Documents.DocumentsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetDocumentRequest request = new GetDocumentRequest { DocumentName = DocumentName.FromProjectKnowledgeBaseDocument("[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]"), }; Document expectedResponse = new Document { DocumentName = DocumentName.FromProjectKnowledgeBaseDocument("[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]"), DisplayName = "display_name137f65c2", MimeType = "mime_type606a0ffc", KnowledgeTypes = { Document.Types.KnowledgeType.Unspecified, }, ContentUri = "content_uriaf560198", Metadata = { { "key8a0b6e3c", "value60c16320" }, }, RawContent = proto::ByteString.CopyFromUtf8("raw_content4f67d498"), EnableAutoReload = true, LatestReloadStatus = new Document.Types.ReloadStatus(), }; mockGrpcClient.Setup(x => x.GetDocumentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Document>(stt::Task.FromResult(expectedResponse), null, null, null, null)); DocumentsClient client = new DocumentsClientImpl(mockGrpcClient.Object, null); Document responseCallSettings = await client.GetDocumentAsync(request.DocumentName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Document responseCancellationToken = await client.GetDocumentAsync(request.DocumentName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; namespace ClosedXML.Excel { internal class XLRow : XLRangeBase, IXLRow { #region Private fields private Boolean _collapsed; private Double _height; private Boolean _isHidden; private Int32 _outlineLevel; #endregion Private fields #region Constructor public XLRow(Int32 row, XLRowParameters xlRowParameters) : base(new XLRangeAddress(new XLAddress(xlRowParameters.Worksheet, row, 1, false, false), new XLAddress(xlRowParameters.Worksheet, row, XLHelper.MaxColumnNumber, false, false))) { SetRowNumber(row); IsReference = xlRowParameters.IsReference; if (IsReference) SubscribeToShiftedRows((range, rowShifted) => this.WorksheetRangeShiftedRows(range, rowShifted)); else { SetStyle(xlRowParameters.DefaultStyleId); _height = xlRowParameters.Worksheet.RowHeight; } } public XLRow(XLRow row) : base(new XLRangeAddress(new XLAddress(row.Worksheet, row.RowNumber(), 1, false, false), new XLAddress(row.Worksheet, row.RowNumber(), XLHelper.MaxColumnNumber, false, false))) { _height = row._height; IsReference = row.IsReference; if (IsReference) SubscribeToShiftedRows((range, rowShifted) => this.WorksheetRangeShiftedRows(range, rowShifted)); _collapsed = row._collapsed; _isHidden = row._isHidden; _outlineLevel = row._outlineLevel; HeightChanged = row.HeightChanged; SetStyle(row.GetStyleId()); } #endregion Constructor public Boolean IsReference { get; private set; } public override IEnumerable<IXLStyle> Styles { get { UpdatingStyle = true; yield return Style; int row = RowNumber(); foreach (XLCell cell in Worksheet.Internals.CellsCollection.GetCellsInRow(row)) yield return cell.Style; UpdatingStyle = false; } } public override Boolean UpdatingStyle { get; set; } public override IXLStyle InnerStyle { get { return IsReference ? Worksheet.Internals.RowsCollection[RowNumber()].InnerStyle : GetStyle(); } set { if (IsReference) Worksheet.Internals.RowsCollection[RowNumber()].InnerStyle = value; else SetStyle(value); } } public Boolean Collapsed { get { return IsReference ? Worksheet.Internals.RowsCollection[RowNumber()].Collapsed : _collapsed; } set { if (IsReference) Worksheet.Internals.RowsCollection[RowNumber()].Collapsed = value; else _collapsed = value; } } #region IXLRow Members private Boolean _loading; public Boolean Loading { get { return IsReference ? Worksheet.Internals.RowsCollection[RowNumber()].Loading : _loading; } set { if (IsReference) Worksheet.Internals.RowsCollection[RowNumber()].Loading = value; else _loading = value; } } public Boolean HeightChanged { get; private set; } public Double Height { get { return IsReference ? Worksheet.Internals.RowsCollection[RowNumber()].Height : _height; } set { if (!Loading) HeightChanged = true; if (IsReference) Worksheet.Internals.RowsCollection[RowNumber()].Height = value; else _height = value; } } public void ClearHeight() { Height = Worksheet.RowHeight; HeightChanged = false; } public void Delete() { int rowNumber = RowNumber(); using (var asRange = AsRange()) asRange.Delete(XLShiftDeletedCells.ShiftCellsUp); Worksheet.Internals.RowsCollection.Remove(rowNumber); var rowsToMove = new List<Int32>(); rowsToMove.AddRange(Worksheet.Internals.RowsCollection.Where(c => c.Key > rowNumber).Select(c => c.Key)); foreach (int row in rowsToMove.OrderBy(r => r)) { Worksheet.Internals.RowsCollection.Add(row - 1, Worksheet.Internals.RowsCollection[row]); Worksheet.Internals.RowsCollection.Remove(row); } } public new IXLRows InsertRowsBelow(Int32 numberOfRows) { int rowNum = RowNumber(); Worksheet.Internals.RowsCollection.ShiftRowsDown(rowNum + 1, numberOfRows); using (var row = Worksheet.Row(rowNum)) { using (var asRange = row.AsRange()) { asRange.InsertRowsBelowVoid(true, numberOfRows); } } var newRows = Worksheet.Rows(rowNum + 1, rowNum + numberOfRows); CopyRows(newRows); return newRows; } private void CopyRows(IXLRows newRows) { foreach (var newRow in newRows) { var internalRow = Worksheet.Internals.RowsCollection[newRow.RowNumber()]; internalRow._height = Height; internalRow.SetStyle(Style); internalRow._collapsed = Collapsed; internalRow._isHidden = IsHidden; internalRow._outlineLevel = OutlineLevel; } } public new IXLRows InsertRowsAbove(Int32 numberOfRows) { int rowNum = RowNumber(); if (rowNum > 1) { using (var row = Worksheet.Row(rowNum - 1)) { return row.InsertRowsBelow(numberOfRows); } } Worksheet.Internals.RowsCollection.ShiftRowsDown(rowNum, numberOfRows); using (var row = Worksheet.Row(rowNum)) { using (var asRange = row.AsRange()) { asRange.InsertRowsAboveVoid(true, numberOfRows); } } return Worksheet.Rows(rowNum, rowNum + numberOfRows - 1); } public new IXLRow Clear(XLClearOptions clearOptions = XLClearOptions.ContentsAndFormats) { base.Clear(clearOptions); return this; } public IXLCell Cell(Int32 columnNumber) { return Cell(1, columnNumber); } public new IXLCell Cell(String columnLetter) { return Cell(1, columnLetter); } public new IXLCells Cells() { return Cells(true, true); } public new IXLCells Cells(Boolean usedCellsOnly) { if (usedCellsOnly) return Cells(true, true); else return Cells(FirstCellUsed().Address.ColumnNumber, LastCellUsed().Address.ColumnNumber); } public new IXLCells Cells(String cellsInRow) { var retVal = new XLCells(false, false); var rangePairs = cellsInRow.Split(','); foreach (string pair in rangePairs) retVal.Add(Range(pair.Trim()).RangeAddress); return retVal; } public IXLCells Cells(Int32 firstColumn, Int32 lastColumn) { return Cells(firstColumn + ":" + lastColumn); } public IXLCells Cells(String firstColumn, String lastColumn) { return Cells(XLHelper.GetColumnNumberFromLetter(firstColumn) + ":" + XLHelper.GetColumnNumberFromLetter(lastColumn)); } public IXLRow AdjustToContents(Int32 startColumn) { return AdjustToContents(startColumn, XLHelper.MaxColumnNumber); } public IXLRow AdjustToContents(Int32 startColumn, Int32 endColumn) { return AdjustToContents(startColumn, endColumn, 0, Double.MaxValue); } public IXLRow AdjustToContents(Double minHeight, Double maxHeight) { return AdjustToContents(1, XLHelper.MaxColumnNumber, minHeight, maxHeight); } public IXLRow AdjustToContents(Int32 startColumn, Double minHeight, Double maxHeight) { return AdjustToContents(startColumn, XLHelper.MaxColumnNumber, minHeight, maxHeight); } public IXLRow AdjustToContents(Int32 startColumn, Int32 endColumn, Double minHeight, Double maxHeight) { var fontCache = new Dictionary<IXLFontBase, Font>(); Double rowMaxHeight = minHeight; foreach (XLCell c in from XLCell c in Row(startColumn, endColumn).CellsUsed() where !c.IsMerged() select c) { Double thisHeight; Int32 textRotation = c.Style.Alignment.TextRotation; if (c.HasRichText || textRotation != 0 || c.InnerText.Contains(Environment.NewLine)) { var kpList = new List<KeyValuePair<IXLFontBase, string>>(); if (c.HasRichText) { foreach (IXLRichString rt in c.RichText) { String formattedString = rt.Text; var arr = formattedString.Split(new[] { Environment.NewLine }, StringSplitOptions.None); Int32 arrCount = arr.Count(); for (Int32 i = 0; i < arrCount; i++) { String s = arr[i]; if (i < arrCount - 1) s += Environment.NewLine; kpList.Add(new KeyValuePair<IXLFontBase, String>(rt, s)); } } } else { String formattedString = c.GetFormattedString(); var arr = formattedString.Split(new[] { Environment.NewLine }, StringSplitOptions.None); Int32 arrCount = arr.Count(); for (Int32 i = 0; i < arrCount; i++) { String s = arr[i]; if (i < arrCount - 1) s += Environment.NewLine; kpList.Add(new KeyValuePair<IXLFontBase, String>(c.Style.Font, s)); } } Double maxLongCol = kpList.Max(kp => kp.Value.Length); Double maxHeightCol = kpList.Max(kp => kp.Key.GetHeight(fontCache)); Int32 lineCount = kpList.Count(kp => kp.Value.Contains(Environment.NewLine)) + 1; if (textRotation == 0) thisHeight = maxHeightCol * lineCount; else { if (textRotation == 255) thisHeight = maxLongCol * maxHeightCol; else { Double rotation; if (textRotation == 90 || textRotation == 180 || textRotation == 255) rotation = 90; else rotation = textRotation % 90; thisHeight = (rotation / 90.0) * maxHeightCol * maxLongCol * 0.5; } } } else thisHeight = c.Style.Font.GetHeight(fontCache); if (thisHeight >= maxHeight) { rowMaxHeight = maxHeight; break; } if (thisHeight > rowMaxHeight) rowMaxHeight = thisHeight; } if (rowMaxHeight <= 0) rowMaxHeight = Worksheet.RowHeight; Height = rowMaxHeight; foreach (IDisposable font in fontCache.Values) { font.Dispose(); } return this; } public IXLRow Hide() { IsHidden = true; return this; } public IXLRow Unhide() { IsHidden = false; return this; } public Boolean IsHidden { get { return IsReference ? Worksheet.Internals.RowsCollection[RowNumber()].IsHidden : _isHidden; } set { if (IsReference) Worksheet.Internals.RowsCollection[RowNumber()].IsHidden = value; else _isHidden = value; } } public override IXLStyle Style { get { return IsReference ? Worksheet.Internals.RowsCollection[RowNumber()].Style : GetStyle(); } set { if (IsReference) Worksheet.Internals.RowsCollection[RowNumber()].Style = value; else { SetStyle(value); Int32 minColumn = 1; Int32 maxColumn = 0; int row = RowNumber(); if (Worksheet.Internals.CellsCollection.RowsUsed.ContainsKey(row)) { minColumn = Worksheet.Internals.CellsCollection.MinColumnInRow(row); maxColumn = Worksheet.Internals.CellsCollection.MaxColumnInRow(row); } if (Worksheet.Internals.ColumnsCollection.Count > 0) { Int32 minInCollection = Worksheet.Internals.ColumnsCollection.Keys.Min(); Int32 maxInCollection = Worksheet.Internals.ColumnsCollection.Keys.Max(); if (minInCollection < minColumn) minColumn = minInCollection; if (maxInCollection > maxColumn) maxColumn = maxInCollection; } if (minColumn > 0 && maxColumn > 0) { for (Int32 co = minColumn; co <= maxColumn; co++) Worksheet.Cell(row, co).Style = value; } } } } public Int32 OutlineLevel { get { return IsReference ? Worksheet.Internals.RowsCollection[RowNumber()].OutlineLevel : _outlineLevel; } set { if (value < 0 || value > 8) throw new ArgumentOutOfRangeException("value", "Outline level must be between 0 and 8."); if (IsReference) Worksheet.Internals.RowsCollection[RowNumber()].OutlineLevel = value; else { Worksheet.IncrementColumnOutline(value); Worksheet.DecrementColumnOutline(_outlineLevel); _outlineLevel = value; } } } public IXLRow Group() { return Group(false); } public IXLRow Group(Int32 outlineLevel) { return Group(outlineLevel, false); } public IXLRow Ungroup() { return Ungroup(false); } public IXLRow Group(Boolean collapse) { if (OutlineLevel < 8) OutlineLevel += 1; Collapsed = collapse; return this; } public IXLRow Group(Int32 outlineLevel, Boolean collapse) { OutlineLevel = outlineLevel; Collapsed = collapse; return this; } public IXLRow Ungroup(Boolean ungroupFromAll) { if (ungroupFromAll) OutlineLevel = 0; else { if (OutlineLevel > 0) OutlineLevel -= 1; } return this; } public IXLRow Collapse() { Collapsed = true; return Hide(); } public IXLRow Expand() { Collapsed = false; return Unhide(); } public Int32 CellCount() { return RangeAddress.LastAddress.ColumnNumber - RangeAddress.FirstAddress.ColumnNumber + 1; } public new IXLRow Sort() { return SortLeftToRight(); } public new IXLRow SortLeftToRight(XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false, Boolean ignoreBlanks = true) { base.SortLeftToRight(sortOrder, matchCase, ignoreBlanks); return this; } IXLRangeRow IXLRow.CopyTo(IXLCell target) { using (var asRange = AsRange()) using (var copy = asRange.CopyTo(target)) return copy.Row(1); } IXLRangeRow IXLRow.CopyTo(IXLRangeBase target) { using (var asRange = AsRange()) using (var copy = asRange.CopyTo(target)) return copy.Row(1); } public IXLRow CopyTo(IXLRow row) { row.Clear(); var newRow = (XLRow)row; newRow._height = _height; newRow.Style = GetStyle(); using (var asRange = AsRange()) asRange.CopyTo(row).Dispose(); return newRow; } public IXLRangeRow Row(Int32 start, Int32 end) { return Range(1, start, 1, end).Row(1); } public IXLRangeRow Row(IXLCell start, IXLCell end) { return Row(start.Address.ColumnNumber, end.Address.ColumnNumber); } public IXLRangeRows Rows(String rows) { var retVal = new XLRangeRows(); var rowPairs = rows.Split(','); foreach (string pair in rowPairs) using (var asRange = AsRange()) asRange.Rows(pair.Trim()).ForEach(retVal.Add); return retVal; } public IXLRow AddHorizontalPageBreak() { Worksheet.PageSetup.AddHorizontalPageBreak(RowNumber()); return this; } public IXLRow SetDataType(XLCellValues dataType) { DataType = dataType; return this; } public IXLRangeRow RowUsed(Boolean includeFormats = false) { return Row(FirstCellUsed(includeFormats), LastCellUsed(includeFormats)); } #endregion IXLRow Members public override XLRange AsRange() { return Range(1, 1, 1, XLHelper.MaxColumnNumber); } private void WorksheetRangeShiftedRows(XLRange range, int rowsShifted) { if (range.RangeAddress.FirstAddress.RowNumber <= RowNumber()) SetRowNumber(RowNumber() + rowsShifted); } private void SetRowNumber(Int32 row) { if (row <= 0) RangeAddress.IsInvalid = false; else { RangeAddress.FirstAddress = new XLAddress(Worksheet, row, 1, RangeAddress.FirstAddress.FixedRow, RangeAddress.FirstAddress.FixedColumn); RangeAddress.LastAddress = new XLAddress(Worksheet, row, XLHelper.MaxColumnNumber, RangeAddress.LastAddress.FixedRow, RangeAddress.LastAddress.FixedColumn); } } public override XLRange Range(String rangeAddressStr) { String rangeAddressToUse; if (rangeAddressStr.Contains(':') || rangeAddressStr.Contains('-')) { if (rangeAddressStr.Contains('-')) rangeAddressStr = rangeAddressStr.Replace('-', ':'); var arrRange = rangeAddressStr.Split(':'); string firstPart = arrRange[0]; string secondPart = arrRange[1]; rangeAddressToUse = FixRowAddress(firstPart) + ":" + FixRowAddress(secondPart); } else rangeAddressToUse = FixRowAddress(rangeAddressStr); var rangeAddress = new XLRangeAddress(Worksheet, rangeAddressToUse); return Range(rangeAddress); } public IXLRow AdjustToContents() { return AdjustToContents(1); } internal void SetStyleNoColumns(IXLStyle value) { if (IsReference) Worksheet.Internals.RowsCollection[RowNumber()].SetStyleNoColumns(value); else { SetStyle(value); int row = RowNumber(); foreach (XLCell c in Worksheet.Internals.CellsCollection.GetCellsInRow(row)) c.Style = value; } } private XLRow RowShift(Int32 rowsToShift) { return Worksheet.Row(RowNumber() + rowsToShift); } #region XLRow Above IXLRow IXLRow.RowAbove() { return RowAbove(); } IXLRow IXLRow.RowAbove(Int32 step) { return RowAbove(step); } public XLRow RowAbove() { return RowAbove(1); } public XLRow RowAbove(Int32 step) { return RowShift(step * -1); } #endregion XLRow Above #region XLRow Below IXLRow IXLRow.RowBelow() { return RowBelow(); } IXLRow IXLRow.RowBelow(Int32 step) { return RowBelow(step); } public XLRow RowBelow() { return RowBelow(1); } public XLRow RowBelow(Int32 step) { return RowShift(step); } #endregion XLRow Below public override Boolean IsEmpty() { return IsEmpty(false); } public override Boolean IsEmpty(Boolean includeFormats) { if (includeFormats && !Style.Equals(Worksheet.Style)) return false; return base.IsEmpty(includeFormats); } public override Boolean IsEntireRow() { return true; } public override Boolean IsEntireColumn() { return false; } } }
// Copyright (c) 2015 Alachisoft // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections; using Alachisoft.NCache.Runtime.Events; using Microsoft.Win32; using System.Reflection; using System.Text; using System.Runtime.InteropServices; using Alachisoft.NCache.Caching; using Alachisoft.NCache.Caching.AutoExpiration; using Alachisoft.NCache.Caching.EvictionPolicies; using Alachisoft.NCache.Serialization.Formatters; using Alachisoft.NCache.Management; using Alachisoft.NCache.Web.Net; using Alachisoft.NCache.Runtime.Exceptions; using Alachisoft.NCache.Runtime.Serialization; using Alachisoft.NCache.Web.RemoteClient.Config; using Alachisoft.NCache.Runtime; using Alachisoft.NCache.Web.Caching.APILogging; using Alachisoft.NCache.Web.Statistics; using Alachisoft.NCache.Common; using Alachisoft.NCache.Common.Stats; using Alachisoft.NCache.Serialization; using Alachisoft.NCache.IO; using Alachisoft.NCache.Util; using Alachisoft.NCache.Common.DataStructures; using Alachisoft.NCache.Common.Enum; using Alachisoft.NCache.Common.Util; using System.Collections.Generic; using Common = Alachisoft.NCache.Common; /// <summary> /// The <see cref="Alachisoft.NCache.Web.Caching"/> namespace provides classes for caching frequently used data /// in a cluster This includes the <see cref="Cache"/> class, a dictionary that allows you to store /// arbitrary data objects, such as hash tables and data sets. It also provides expiration functionality /// for those objects, and methods that allow you to add and removed the objects. /// </summary> namespace Alachisoft.NCache.Web.Caching { //Wraps Cache class instance //This class is used to log any public api of Cache called by the user. //Note that internal/private methods does not need to be logged. Implementation of internal/private methods if any will just call same function on Cache instance. class WrapperCache : Cache { private Cache _webCache = null; private APILogger _apiLogger; private DebugAPIConfiguraions _debugConfigurations; public WrapperCache(Cache cache) { _webCache = cache; try { _debugConfigurations = new DebugAPIConfiguraions(); _apiLogger = new APILogger(cache.CacheId, _debugConfigurations); } catch (Exception) { } } internal override string SerializationContext { get { return _webCache.SerializationContext; } set { _webCache.SerializationContext = value; } } internal override Cache.CacheAsyncEventsListener AsyncListener { get { return _webCache.AsyncListener; } } internal override Cache.CacheEventsListener EventListener { get { return _webCache.EventListener; } } internal override Common.ResourcePool CallbackIDsMap { get { return _webCache.CallbackIDsMap; } } internal override Common.ResourcePool CallbacksMap { get { return _webCache.CallbacksMap; } } internal override string CacheId { get { return _webCache.CacheId; } } internal override CacheImplBase CacheImpl { get { return _webCache.CacheImpl; } set { _webCache.CacheImpl = value; } } internal override void AddRef() { _webCache.AddRef(); } internal override EventManager EventManager { get { return _webCache.EventManager; } } public override void Dispose() { string exceptionMessage = null; try { _webCache.Dispose(); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(); logItem.Signature = "Dispose()"; logItem.ExceptionMessage = exceptionMessage; _apiLogger.Log(logItem); } _apiLogger.Dispose(); } catch (Exception) { } } } public override bool ExceptionsEnabled { get { return _webCache.ExceptionsEnabled; } set { _webCache.ExceptionsEnabled = value; } } public override long Count { get { return _webCache.Count; } } public override void Clear() { string exceptionMessage = null; try { _webCache.Clear(); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(); logItem.Signature = "Clear()"; logItem.ExceptionMessage = exceptionMessage; _apiLogger.Log(logItem); ; } } catch (Exception) { } } } public override bool Contains(string key) { bool result; string exceptionMessage = null; try { result = _webCache.Contains(key); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(); logItem.Signature = "Contains(string key)"; logItem.Key = key; logItem.ExceptionMessage = exceptionMessage; _apiLogger.Log(logItem); ; } } catch (Exception) { } } return result; } public override void Add(string key, object value) { string exceptionMessage = null; try { _webCache.Add(key, value); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(key, exceptionMessage); logItem.Signature = "Add(string key, object value)"; logItem.RuntimeAPILogItem = (RuntimeAPILogItem)_webCache.APILogHashTable[System.Threading.Thread.CurrentThread.ManagedThreadId]; _apiLogger.Log(logItem); } } catch (Exception) { } _webCache.APILogHashTable.Remove(System.Threading.Thread.CurrentThread.ManagedThreadId); } } public override bool SetAttributes(string key, Runtime.Caching.CacheItemAttributes attributes) { return _webCache.SetAttributes(key, attributes); } public override void Add(string key, object value, DateTime absoluteExpiration, TimeSpan slidingExpiration, Runtime.CacheItemPriority priority) { string exceptionMessage = null; try { _webCache.Add(key, value, absoluteExpiration, slidingExpiration, priority); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(key, exceptionMessage); logItem.Signature = "Add(string key, object value, DateTime absoluteExpiration, TimeSpan slidingExpiration, Runtime.CacheItemPriority priority)"; logItem.AbsolueExpiration = absoluteExpiration; logItem.SlidingExpiration = slidingExpiration; logItem.Priority = priority; logItem.RuntimeAPILogItem = (RuntimeAPILogItem)_webCache.APILogHashTable[System.Threading.Thread.CurrentThread.ManagedThreadId]; _apiLogger.Log(logItem); } } catch (Exception) { } _webCache.APILogHashTable.Remove(System.Threading.Thread.CurrentThread.ManagedThreadId); } } public override void Add(string key, CacheItem item) { string exceptionMessage = null; try { _webCache.Add(key, item); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(key, item, exceptionMessage); logItem.Signature = "Add(string key, CacheItem item)"; logItem.RuntimeAPILogItem = (RuntimeAPILogItem)_webCache.APILogHashTable[System.Threading.Thread.CurrentThread.ManagedThreadId]; _apiLogger.Log(logItem); } } catch (Exception) { } _webCache.APILogHashTable.Remove(System.Threading.Thread.CurrentThread.ManagedThreadId); } } public override IDictionary AddBulk(string[] keys, CacheItem[] items) { IDictionary iDict = null; string exceptionMessage = null; try { iDict = _webCache.AddBulk(keys, items); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(); logItem.Signature = "AddBulk(string[] keys, CacheItem[] items)"; logItem.NoOfKeys = keys.Length; logItem.ExceptionMessage = exceptionMessage; logItem.RuntimeAPILogItem = (RuntimeAPILogItem)_webCache.APILogHashTable[System.Threading.Thread.CurrentThread.ManagedThreadId]; _apiLogger.Log(logItem); } } catch (Exception) { } _webCache.APILogHashTable.Remove(System.Threading.Thread.CurrentThread.ManagedThreadId); } return iDict; } internal override void MakeTargetCacheActivePassive(bool makeActive) { _webCache.MakeTargetCacheActivePassive(makeActive); } /// <summary> /// Retrieves the specified item from the Cache object. /// </summary> /// <param name="key">The identifier for the cache item to retrieve.</param> /// <returns>The retrieved cache item, or a null reference (Nothing /// in Visual Basic) if the key is not found.</returns> /// <exception cref="ArgumentNullException"><paramref name="key"/> contains a null reference (Nothing in Visual Basic).</exception> /// <exception cref="ArgumentException"><paramref name="key"/> is not serializable.</exception> /// <remarks> /// <para><b>Note:</b> If exceptions are enabled through the <see cref="ExceptionsEnabled"/> /// setting, this property throws exception incase of failure.</para> /// </remarks> /// <example>The following example demonstrates how to retrieve the value cached for an ASP.NET text /// box server control. /// <code> /// Cache cache = NCache.InitializeCache("myCache"); /// cache.Get("MyTextBox.Value"); /// /// </code> /// </example> public override object Get(string key) { object obj = null; try { obj = _webCache.Get(key); } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(); logItem.Signature = "Get(string key)"; logItem.Key = key; logItem.RuntimeAPILogItem = (RuntimeAPILogItem)_webCache.APILogHashTable[System.Threading.Thread.CurrentThread.ManagedThreadId]; _apiLogger.Log(logItem); } } catch (Exception) { } _webCache.APILogHashTable.Remove(System.Threading.Thread.CurrentThread.ManagedThreadId); } return obj; } public override object Get(string key, TimeSpan lockTimeout, ref LockHandle lockHandle, bool acquireLock) { Object obj = null; try { obj = _webCache.Get(key, lockTimeout, ref lockHandle, acquireLock); } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(); logItem.Signature = "Get(string key, TimeSpan lockTimeout, ref LockHandle lockHandle, bool acquireLock)"; logItem.Key = key; logItem.LockTimeout = lockTimeout; logItem.AcquireLock = acquireLock; logItem.RuntimeAPILogItem = (RuntimeAPILogItem)_webCache.APILogHashTable[System.Threading.Thread.CurrentThread.ManagedThreadId]; _apiLogger.Log(logItem); } } catch (Exception) { } _webCache.APILogHashTable.Remove(System.Threading.Thread.CurrentThread.ManagedThreadId); } return obj; } public override IDictionary GetBulk(string[] keys) { System.Collections.IDictionary iDict = null; string exceptionMessage = null; try { iDict = _webCache.GetBulk(keys); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(); logItem.Signature = "GetBulk(string[] keys)"; logItem.ExceptionMessage = exceptionMessage; logItem.RuntimeAPILogItem = (RuntimeAPILogItem)_webCache.APILogHashTable[System.Threading.Thread.CurrentThread.ManagedThreadId]; _apiLogger.Log(logItem); } } catch (Exception) { } _webCache.APILogHashTable.Remove(System.Threading.Thread.CurrentThread.ManagedThreadId); } return iDict; } public override CacheItem GetCacheItem(string key) { CacheItem cItem = null; string exceptionMessage = null; try { cItem = _webCache.GetCacheItem(key); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(key, exceptionMessage); logItem.Signature = "GetCacheItem(string key)"; logItem.RuntimeAPILogItem = (RuntimeAPILogItem)_webCache.APILogHashTable[System.Threading.Thread.CurrentThread.ManagedThreadId]; _apiLogger.Log(logItem); } } catch (Exception) { } _webCache.APILogHashTable.Remove(System.Threading.Thread.CurrentThread.ManagedThreadId); } return cItem; } public override CacheItem GetCacheItem(string key, TimeSpan lockTimeout, ref LockHandle lockHandle, bool acquireLock) { CacheItem cItem = null; string exceptionMessage = null; try { cItem = _webCache.GetCacheItem(key, lockTimeout, ref lockHandle, acquireLock); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(key, exceptionMessage); logItem.Signature = "GetCacheItem(string key, TimeSpan lockTimeout, ref LockHandle lockHandle, bool acquireLock)"; logItem.LockTimeout = lockTimeout; logItem.AcquireLock = acquireLock; logItem.RuntimeAPILogItem = (RuntimeAPILogItem)_webCache.APILogHashTable[System.Threading.Thread.CurrentThread.ManagedThreadId]; _apiLogger.Log(logItem); } } catch (Exception) { } _webCache.APILogHashTable.Remove(System.Threading.Thread.CurrentThread.ManagedThreadId); } return cItem; } internal override CacheItem GetCacheItemInternal(string key, LockAccessType accessType, TimeSpan lockTimeout, ref LockHandle lockHandle) { return _webCache.GetCacheItemInternal(key, accessType, lockTimeout, ref lockHandle); } public override void Insert(string key, object value, DateTime absoluteExpiration, TimeSpan slidingExpiration, Runtime.CacheItemPriority priority) { string exceptionMessage = null; try { _webCache.Insert(key, value, absoluteExpiration, slidingExpiration, priority); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(key, exceptionMessage); logItem.Signature = "GetCacheItem(string key, ref CacheItemVersion version)"; logItem.RuntimeAPILogItem = (RuntimeAPILogItem)_webCache.APILogHashTable[System.Threading.Thread.CurrentThread.ManagedThreadId]; _apiLogger.Log(logItem); } } catch (Exception) { } _webCache.APILogHashTable.Remove(System.Threading.Thread.CurrentThread.ManagedThreadId); } } internal override object GetInternal(string key, LockAccessType accessType, TimeSpan lockTimeout, ref LockHandle lockHandle) { return _webCache.GetInternal(key, accessType, lockTimeout, ref lockHandle); } public override void Insert(string key, object value) { string exceptionMessage = null; try { _webCache.Insert(key, value); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(key, exceptionMessage); logItem.Signature = "Insert(string key, object value)"; logItem.RuntimeAPILogItem = (RuntimeAPILogItem)_webCache.APILogHashTable[System.Threading.Thread.CurrentThread.ManagedThreadId]; _apiLogger.Log(logItem); } } catch (Exception) { } _webCache.APILogHashTable.Remove(System.Threading.Thread.CurrentThread.ManagedThreadId); } } public override void Insert(string key, CacheItem item) { string exceptionMessage = null; try { _webCache.Insert(key, item); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(key, item, exceptionMessage); logItem.Signature = "Insert(string key, CacheItem item)"; logItem.RuntimeAPILogItem = (RuntimeAPILogItem)_webCache.APILogHashTable[System.Threading.Thread.CurrentThread.ManagedThreadId]; _apiLogger.Log(logItem); } } catch (Exception) { } _webCache.APILogHashTable.Remove(System.Threading.Thread.CurrentThread.ManagedThreadId); } } public override void Insert(string key, CacheItem item, LockHandle lockHandle, bool releaseLock) { string exceptionMessage = null; try { _webCache.Insert(key, item, lockHandle, releaseLock); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(key, item, exceptionMessage); logItem.Signature = "Insert(string key, CacheItem item, LockHandle lockHandle, bool releaseLock)"; logItem.RuntimeAPILogItem = (RuntimeAPILogItem)_webCache.APILogHashTable[System.Threading.Thread.CurrentThread.ManagedThreadId]; _apiLogger.Log(logItem); } } catch (Exception) { } _webCache.APILogHashTable.Remove(System.Threading.Thread.CurrentThread.ManagedThreadId); } } public override IDictionary InsertBulk(string[] keys, CacheItem[] items) { System.Collections.IDictionary iDict = null; string exceptionMessage = null; try { iDict = _webCache.InsertBulk(keys, items); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(); logItem.Signature = "InsertBulk(string[] keys, CacheItem[] items)"; logItem.NoOfKeys = keys.Length; logItem.ExceptionMessage = exceptionMessage; logItem.RuntimeAPILogItem = (RuntimeAPILogItem)_webCache.APILogHashTable[System.Threading.Thread.CurrentThread.ManagedThreadId]; _apiLogger.Log(logItem); } } catch (Exception) { } _webCache.APILogHashTable.Remove(System.Threading.Thread.CurrentThread.ManagedThreadId); } return iDict; } public override void Unlock(string key) { string exceptionMessage = null; try { _webCache.Unlock(key); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(key, exceptionMessage); logItem.Signature = "Unlock(string key)"; _apiLogger.Log(logItem); } } catch (Exception) { } } } public override void Unlock(string key, LockHandle lockHandle) { string exceptionMessage = null; try { _webCache.Unlock(key, lockHandle); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(key, exceptionMessage); logItem.Signature = "Unlock(string key, LockHandle lockHandle)"; _apiLogger.Log(logItem); } } catch (Exception) { } } } public override bool Lock(string key, TimeSpan lockTimeout, out LockHandle lockHandle) { bool result; string exceptionMessage = null; try { result = _webCache.Lock(key, lockTimeout, out lockHandle); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(key, exceptionMessage); logItem.Signature = "Lock(string key, TimeSpan lockTimeout, out LockHandle lockHandle)"; logItem.LockTimeout = lockTimeout; _apiLogger.Log(logItem); } } catch (Exception) { } } return result; } internal override bool IsLocked(string key, ref LockHandle lockHandle) { return _webCache.IsLocked(key, ref lockHandle); } public override object Remove(string key) { object obj = null; string exceptionMessage = null; try { obj = _webCache.Remove(key); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(key, exceptionMessage); logItem.Signature = "Remove(string key)"; logItem.RuntimeAPILogItem = (RuntimeAPILogItem)_webCache.APILogHashTable[System.Threading.Thread.CurrentThread.ManagedThreadId]; _apiLogger.Log(logItem); } } catch (Exception) { } } return obj; } public override void Delete(string key) { string exceptionMessage = null; try { _webCache.Delete(key); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(key, exceptionMessage); logItem.Signature = "Delete(string key)"; _apiLogger.Log(logItem); } } catch (Exception) { } } } internal override object Remove(string key, LockHandle lockHandle, LockAccessType accessType) { return _webCache.Remove(key, lockHandle, accessType); } internal override void Delete(string key, LockHandle lockHandle, LockAccessType accessType) { _webCache.Delete(key, lockHandle, accessType); } public override object Remove(string key, LockHandle lockHandle) { object obj = null; string exceptionMessage = null; try { obj = _webCache.Remove(key, lockHandle); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(key, exceptionMessage); logItem.Signature = "Remove(string key, LockHandle lockHandle)"; logItem.RuntimeAPILogItem = (RuntimeAPILogItem)_webCache.APILogHashTable[System.Threading.Thread.CurrentThread.ManagedThreadId]; _apiLogger.Log(logItem); } } catch (Exception) { } _webCache.APILogHashTable.Remove(System.Threading.Thread.CurrentThread.ManagedThreadId); } return obj; } public override void Delete(string key, LockHandle lockHandle) { string exceptionMessage = null; try { _webCache.Delete(key, lockHandle); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(key, exceptionMessage); logItem.Signature = "Delete(string key, LockHandle lockHandle)"; _apiLogger.Log(logItem); } } catch (Exception) { } } } public override IDictionary RemoveBulk(string[] keys) { System.Collections.IDictionary iDict = null; string exceptionMessage = null; try { iDict = _webCache.RemoveBulk(keys); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(); logItem.Signature = "RemoveBulk(string[] keys)"; logItem.NoOfKeys = keys.Length; logItem.ExceptionMessage = exceptionMessage; logItem.RuntimeAPILogItem = (RuntimeAPILogItem)_webCache.APILogHashTable[System.Threading.Thread.CurrentThread.ManagedThreadId]; _apiLogger.Log(logItem); } } catch (Exception) { } _webCache.APILogHashTable.Remove(System.Threading.Thread.CurrentThread.ManagedThreadId); } return iDict; } public override void DeleteBulk(string[] keys) { string exceptionMessage = null; try { _webCache.DeleteBulk(keys); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(); logItem.Signature = "DeleteBulk(string[] keys)"; logItem.NoOfKeys = keys.Length; logItem.ExceptionMessage = exceptionMessage; _apiLogger.Log(logItem); } } catch (Exception) { } } } public override System.Collections.ICollection Search(string query, System.Collections.IDictionary values) { System.Collections.ICollection iCol = null; string exceptionMessage = null; try { iCol = _webCache.Search(query, values); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(); logItem.Signature = "Search(string query, System.Collections.IDictionary values)"; logItem.Query = query; logItem.QueryValues = values; if (iCol != null) logItem.NoOfObjectsReturned = iCol.Count; logItem.ExceptionMessage = exceptionMessage; _apiLogger.Log(logItem); } } catch (Exception) { } } return iCol; } public override System.Collections.IDictionary SearchEntries(string query, System.Collections.IDictionary values) { System.Collections.IDictionary iDict = null; string exceptionMessage = null; try { iDict = _webCache.SearchEntries(query, values); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(); logItem.Signature = "SearchEntries(string query, System.Collections.IDictionary values)"; logItem.Query = query; logItem.QueryValues = values; if (iDict != null) logItem.NoOfObjectsReturned = iDict.Count; logItem.RuntimeAPILogItem = (RuntimeAPILogItem)_webCache.APILogHashTable[System.Threading.Thread.CurrentThread.ManagedThreadId]; logItem.ExceptionMessage = exceptionMessage; _apiLogger.Log(logItem); } } catch (Exception) { } _webCache.APILogHashTable.Remove(System.Threading.Thread.CurrentThread.ManagedThreadId); } return iDict; } public override System.Collections.IEnumerator GetEnumerator() { System.Collections.IEnumerator iEnum = null; string exceptionMessage = null; try { _webCache.GetEnumerator(); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(); logItem.Signature = "GetEnumerator()"; logItem.ExceptionMessage = exceptionMessage; _apiLogger.Log(logItem); } } catch (Exception) { } } return iEnum; } internal override List<Common.DataStructures.EnumerationDataChunk> GetNextChunk(List<Common.DataStructures.EnumerationPointer> pointer) { return _webCache.GetNextChunk(pointer); } internal override void InitializeCompactFramework() { _webCache.InitializeCompactFramework(); } internal override IDictionary AddBulkOperation(string[] keys, CacheItem[] items, ref long[] sizes, bool allowQueryTags) { return _webCache.AddBulkOperation(keys, items, ref sizes, true); } public override bool Equals(object obj) { bool result = false; string exceptionMessage = null; try { result = _webCache.Equals(obj); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(); logItem.Signature = "Equals(object obj)"; logItem.ExceptionMessage = exceptionMessage; _apiLogger.Log(logItem); } } catch (Exception) { } } return result; } public override int GetHashCode() { int result; string exceptionMessage = null; try { result = _webCache.GetHashCode(); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(); logItem.Signature = "GetHashCode()"; logItem.ExceptionMessage = exceptionMessage; _apiLogger.Log(logItem); } } catch (Exception) { } } return result; } internal override IDictionary InsertBulkOperation(string[] keys, CacheItem[] items, ref long[] sizes, bool allowQueryTags) { return _webCache.InsertBulkOperation(keys, items, ref sizes, true); } internal override void InsertOperation(string key, object value, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, LockHandle lockHandle, LockAccessType accessType, CacheDataNotificationCallback cacheItemUdpatedCallback, CacheDataNotificationCallback cacheItemRemovedCallaback, EventDataFilter itemUpdateDataFilter, EventDataFilter itemRemovedDataFilter, ref long size, bool allowQueryTags) { _webCache.InsertOperation(key, value, absoluteExpiration, slidingExpiration, priority, lockHandle, accessType, cacheItemUdpatedCallback, cacheItemRemovedCallaback, itemUpdateDataFilter, itemRemovedDataFilter, ref size, true); } internal override CacheEventDescriptor RegisterCacheNotification(CacheDataNotificationCallback cacheDataNotificationCallback, Runtime.Events.EventType eventType, Runtime.Events.EventDataFilter datafilter) { CacheEventDescriptor result = null; string exceptionMessage = null; try { result = _webCache.RegisterCacheNotification(cacheDataNotificationCallback, eventType, datafilter); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(); logItem.Signature = "RegisterCacheNotification(string key, CacheDataNotificationCallback selectiveCacheDataNotificationCallback, Runtime.Events.EventType eventType, Runtime.Events.EventDataFilter datafilter)"; logItem.ExceptionMessage = exceptionMessage; _apiLogger.Log(logItem); } } catch (Exception) { } } return result; } public override void RegisterCacheNotification(string key, CacheDataNotificationCallback selectiveCacheDataNotificationCallback, Runtime.Events.EventType eventType, Runtime.Events.EventDataFilter datafilter) { string exceptionMessage = null; try { _webCache.RegisterCacheNotification(key, selectiveCacheDataNotificationCallback, eventType, datafilter); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(); logItem.Signature = "RegisterCacheNotification(string key, CacheDataNotificationCallback selectiveCacheDataNotificationCallback, Runtime.Events.EventType eventType, Runtime.Events.EventDataFilter datafilter)"; logItem.ExceptionMessage = exceptionMessage; logItem.Key = key; _apiLogger.Log(logItem); } } catch (Exception) { } } } internal override CacheEventDescriptor RegisterCacheNotificationInternal(string key, CacheDataNotificationCallback callback, Runtime.Events.EventType eventType, Runtime.Events.EventDataFilter datafilter, bool notifyOnItemExpiration) { return _webCache.RegisterCacheNotificationInternal(key, callback, eventType, datafilter, notifyOnItemExpiration); } internal override object SafeDeserialize(object serializedObject, string serializationContext, BitSet flag) { return _webCache.SafeDeserialize(serializedObject, serializationContext, flag); } internal override object SafeSerialize(object serializableObject, string serializationContext, ref BitSet flag, ref long size) { return _webCache.SafeSerialize(serializableObject, serializationContext, ref flag, ref size); } public override string ToString() { return _webCache.ToString(); } public override void UnRegisterCacheNotification(string key, CacheDataNotificationCallback callback, Runtime.Events.EventType eventType) { string exceptionMessage = null; try { _webCache.UnRegisterCacheNotification(key, callback, eventType); } catch (Exception e) { exceptionMessage = e.Message; throw; } finally { try { if (_debugConfigurations.IsInLoggingInterval()) { APILogItem logItem = new APILogItem(); logItem.Signature = "UnRegisterCacheNotification(string key, CacheDataNotificationCallback callback, Runtime.Events.EventType eventType)"; logItem.Key = key; logItem.ExceptionMessage = exceptionMessage; _apiLogger.Log(logItem); } } catch (Exception) { } } } } }
#region Copyright notice and license // Copyright 2015, Google 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: // // * 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 Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Threading; using Grpc.Core.Internal; using Grpc.Core.Utils; namespace Grpc.Core { /// <summary> /// Options for calls made by client. /// </summary> public struct CallOptions { Metadata headers; DateTime? deadline; CancellationToken cancellationToken; WriteOptions writeOptions; ContextPropagationToken propagationToken; CallCredentials credentials; /// <summary> /// Creates a new instance of <c>CallOptions</c> struct. /// </summary> /// <param name="headers">Headers to be sent with the call.</param> /// <param name="deadline">Deadline for the call to finish. null means no deadline.</param> /// <param name="cancellationToken">Can be used to request cancellation of the call.</param> /// <param name="writeOptions">Write options that will be used for this call.</param> /// <param name="propagationToken">Context propagation token obtained from <see cref="ServerCallContext"/>.</param> /// <param name="credentials">Credentials to use for this call.</param> public CallOptions(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken), WriteOptions writeOptions = null, ContextPropagationToken propagationToken = null, CallCredentials credentials = null) { this.headers = headers; this.deadline = deadline; this.cancellationToken = cancellationToken; this.writeOptions = writeOptions; this.propagationToken = propagationToken; this.credentials = credentials; } /// <summary> /// Headers to send at the beginning of the call. /// </summary> public Metadata Headers { get { return headers; } } /// <summary> /// Call deadline. /// </summary> public DateTime? Deadline { get { return deadline; } } /// <summary> /// Token that can be used for cancelling the call on the client side. /// Cancelling the token will request cancellation /// of the remote call. Best effort will be made to deliver the cancellation /// notification to the server and interaction of the call with the server side /// will be terminated. Unless the call finishes before the cancellation could /// happen (there is an inherent race), /// the call will finish with <c>StatusCode.Cancelled</c> status. /// </summary> public CancellationToken CancellationToken { get { return cancellationToken; } } /// <summary> /// Write options that will be used for this call. /// </summary> public WriteOptions WriteOptions { get { return this.writeOptions; } } /// <summary> /// Token for propagating parent call context. /// </summary> public ContextPropagationToken PropagationToken { get { return this.propagationToken; } } /// <summary> /// Credentials to use for this call. /// </summary> public CallCredentials Credentials { get { return this.credentials; } } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>Headers</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="headers">The headers.</param> public CallOptions WithHeaders(Metadata headers) { var newOptions = this; newOptions.headers = headers; return newOptions; } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>Deadline</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="deadline">The deadline.</param> public CallOptions WithDeadline(DateTime deadline) { var newOptions = this; newOptions.deadline = deadline; return newOptions; } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>CancellationToken</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> public CallOptions WithCancellationToken(CancellationToken cancellationToken) { var newOptions = this; newOptions.cancellationToken = cancellationToken; return newOptions; } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>WriteOptions</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="writeOptions">The write options.</param> public CallOptions WithWriteOptions(WriteOptions writeOptions) { var newOptions = this; newOptions.writeOptions = writeOptions; return newOptions; } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>PropagationToken</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="propagationToken">The context propagation token.</param> public CallOptions WithPropagationToken(ContextPropagationToken propagationToken) { var newOptions = this; newOptions.propagationToken = propagationToken; return newOptions; } /// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>Credentials</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="credentials">The call credentials.</param> public CallOptions WithCredentials(CallCredentials credentials) { var newOptions = this; newOptions.credentials = credentials; return newOptions; } /// <summary> /// Returns a new instance of <see cref="CallOptions"/> with /// all previously unset values set to their defaults and deadline and cancellation /// token propagated when appropriate. /// </summary> internal CallOptions Normalize() { var newOptions = this; if (propagationToken != null) { if (propagationToken.Options.IsPropagateDeadline) { GrpcPreconditions.CheckArgument(!newOptions.deadline.HasValue, "Cannot propagate deadline from parent call. The deadline has already been set explicitly."); newOptions.deadline = propagationToken.ParentDeadline; } if (propagationToken.Options.IsPropagateCancellation) { GrpcPreconditions.CheckArgument(!newOptions.cancellationToken.CanBeCanceled, "Cannot propagate cancellation token from parent call. The cancellation token has already been set to a non-default value."); newOptions.cancellationToken = propagationToken.ParentCancellationToken; } } newOptions.headers = newOptions.headers ?? Metadata.Empty; newOptions.deadline = newOptions.deadline ?? DateTime.MaxValue; return newOptions; } } }
namespace java.util { [global::MonoJavaBridge.JavaClass()] public partial class Arrays : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected Arrays(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public static bool equals(java.lang.Object[] arg0, java.lang.Object[] arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m0.native == global::System.IntPtr.Zero) global::java.util.Arrays._m0 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "equals", "([Ljava/lang/Object;[Ljava/lang/Object;)Z"); return @__env.CallStaticBooleanMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m1; public static bool equals(float[] arg0, float[] arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m1.native == global::System.IntPtr.Zero) global::java.util.Arrays._m1 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "equals", "([F[F)Z"); return @__env.CallStaticBooleanMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m2; public static bool equals(double[] arg0, double[] arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m2.native == global::System.IntPtr.Zero) global::java.util.Arrays._m2 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "equals", "([D[D)Z"); return @__env.CallStaticBooleanMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m3; public static bool equals(bool[] arg0, bool[] arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m3.native == global::System.IntPtr.Zero) global::java.util.Arrays._m3 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "equals", "([Z[Z)Z"); return @__env.CallStaticBooleanMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m4; public static bool equals(byte[] arg0, byte[] arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m4.native == global::System.IntPtr.Zero) global::java.util.Arrays._m4 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "equals", "([B[B)Z"); return @__env.CallStaticBooleanMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m5; public static bool equals(char[] arg0, char[] arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m5.native == global::System.IntPtr.Zero) global::java.util.Arrays._m5 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "equals", "([C[C)Z"); return @__env.CallStaticBooleanMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m6; public static bool equals(short[] arg0, short[] arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m6.native == global::System.IntPtr.Zero) global::java.util.Arrays._m6 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "equals", "([S[S)Z"); return @__env.CallStaticBooleanMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m7; public static bool equals(int[] arg0, int[] arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m7.native == global::System.IntPtr.Zero) global::java.util.Arrays._m7 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "equals", "([I[I)Z"); return @__env.CallStaticBooleanMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m8; public static bool equals(long[] arg0, long[] arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m8.native == global::System.IntPtr.Zero) global::java.util.Arrays._m8 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "equals", "([J[J)Z"); return @__env.CallStaticBooleanMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m9; public static global::java.lang.String toString(java.lang.Object[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m9.native == global::System.IntPtr.Zero) global::java.util.Arrays._m9 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "toString", "([Ljava/lang/Object;)Ljava/lang/String;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m10; public static global::java.lang.String toString(int[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m10.native == global::System.IntPtr.Zero) global::java.util.Arrays._m10 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "toString", "([I)Ljava/lang/String;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m11; public static global::java.lang.String toString(short[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m11.native == global::System.IntPtr.Zero) global::java.util.Arrays._m11 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "toString", "([S)Ljava/lang/String;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m12; public static global::java.lang.String toString(char[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m12.native == global::System.IntPtr.Zero) global::java.util.Arrays._m12 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "toString", "([C)Ljava/lang/String;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m13; public static global::java.lang.String toString(byte[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m13.native == global::System.IntPtr.Zero) global::java.util.Arrays._m13 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "toString", "([B)Ljava/lang/String;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m14; public static global::java.lang.String toString(bool[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m14.native == global::System.IntPtr.Zero) global::java.util.Arrays._m14 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "toString", "([Z)Ljava/lang/String;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m15; public static global::java.lang.String toString(float[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m15.native == global::System.IntPtr.Zero) global::java.util.Arrays._m15 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "toString", "([F)Ljava/lang/String;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m16; public static global::java.lang.String toString(double[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m16.native == global::System.IntPtr.Zero) global::java.util.Arrays._m16 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "toString", "([D)Ljava/lang/String;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m17; public static global::java.lang.String toString(long[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m17.native == global::System.IntPtr.Zero) global::java.util.Arrays._m17 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "toString", "([J)Ljava/lang/String;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m18; public static int hashCode(float[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m18.native == global::System.IntPtr.Zero) global::java.util.Arrays._m18 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "hashCode", "([F)I"); return @__env.CallStaticIntMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m19; public static int hashCode(long[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m19.native == global::System.IntPtr.Zero) global::java.util.Arrays._m19 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "hashCode", "([J)I"); return @__env.CallStaticIntMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m20; public static int hashCode(int[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m20.native == global::System.IntPtr.Zero) global::java.util.Arrays._m20 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "hashCode", "([I)I"); return @__env.CallStaticIntMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m21; public static int hashCode(short[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m21.native == global::System.IntPtr.Zero) global::java.util.Arrays._m21 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "hashCode", "([S)I"); return @__env.CallStaticIntMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m22; public static int hashCode(char[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m22.native == global::System.IntPtr.Zero) global::java.util.Arrays._m22 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "hashCode", "([C)I"); return @__env.CallStaticIntMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m23; public static int hashCode(byte[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m23.native == global::System.IntPtr.Zero) global::java.util.Arrays._m23 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "hashCode", "([B)I"); return @__env.CallStaticIntMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m24; public static int hashCode(bool[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m24.native == global::System.IntPtr.Zero) global::java.util.Arrays._m24 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "hashCode", "([Z)I"); return @__env.CallStaticIntMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m24, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m25; public static int hashCode(java.lang.Object[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m25.native == global::System.IntPtr.Zero) global::java.util.Arrays._m25 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "hashCode", "([Ljava/lang/Object;)I"); return @__env.CallStaticIntMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m26; public static int hashCode(double[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m26.native == global::System.IntPtr.Zero) global::java.util.Arrays._m26 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "hashCode", "([D)I"); return @__env.CallStaticIntMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m27; public static int[] copyOf(int[] arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m27.native == global::System.IntPtr.Zero) global::java.util.Arrays._m27 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "copyOf", "([II)[I"); return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<int>(@__env.CallStaticObjectMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m27, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as int[]; } private static global::MonoJavaBridge.MethodId _m28; public static global::java.lang.Object[] copyOf(java.lang.Object[] arg0, int arg1, java.lang.Class arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m28.native == global::System.IntPtr.Zero) global::java.util.Arrays._m28 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "copyOf", "([Ljava/lang/Object;ILjava/lang/Class;)[Ljava/lang/Object;"); return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.Object>(@__env.CallStaticObjectMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m28, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.lang.Object[]; } private static global::MonoJavaBridge.MethodId _m29; public static float[] copyOf(float[] arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m29.native == global::System.IntPtr.Zero) global::java.util.Arrays._m29 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "copyOf", "([FI)[F"); return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<float>(@__env.CallStaticObjectMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as float[]; } private static global::MonoJavaBridge.MethodId _m30; public static double[] copyOf(double[] arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m30.native == global::System.IntPtr.Zero) global::java.util.Arrays._m30 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "copyOf", "([DI)[D"); return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<double>(@__env.CallStaticObjectMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as double[]; } private static global::MonoJavaBridge.MethodId _m31; public static bool[] copyOf(bool[] arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m31.native == global::System.IntPtr.Zero) global::java.util.Arrays._m31 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "copyOf", "([ZI)[Z"); return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<bool>(@__env.CallStaticObjectMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m31, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as bool[]; } private static global::MonoJavaBridge.MethodId _m32; public static char[] copyOf(char[] arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m32.native == global::System.IntPtr.Zero) global::java.util.Arrays._m32 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "copyOf", "([CI)[C"); return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<char>(@__env.CallStaticObjectMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m32, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as char[]; } private static global::MonoJavaBridge.MethodId _m33; public static long[] copyOf(long[] arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m33.native == global::System.IntPtr.Zero) global::java.util.Arrays._m33 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "copyOf", "([JI)[J"); return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<long>(@__env.CallStaticObjectMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m33, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as long[]; } private static global::MonoJavaBridge.MethodId _m34; public static global::java.lang.Object[] copyOf(java.lang.Object[] arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m34.native == global::System.IntPtr.Zero) global::java.util.Arrays._m34 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "copyOf", "([Ljava/lang/Object;I)[Ljava/lang/Object;"); return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.Object>(@__env.CallStaticObjectMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m34, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.Object[]; } private static global::MonoJavaBridge.MethodId _m35; public static byte[] copyOf(byte[] arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m35.native == global::System.IntPtr.Zero) global::java.util.Arrays._m35 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "copyOf", "([BI)[B"); return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallStaticObjectMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m35, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as byte[]; } private static global::MonoJavaBridge.MethodId _m36; public static short[] copyOf(short[] arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m36.native == global::System.IntPtr.Zero) global::java.util.Arrays._m36 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "copyOf", "([SI)[S"); return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<short>(@__env.CallStaticObjectMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m36, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as short[]; } private static global::MonoJavaBridge.MethodId _m37; public static char[] copyOfRange(char[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m37.native == global::System.IntPtr.Zero) global::java.util.Arrays._m37 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "copyOfRange", "([CII)[C"); return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<char>(@__env.CallStaticObjectMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m37, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as char[]; } private static global::MonoJavaBridge.MethodId _m38; public static bool[] copyOfRange(bool[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m38.native == global::System.IntPtr.Zero) global::java.util.Arrays._m38 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "copyOfRange", "([ZII)[Z"); return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<bool>(@__env.CallStaticObjectMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m38, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as bool[]; } private static global::MonoJavaBridge.MethodId _m39; public static double[] copyOfRange(double[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m39.native == global::System.IntPtr.Zero) global::java.util.Arrays._m39 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "copyOfRange", "([DII)[D"); return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<double>(@__env.CallStaticObjectMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m39, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as double[]; } private static global::MonoJavaBridge.MethodId _m40; public static float[] copyOfRange(float[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m40.native == global::System.IntPtr.Zero) global::java.util.Arrays._m40 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "copyOfRange", "([FII)[F"); return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<float>(@__env.CallStaticObjectMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m40, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as float[]; } private static global::MonoJavaBridge.MethodId _m41; public static long[] copyOfRange(long[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m41.native == global::System.IntPtr.Zero) global::java.util.Arrays._m41 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "copyOfRange", "([JII)[J"); return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<long>(@__env.CallStaticObjectMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m41, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as long[]; } private static global::MonoJavaBridge.MethodId _m42; public static int[] copyOfRange(int[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m42.native == global::System.IntPtr.Zero) global::java.util.Arrays._m42 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "copyOfRange", "([III)[I"); return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<int>(@__env.CallStaticObjectMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m42, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as int[]; } private static global::MonoJavaBridge.MethodId _m43; public static short[] copyOfRange(short[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m43.native == global::System.IntPtr.Zero) global::java.util.Arrays._m43 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "copyOfRange", "([SII)[S"); return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<short>(@__env.CallStaticObjectMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m43, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as short[]; } private static global::MonoJavaBridge.MethodId _m44; public static byte[] copyOfRange(byte[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m44.native == global::System.IntPtr.Zero) global::java.util.Arrays._m44 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "copyOfRange", "([BII)[B"); return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallStaticObjectMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m44, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as byte[]; } private static global::MonoJavaBridge.MethodId _m45; public static global::java.lang.Object[] copyOfRange(java.lang.Object[] arg0, int arg1, int arg2, java.lang.Class arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m45.native == global::System.IntPtr.Zero) global::java.util.Arrays._m45 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "copyOfRange", "([Ljava/lang/Object;IILjava/lang/Class;)[Ljava/lang/Object;"); return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.Object>(@__env.CallStaticObjectMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m45, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as java.lang.Object[]; } private static global::MonoJavaBridge.MethodId _m46; public static global::java.lang.Object[] copyOfRange(java.lang.Object[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m46.native == global::System.IntPtr.Zero) global::java.util.Arrays._m46 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "copyOfRange", "([Ljava/lang/Object;II)[Ljava/lang/Object;"); return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.Object>(@__env.CallStaticObjectMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m46, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.lang.Object[]; } private static global::MonoJavaBridge.MethodId _m47; public static void fill(double[] arg0, double arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m47.native == global::System.IntPtr.Zero) global::java.util.Arrays._m47 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "fill", "([DD)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m47, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m48; public static void fill(float[] arg0, float arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m48.native == global::System.IntPtr.Zero) global::java.util.Arrays._m48 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "fill", "([FF)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m48, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m49; public static void fill(float[] arg0, int arg1, int arg2, float arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m49.native == global::System.IntPtr.Zero) global::java.util.Arrays._m49 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "fill", "([FIIF)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m49, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m50; public static void fill(bool[] arg0, int arg1, int arg2, bool arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m50.native == global::System.IntPtr.Zero) global::java.util.Arrays._m50 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "fill", "([ZIIZ)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m50, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m51; public static void fill(byte[] arg0, int arg1, int arg2, byte arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m51.native == global::System.IntPtr.Zero) global::java.util.Arrays._m51 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "fill", "([BIIB)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m51, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m52; public static void fill(byte[] arg0, byte arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m52.native == global::System.IntPtr.Zero) global::java.util.Arrays._m52 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "fill", "([BB)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m52, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m53; public static void fill(char[] arg0, int arg1, int arg2, char arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m53.native == global::System.IntPtr.Zero) global::java.util.Arrays._m53 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "fill", "([CIIC)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m53, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m54; public static void fill(short[] arg0, short arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m54.native == global::System.IntPtr.Zero) global::java.util.Arrays._m54 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "fill", "([SS)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m54, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m55; public static void fill(java.lang.Object[] arg0, int arg1, int arg2, java.lang.Object arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m55.native == global::System.IntPtr.Zero) global::java.util.Arrays._m55 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "fill", "([Ljava/lang/Object;IILjava/lang/Object;)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m55, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m56; public static void fill(java.lang.Object[] arg0, java.lang.Object arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m56.native == global::System.IntPtr.Zero) global::java.util.Arrays._m56 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "fill", "([Ljava/lang/Object;Ljava/lang/Object;)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m56, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m57; public static void fill(char[] arg0, char arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m57.native == global::System.IntPtr.Zero) global::java.util.Arrays._m57 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "fill", "([CC)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m57, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m58; public static void fill(short[] arg0, int arg1, int arg2, short arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m58.native == global::System.IntPtr.Zero) global::java.util.Arrays._m58 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "fill", "([SIIS)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m58, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m59; public static void fill(long[] arg0, long arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m59.native == global::System.IntPtr.Zero) global::java.util.Arrays._m59 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "fill", "([JJ)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m59, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m60; public static void fill(long[] arg0, int arg1, int arg2, long arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m60.native == global::System.IntPtr.Zero) global::java.util.Arrays._m60 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "fill", "([JIIJ)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m60, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m61; public static void fill(int[] arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m61.native == global::System.IntPtr.Zero) global::java.util.Arrays._m61 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "fill", "([II)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m61, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m62; public static void fill(int[] arg0, int arg1, int arg2, int arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m62.native == global::System.IntPtr.Zero) global::java.util.Arrays._m62 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "fill", "([IIII)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m62, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m63; public static void fill(bool[] arg0, bool arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m63.native == global::System.IntPtr.Zero) global::java.util.Arrays._m63 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "fill", "([ZZ)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m63, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m64; public static void fill(double[] arg0, int arg1, int arg2, double arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m64.native == global::System.IntPtr.Zero) global::java.util.Arrays._m64 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "fill", "([DIID)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m64, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m65; public static void sort(int[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m65.native == global::System.IntPtr.Zero) global::java.util.Arrays._m65 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "sort", "([I)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m65, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m66; public static void sort(java.lang.Object[] arg0, java.util.Comparator arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m66.native == global::System.IntPtr.Zero) global::java.util.Arrays._m66 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "sort", "([Ljava/lang/Object;Ljava/util/Comparator;)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m66, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m67; public static void sort(java.lang.Object[] arg0, int arg1, int arg2, java.util.Comparator arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m67.native == global::System.IntPtr.Zero) global::java.util.Arrays._m67 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "sort", "([Ljava/lang/Object;IILjava/util/Comparator;)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m67, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m68; public static void sort(long[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m68.native == global::System.IntPtr.Zero) global::java.util.Arrays._m68 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "sort", "([JII)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m68, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m69; public static void sort(long[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m69.native == global::System.IntPtr.Zero) global::java.util.Arrays._m69 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "sort", "([J)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m69, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m70; public static void sort(float[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m70.native == global::System.IntPtr.Zero) global::java.util.Arrays._m70 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "sort", "([FII)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m70, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m71; public static void sort(float[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m71.native == global::System.IntPtr.Zero) global::java.util.Arrays._m71 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "sort", "([F)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m71, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m72; public static void sort(double[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m72.native == global::System.IntPtr.Zero) global::java.util.Arrays._m72 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "sort", "([DII)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m72, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m73; public static void sort(double[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m73.native == global::System.IntPtr.Zero) global::java.util.Arrays._m73 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "sort", "([D)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m73, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m74; public static void sort(byte[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m74.native == global::System.IntPtr.Zero) global::java.util.Arrays._m74 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "sort", "([BII)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m74, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m75; public static void sort(byte[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m75.native == global::System.IntPtr.Zero) global::java.util.Arrays._m75 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "sort", "([B)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m75, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m76; public static void sort(char[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m76.native == global::System.IntPtr.Zero) global::java.util.Arrays._m76 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "sort", "([CII)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m76, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m77; public static void sort(short[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m77.native == global::System.IntPtr.Zero) global::java.util.Arrays._m77 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "sort", "([S)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m77, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m78; public static void sort(short[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m78.native == global::System.IntPtr.Zero) global::java.util.Arrays._m78 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "sort", "([SII)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m78, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m79; public static void sort(int[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m79.native == global::System.IntPtr.Zero) global::java.util.Arrays._m79 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "sort", "([III)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m79, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m80; public static void sort(java.lang.Object[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m80.native == global::System.IntPtr.Zero) global::java.util.Arrays._m80 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "sort", "([Ljava/lang/Object;)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m80, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m81; public static void sort(java.lang.Object[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m81.native == global::System.IntPtr.Zero) global::java.util.Arrays._m81 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "sort", "([Ljava/lang/Object;II)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m81, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m82; public static void sort(char[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m82.native == global::System.IntPtr.Zero) global::java.util.Arrays._m82 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "sort", "([C)V"); @__env.CallStaticVoidMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m82, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m83; public static int binarySearch(char[] arg0, char arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m83.native == global::System.IntPtr.Zero) global::java.util.Arrays._m83 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "binarySearch", "([CC)I"); return @__env.CallStaticIntMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m83, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m84; public static int binarySearch(java.lang.Object[] arg0, java.lang.Object arg1, java.util.Comparator arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m84.native == global::System.IntPtr.Zero) global::java.util.Arrays._m84 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "binarySearch", "([Ljava/lang/Object;Ljava/lang/Object;Ljava/util/Comparator;)I"); return @__env.CallStaticIntMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m84, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m85; public static int binarySearch(short[] arg0, int arg1, int arg2, short arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m85.native == global::System.IntPtr.Zero) global::java.util.Arrays._m85 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "binarySearch", "([SIIS)I"); return @__env.CallStaticIntMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m85, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m86; public static int binarySearch(short[] arg0, short arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m86.native == global::System.IntPtr.Zero) global::java.util.Arrays._m86 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "binarySearch", "([SS)I"); return @__env.CallStaticIntMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m86, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m87; public static int binarySearch(float[] arg0, int arg1, int arg2, float arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m87.native == global::System.IntPtr.Zero) global::java.util.Arrays._m87 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "binarySearch", "([FIIF)I"); return @__env.CallStaticIntMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m87, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m88; public static int binarySearch(int[] arg0, int arg1, int arg2, int arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m88.native == global::System.IntPtr.Zero) global::java.util.Arrays._m88 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "binarySearch", "([IIII)I"); return @__env.CallStaticIntMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m88, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m89; public static int binarySearch(int[] arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m89.native == global::System.IntPtr.Zero) global::java.util.Arrays._m89 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "binarySearch", "([II)I"); return @__env.CallStaticIntMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m89, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m90; public static int binarySearch(float[] arg0, float arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m90.native == global::System.IntPtr.Zero) global::java.util.Arrays._m90 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "binarySearch", "([FF)I"); return @__env.CallStaticIntMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m90, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m91; public static int binarySearch(long[] arg0, int arg1, int arg2, long arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m91.native == global::System.IntPtr.Zero) global::java.util.Arrays._m91 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "binarySearch", "([JIIJ)I"); return @__env.CallStaticIntMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m91, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m92; public static int binarySearch(double[] arg0, double arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m92.native == global::System.IntPtr.Zero) global::java.util.Arrays._m92 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "binarySearch", "([DD)I"); return @__env.CallStaticIntMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m92, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m93; public static int binarySearch(long[] arg0, long arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m93.native == global::System.IntPtr.Zero) global::java.util.Arrays._m93 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "binarySearch", "([JJ)I"); return @__env.CallStaticIntMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m93, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m94; public static int binarySearch(java.lang.Object[] arg0, int arg1, int arg2, java.lang.Object arg3, java.util.Comparator arg4) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m94.native == global::System.IntPtr.Zero) global::java.util.Arrays._m94 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "binarySearch", "([Ljava/lang/Object;IILjava/lang/Object;Ljava/util/Comparator;)I"); return @__env.CallStaticIntMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m94, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); } private static global::MonoJavaBridge.MethodId _m95; public static int binarySearch(double[] arg0, int arg1, int arg2, double arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m95.native == global::System.IntPtr.Zero) global::java.util.Arrays._m95 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "binarySearch", "([DIID)I"); return @__env.CallStaticIntMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m95, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m96; public static int binarySearch(java.lang.Object[] arg0, int arg1, int arg2, java.lang.Object arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m96.native == global::System.IntPtr.Zero) global::java.util.Arrays._m96 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "binarySearch", "([Ljava/lang/Object;IILjava/lang/Object;)I"); return @__env.CallStaticIntMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m96, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m97; public static int binarySearch(byte[] arg0, byte arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m97.native == global::System.IntPtr.Zero) global::java.util.Arrays._m97 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "binarySearch", "([BB)I"); return @__env.CallStaticIntMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m97, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m98; public static int binarySearch(byte[] arg0, int arg1, int arg2, byte arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m98.native == global::System.IntPtr.Zero) global::java.util.Arrays._m98 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "binarySearch", "([BIIB)I"); return @__env.CallStaticIntMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m98, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m99; public static int binarySearch(java.lang.Object[] arg0, java.lang.Object arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m99.native == global::System.IntPtr.Zero) global::java.util.Arrays._m99 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "binarySearch", "([Ljava/lang/Object;Ljava/lang/Object;)I"); return @__env.CallStaticIntMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m99, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m100; public static int binarySearch(char[] arg0, int arg1, int arg2, char arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m100.native == global::System.IntPtr.Zero) global::java.util.Arrays._m100 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "binarySearch", "([CIIC)I"); return @__env.CallStaticIntMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m100, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m101; public static global::java.util.List asList(java.lang.Object[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m101.native == global::System.IntPtr.Zero) global::java.util.Arrays._m101 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "asList", "([Ljava/lang/Object;)Ljava/util/List;"); return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.List>(@__env.CallStaticObjectMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m101, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.util.List; } private static global::MonoJavaBridge.MethodId _m102; public static int deepHashCode(java.lang.Object[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m102.native == global::System.IntPtr.Zero) global::java.util.Arrays._m102 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "deepHashCode", "([Ljava/lang/Object;)I"); return @__env.CallStaticIntMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m102, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m103; public static bool deepEquals(java.lang.Object[] arg0, java.lang.Object[] arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m103.native == global::System.IntPtr.Zero) global::java.util.Arrays._m103 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "deepEquals", "([Ljava/lang/Object;[Ljava/lang/Object;)Z"); return @__env.CallStaticBooleanMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m103, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m104; public static global::java.lang.String deepToString(java.lang.Object[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.util.Arrays._m104.native == global::System.IntPtr.Zero) global::java.util.Arrays._m104 = @__env.GetStaticMethodIDNoThrow(global::java.util.Arrays.staticClass, "deepToString", "([Ljava/lang/Object;)Ljava/lang/String;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(java.util.Arrays.staticClass, global::java.util.Arrays._m104, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } static Arrays() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.util.Arrays.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/util/Arrays")); } } }
// Copyright (c) 2015-present, Parse, LLC. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory. using Parse.Internal; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using UnityEngine; namespace Parse { partial class PlatformHooks : IPlatformHooks { private static IDictionary<string, object> settings; private static string settingsPath; private IHttpClient httpClient = null; public IHttpClient HttpClient { get { httpClient = httpClient ?? new HttpClient(); return httpClient; } } public string SDKName { get { return "unity"; } } private string appName; public string AppName { get { return appName; } } private string appBuildVersion; public string AppBuildVersion { get { return appBuildVersion; } } private string appDisplayVersion; public string AppDisplayVersion { get { return appDisplayVersion; } } public string AppIdentifier { get { ApplicationIdentity appId = AppDomain.CurrentDomain.ApplicationIdentity; if (appId == null) { return null; } else { return appId.FullName; } } } private string osVersion; public string OSVersion { get { return osVersion; } } public string DeviceType { get { if (PlatformHooks.IsAndroid) { return "android"; } else if (PlatformHooks.IsIOS) { return "ios"; } else if (PlatformHooks.IsWindowsPhone8) { return "winphone"; } else { return "unknown"; } } } public string DeviceTimeZone { get { try { // We need the system string to be in english so we'll have the proper key in our lookup table. // If it's not in english then we will attempt to fallback to the closest Time Zone we can find. TimeZoneInfo tzInfo = TimeZoneInfo.Local; string deviceTimeZone = null; if (ParseInstallation.TimeZoneNameMap.TryGetValue(tzInfo.StandardName, out deviceTimeZone)) { return deviceTimeZone; } TimeSpan utcOffset = tzInfo.BaseUtcOffset; // If we have an offset that is not a round hour, then use our second map to see if we can // convert it or not. if (ParseInstallation.TimeZoneOffsetMap.TryGetValue(utcOffset, out deviceTimeZone)) { return deviceTimeZone; } // NOTE: Etc/GMT{+/-} format is inverted from the UTC offset we use as normal people - // a negative value means ahead of UTC, a positive value means behind UTC. bool negativeOffset = utcOffset.Ticks < 0; return String.Format("Etc/GMT{0}{1}", negativeOffset ? "+" : "-", Math.Abs(utcOffset.Hours)); } catch (TimeZoneNotFoundException) { return null; } } } private static bool isCompiledByIL2CPP = System.AppDomain.CurrentDomain.FriendlyName.Equals("IL2CPP Root Domain"); /// <summary> /// Returns true if current running platform is run from a project generated by IL2CPP compiler. /// </summary> internal static bool IsCompiledByIL2CPP { get { return isCompiledByIL2CPP; } } private static bool isWebPlayer; /// <summary> /// Returns true if current running platform is a web player. /// </summary> internal static bool IsWebPlayer { get { if (settingsPath == null) { throw new InvalidOperationException("Parse must be initialized before making any calls."); } return isWebPlayer; } } /// <summary> /// Returns true if current running platform is Android. /// </summary> internal static bool IsAndroid { get { if (settingsPath == null) { throw new InvalidOperationException("Parse must be initialized before making any calls."); } return Application.platform == RuntimePlatform.Android; } } /// <summary> /// Returns true if current running platform is iPhone or iPad. /// </summary> internal static bool IsIOS { get { if (settingsPath == null) { throw new InvalidOperationException("Parse must be initialized before making any calls."); } return Application.platform == RuntimePlatform.IPhonePlayer; } } /// <summary> /// Returns true if the current platform is tvOS. /// </summary> internal static bool IsTvOS { get { if (settingsPath == null) { throw new InvalidOperationException("Parse must be initialized before making any calls."); } return Application.platform == RuntimePlatform.tvOS; } } /// <summary> /// Returns true if current running platform is Windows Phone 8. /// </summary> internal static bool IsWindowsPhone8 { get { if (settingsPath == null) { throw new InvalidOperationException("Parse must be initialized before making any calls."); } return Application.platform == RuntimePlatform.WP8Player; } } #region Unity Reflection Helpers internal static Type GetTypeFromUnityEngine(string typeName) { return Type.GetType(string.Format("UnityEngine.{0}, UnityEngine", typeName)); } /// <summary> /// Calls a static method under Unity Java plugin with reflection. /// </summary> /// <remarks> /// Warning: Unity Android only. /// /// Basically what we want to do: /// <code> /// AndroidJavaClass javaUnityHelper = new AndroidJavaClass(className); /// javaUnityHelper.CallStatic(methodName, parameters); /// But we can't because <c>AndroidJavaClass</c> is not cross-platform. It won't compile on iOS. /// </code> /// </remarks> /// <param name="className"></param> /// <param name="methodName"></param> /// <param name="parameters"></param> internal static void CallStaticJavaUnityMethod(string className, string methodName, object[] parameters) { Type androidJavaClassType = PlatformHooks.GetTypeFromUnityEngine("AndroidJavaClass"); if (androidJavaClassType != null) { // Yo dawg, I heard you like reflection. So I used reflection to invoke a method via reflection inside Java // which calls another reflection in Java. var javaUnityHelper = Activator.CreateInstance(androidJavaClassType, className); var callStaticMethod = androidJavaClassType.GetMethods() .Where(x => x.Name == "CallStatic") .First(x => !x.ContainsGenericParameters); if (callStaticMethod != null) { callStaticMethod.Invoke(javaUnityHelper, new object[] { methodName, parameters }); } } } #endregion /// <summary> /// Wraps the custom settings object for Parse so that it can be exposed as ApplicationSettings. /// </summary> private class SettingsWrapper : IDictionary<string, object> { private readonly IDictionary<string, object> data; private static SettingsWrapper wrapper; public static SettingsWrapper Wrapper { get { wrapper = wrapper ?? new SettingsWrapper(); return wrapper; } } private SettingsWrapper() { var existingSettings = Load(); if (string.IsNullOrEmpty(existingSettings)) { data = new Dictionary<string, object>(); Save(); } else { data = ParseClient.DeserializeJsonString(existingSettings); } } private string Load() { if (settingsPath == null) { throw new InvalidOperationException("Parse must be initialized before making any calls."); } lock (this) { try { if (IsWebPlayer) { return PlayerPrefs.GetString("Parse.settings", null); } else if (IsTvOS) { Debug.Log("Running on TvOS, prefs cannot be loaded."); return null; } else { using (var fs = new FileStream(settingsPath, FileMode.Open, FileAccess.Read)) { var reader = new StreamReader(fs); return reader.ReadToEnd(); } } } catch (Exception) { return null; } } } private void Save() { if (settingsPath == null) { throw new InvalidOperationException("Parse must be initialized before making any calls."); } lock (this) { if (IsWebPlayer) { PlayerPrefs.SetString("Parse.settings", ParseClient.SerializeJsonString(data)); PlayerPrefs.Save(); } else if (IsTvOS) { Debug.Log("Running on TvOS, prefs cannot be saved."); } else { using (var fs = new FileStream(settingsPath, FileMode.Create, FileAccess.Write)) { using (var writer = new StreamWriter(fs)) { writer.Write(ParseClient.SerializeJsonString(data)); } } } } } public void Add(string key, object value) { data.Add(key, value); Save(); } public bool ContainsKey(string key) { return data.ContainsKey(key); } public ICollection<string> Keys { get { return data.Keys; } } public bool Remove(string key) { if (data.Remove(key)) { Save(); return true; } return false; } public bool TryGetValue(string key, out object value) { return data.TryGetValue(key, out value); } public ICollection<object> Values { get { return data.Values; } } public object this[string key] { get { return data[key]; } set { data[key] = value; Save(); } } public void Add(KeyValuePair<string, object> item) { data.Add(item); Save(); } public void Clear() { data.Clear(); Save(); } public bool Contains(KeyValuePair<string, object> item) { return data.Contains(item); } public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex) { data.CopyTo(array, arrayIndex); } public int Count { get { return data.Count; } } public bool IsReadOnly { get { return data.IsReadOnly; } } public bool Remove(KeyValuePair<string, object> item) { if (data.Remove(item)) { Save(); return true; } return false; } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { return data.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return data.GetEnumerator(); } } /// <summary> /// Provides a dictionary that gets persisted on the filesystem between runs of the app. /// This is analogous to NSUserDefaults in iOS. /// </summary> public IDictionary<string, object> ApplicationSettings { get { if (settings == null) { throw new InvalidOperationException("Parse must be initialized before making any calls."); } return settings; } } /// <summary> /// Exists to ensure that generic types are AOT-compiled for the conversions we support. /// Any new value types that we add support for will need to be registered here. /// The method itself is never called, but by virtue of the Preserve attribute being set /// on the PlatformHooks class, these types will be AOT-compiled. /// </summary> private static List<object> CreateWrapperTypes() { return new List<object> { (Action)(() => ParseCloud.CallFunctionAsync<object>(null, null, CancellationToken.None)), (Action)(() => ParseCloud.CallFunctionAsync<bool>(null, null, CancellationToken.None)), (Action)(() => ParseCloud.CallFunctionAsync<byte>(null, null, CancellationToken.None)), (Action)(() => ParseCloud.CallFunctionAsync<sbyte>(null, null, CancellationToken.None)), (Action)(() => ParseCloud.CallFunctionAsync<short>(null, null, CancellationToken.None)), (Action)(() => ParseCloud.CallFunctionAsync<ushort>(null, null, CancellationToken.None)), (Action)(() => ParseCloud.CallFunctionAsync<int>(null, null, CancellationToken.None)), (Action)(() => ParseCloud.CallFunctionAsync<uint>(null, null, CancellationToken.None)), (Action)(() => ParseCloud.CallFunctionAsync<long>(null, null, CancellationToken.None)), (Action)(() => ParseCloud.CallFunctionAsync<ulong>(null, null, CancellationToken.None)), (Action)(() => ParseCloud.CallFunctionAsync<char>(null, null, CancellationToken.None)), (Action)(() => ParseCloud.CallFunctionAsync<double>(null, null, CancellationToken.None)), (Action)(() => ParseCloud.CallFunctionAsync<float>(null, null, CancellationToken.None)), (Action)(() => ParseCloud.CallFunctionAsync<IDictionary<string, object>>(null, null, CancellationToken.None)), (Action)(() => ParseCloud.CallFunctionAsync<IList<object>>(null, null, CancellationToken.None)), typeof(FlexibleListWrapper<object, object>), typeof(FlexibleListWrapper<object, bool>), typeof(FlexibleListWrapper<object, byte>), typeof(FlexibleListWrapper<object, sbyte>), typeof(FlexibleListWrapper<object, short>), typeof(FlexibleListWrapper<object, ushort>), typeof(FlexibleListWrapper<object, int>), typeof(FlexibleListWrapper<object, uint>), typeof(FlexibleListWrapper<object, long>), typeof(FlexibleListWrapper<object, ulong>), typeof(FlexibleListWrapper<object, char>), typeof(FlexibleListWrapper<object, double>), typeof(FlexibleListWrapper<object, float>), typeof(FlexibleListWrapper<bool, object>), typeof(FlexibleListWrapper<bool, bool>), typeof(FlexibleListWrapper<bool, byte>), typeof(FlexibleListWrapper<bool, sbyte>), typeof(FlexibleListWrapper<bool, short>), typeof(FlexibleListWrapper<bool, ushort>), typeof(FlexibleListWrapper<bool, int>), typeof(FlexibleListWrapper<bool, uint>), typeof(FlexibleListWrapper<bool, long>), typeof(FlexibleListWrapper<bool, ulong>), typeof(FlexibleListWrapper<bool, char>), typeof(FlexibleListWrapper<bool, double>), typeof(FlexibleListWrapper<bool, float>), typeof(FlexibleListWrapper<byte, object>), typeof(FlexibleListWrapper<byte, bool>), typeof(FlexibleListWrapper<byte, byte>), typeof(FlexibleListWrapper<byte, sbyte>), typeof(FlexibleListWrapper<byte, short>), typeof(FlexibleListWrapper<byte, ushort>), typeof(FlexibleListWrapper<byte, int>), typeof(FlexibleListWrapper<byte, uint>), typeof(FlexibleListWrapper<byte, long>), typeof(FlexibleListWrapper<byte, ulong>), typeof(FlexibleListWrapper<byte, char>), typeof(FlexibleListWrapper<byte, double>), typeof(FlexibleListWrapper<byte, float>), typeof(FlexibleListWrapper<sbyte, object>), typeof(FlexibleListWrapper<sbyte, bool>), typeof(FlexibleListWrapper<sbyte, byte>), typeof(FlexibleListWrapper<sbyte, sbyte>), typeof(FlexibleListWrapper<sbyte, short>), typeof(FlexibleListWrapper<sbyte, ushort>), typeof(FlexibleListWrapper<sbyte, int>), typeof(FlexibleListWrapper<sbyte, uint>), typeof(FlexibleListWrapper<sbyte, long>), typeof(FlexibleListWrapper<sbyte, ulong>), typeof(FlexibleListWrapper<sbyte, char>), typeof(FlexibleListWrapper<sbyte, double>), typeof(FlexibleListWrapper<sbyte, float>), typeof(FlexibleListWrapper<short, object>), typeof(FlexibleListWrapper<short, bool>), typeof(FlexibleListWrapper<short, byte>), typeof(FlexibleListWrapper<short, sbyte>), typeof(FlexibleListWrapper<short, short>), typeof(FlexibleListWrapper<short, ushort>), typeof(FlexibleListWrapper<short, int>), typeof(FlexibleListWrapper<short, uint>), typeof(FlexibleListWrapper<short, long>), typeof(FlexibleListWrapper<short, ulong>), typeof(FlexibleListWrapper<short, char>), typeof(FlexibleListWrapper<short, double>), typeof(FlexibleListWrapper<short, float>), typeof(FlexibleListWrapper<ushort, object>), typeof(FlexibleListWrapper<ushort, bool>), typeof(FlexibleListWrapper<ushort, byte>), typeof(FlexibleListWrapper<ushort, sbyte>), typeof(FlexibleListWrapper<ushort, short>), typeof(FlexibleListWrapper<ushort, ushort>), typeof(FlexibleListWrapper<ushort, int>), typeof(FlexibleListWrapper<ushort, uint>), typeof(FlexibleListWrapper<ushort, long>), typeof(FlexibleListWrapper<ushort, ulong>), typeof(FlexibleListWrapper<ushort, char>), typeof(FlexibleListWrapper<ushort, double>), typeof(FlexibleListWrapper<ushort, float>), typeof(FlexibleListWrapper<int, object>), typeof(FlexibleListWrapper<int, bool>), typeof(FlexibleListWrapper<int, byte>), typeof(FlexibleListWrapper<int, sbyte>), typeof(FlexibleListWrapper<int, short>), typeof(FlexibleListWrapper<int, ushort>), typeof(FlexibleListWrapper<int, int>), typeof(FlexibleListWrapper<int, uint>), typeof(FlexibleListWrapper<int, long>), typeof(FlexibleListWrapper<int, ulong>), typeof(FlexibleListWrapper<int, char>), typeof(FlexibleListWrapper<int, double>), typeof(FlexibleListWrapper<int, float>), typeof(FlexibleListWrapper<uint, object>), typeof(FlexibleListWrapper<uint, bool>), typeof(FlexibleListWrapper<uint, byte>), typeof(FlexibleListWrapper<uint, sbyte>), typeof(FlexibleListWrapper<uint, short>), typeof(FlexibleListWrapper<uint, ushort>), typeof(FlexibleListWrapper<uint, int>), typeof(FlexibleListWrapper<uint, uint>), typeof(FlexibleListWrapper<uint, long>), typeof(FlexibleListWrapper<uint, ulong>), typeof(FlexibleListWrapper<uint, char>), typeof(FlexibleListWrapper<uint, double>), typeof(FlexibleListWrapper<uint, float>), typeof(FlexibleListWrapper<long, object>), typeof(FlexibleListWrapper<long, bool>), typeof(FlexibleListWrapper<long, byte>), typeof(FlexibleListWrapper<long, sbyte>), typeof(FlexibleListWrapper<long, short>), typeof(FlexibleListWrapper<long, ushort>), typeof(FlexibleListWrapper<long, int>), typeof(FlexibleListWrapper<long, uint>), typeof(FlexibleListWrapper<long, long>), typeof(FlexibleListWrapper<long, ulong>), typeof(FlexibleListWrapper<long, char>), typeof(FlexibleListWrapper<long, double>), typeof(FlexibleListWrapper<long, float>), typeof(FlexibleListWrapper<ulong, object>), typeof(FlexibleListWrapper<ulong, bool>), typeof(FlexibleListWrapper<ulong, byte>), typeof(FlexibleListWrapper<ulong, sbyte>), typeof(FlexibleListWrapper<ulong, short>), typeof(FlexibleListWrapper<ulong, ushort>), typeof(FlexibleListWrapper<ulong, int>), typeof(FlexibleListWrapper<ulong, uint>), typeof(FlexibleListWrapper<ulong, long>), typeof(FlexibleListWrapper<ulong, ulong>), typeof(FlexibleListWrapper<ulong, char>), typeof(FlexibleListWrapper<ulong, double>), typeof(FlexibleListWrapper<ulong, float>), typeof(FlexibleListWrapper<char, object>), typeof(FlexibleListWrapper<char, bool>), typeof(FlexibleListWrapper<char, byte>), typeof(FlexibleListWrapper<char, sbyte>), typeof(FlexibleListWrapper<char, short>), typeof(FlexibleListWrapper<char, ushort>), typeof(FlexibleListWrapper<char, int>), typeof(FlexibleListWrapper<char, uint>), typeof(FlexibleListWrapper<char, long>), typeof(FlexibleListWrapper<char, ulong>), typeof(FlexibleListWrapper<char, char>), typeof(FlexibleListWrapper<char, double>), typeof(FlexibleListWrapper<char, float>), typeof(FlexibleListWrapper<double, object>), typeof(FlexibleListWrapper<double, bool>), typeof(FlexibleListWrapper<double, byte>), typeof(FlexibleListWrapper<double, sbyte>), typeof(FlexibleListWrapper<double, short>), typeof(FlexibleListWrapper<double, ushort>), typeof(FlexibleListWrapper<double, int>), typeof(FlexibleListWrapper<double, uint>), typeof(FlexibleListWrapper<double, long>), typeof(FlexibleListWrapper<double, ulong>), typeof(FlexibleListWrapper<double, char>), typeof(FlexibleListWrapper<double, double>), typeof(FlexibleListWrapper<double, float>), typeof(FlexibleListWrapper<float, object>), typeof(FlexibleListWrapper<float, bool>), typeof(FlexibleListWrapper<float, byte>), typeof(FlexibleListWrapper<float, sbyte>), typeof(FlexibleListWrapper<float, short>), typeof(FlexibleListWrapper<float, ushort>), typeof(FlexibleListWrapper<float, int>), typeof(FlexibleListWrapper<float, uint>), typeof(FlexibleListWrapper<float, long>), typeof(FlexibleListWrapper<float, ulong>), typeof(FlexibleListWrapper<float, char>), typeof(FlexibleListWrapper<float, double>), typeof(FlexibleListWrapper<float, float>), typeof(FlexibleListWrapper<object, string>), typeof(FlexibleListWrapper<string, object>), typeof(FlexibleListWrapper<object, DateTime>), typeof(FlexibleListWrapper<DateTime, object>), typeof(FlexibleListWrapper<object, ParseObject>), typeof(FlexibleListWrapper<ParseObject, object>), typeof(FlexibleListWrapper<object, ParseGeoPoint>), typeof(FlexibleListWrapper<ParseGeoPoint, object>), typeof(FlexibleListWrapper<object, ParseFile>), typeof(FlexibleListWrapper<ParseFile, object>), typeof(FlexibleListWrapper<object, ParseACL>), typeof(FlexibleListWrapper<ParseACL, object>), typeof(FlexibleListWrapper<object, ParseUser>), typeof(FlexibleListWrapper<ParseUser, object>), typeof(FlexibleListWrapper<object, ParseRole>), typeof(FlexibleListWrapper<ParseRole, object>), typeof(FlexibleListWrapper<object, IList<bool>>), typeof(FlexibleListWrapper<IList<bool>, object>), typeof(FlexibleListWrapper<object, IList<int>>), typeof(FlexibleListWrapper<IList<int>, object>), typeof(FlexibleListWrapper<object, IList<float>>), typeof(FlexibleListWrapper<IList<float>, object>), typeof(FlexibleListWrapper<object, IList<double>>), typeof(FlexibleListWrapper<IList<double>, object>), typeof(FlexibleListWrapper<object, IList<string>>), typeof(FlexibleListWrapper<IList<string>, object>), typeof(FlexibleListWrapper<object, IList<object>>), typeof(FlexibleListWrapper<IList<object>, object>), typeof(FlexibleListWrapper<object, IList<DateTime>>), typeof(FlexibleListWrapper<IList<DateTime>, object>), typeof(FlexibleListWrapper<object, IList<ParseObject>>), typeof(FlexibleListWrapper<IList<ParseObject>, object>), typeof(FlexibleListWrapper<object, IList<ParseGeoPoint>>), typeof(FlexibleListWrapper<IList<ParseGeoPoint>, object>), typeof(FlexibleListWrapper<object, IList<ParseFile>>), typeof(FlexibleListWrapper<IList<ParseFile>, object>), typeof(FlexibleListWrapper<object, IList<ParseACL>>), typeof(FlexibleListWrapper<IList<ParseACL>, object>), typeof(FlexibleListWrapper<object, IList<ParseUser>>), typeof(FlexibleListWrapper<IList<ParseUser>, object>), typeof(FlexibleListWrapper<object, IList<ParseRole>>), typeof(FlexibleListWrapper<IList<ParseRole>, object>), typeof(FlexibleListWrapper<object, List<bool>>), typeof(FlexibleListWrapper<List<bool>, object>), typeof(FlexibleListWrapper<object, List<int>>), typeof(FlexibleListWrapper<List<int>, object>), typeof(FlexibleListWrapper<object, List<float>>), typeof(FlexibleListWrapper<List<float>, object>), typeof(FlexibleListWrapper<object, List<double>>), typeof(FlexibleListWrapper<List<double>, object>), typeof(FlexibleListWrapper<object, List<string>>), typeof(FlexibleListWrapper<List<string>, object>), typeof(FlexibleListWrapper<object, List<object>>), typeof(FlexibleListWrapper<List<object>, object>), typeof(FlexibleListWrapper<object, List<DateTime>>), typeof(FlexibleListWrapper<List<DateTime>, object>), typeof(FlexibleListWrapper<object, List<ParseObject>>), typeof(FlexibleListWrapper<List<ParseObject>, object>), typeof(FlexibleListWrapper<object, List<ParseGeoPoint>>), typeof(FlexibleListWrapper<List<ParseGeoPoint>, object>), typeof(FlexibleListWrapper<object, List<ParseFile>>), typeof(FlexibleListWrapper<List<ParseFile>, object>), typeof(FlexibleListWrapper<object, List<ParseACL>>), typeof(FlexibleListWrapper<List<ParseACL>, object>), typeof(FlexibleListWrapper<object, List<ParseUser>>), typeof(FlexibleListWrapper<List<ParseUser>, object>), typeof(FlexibleListWrapper<object, List<ParseRole>>), typeof(FlexibleListWrapper<List<ParseRole>, object>), typeof(FlexibleListWrapper<object, IDictionary<string, bool>>), typeof(FlexibleListWrapper<IDictionary<string, bool>, object>), typeof(FlexibleListWrapper<object, IDictionary<string, int>>), typeof(FlexibleListWrapper<IDictionary<string, int>, object>), typeof(FlexibleListWrapper<object, IDictionary<string, float>>), typeof(FlexibleListWrapper<IDictionary<string, float>, object>), typeof(FlexibleListWrapper<object, IDictionary<string, double>>), typeof(FlexibleListWrapper<IDictionary<string, double>, object>), typeof(FlexibleListWrapper<object, IDictionary<string, string>>), typeof(FlexibleListWrapper<IDictionary<string, string>, object>), typeof(FlexibleListWrapper<object, IDictionary<string, object>>), typeof(FlexibleListWrapper<IDictionary<string, object>, object>), typeof(FlexibleListWrapper<object, IDictionary<string, DateTime>>), typeof(FlexibleListWrapper<IDictionary<string, DateTime>, object>), typeof(FlexibleListWrapper<object, IDictionary<string, ParseObject>>), typeof(FlexibleListWrapper<IDictionary<string, ParseObject>, object>), typeof(FlexibleListWrapper<object, IDictionary<string, ParseGeoPoint>>), typeof(FlexibleListWrapper<IDictionary<string, ParseGeoPoint>, object>), typeof(FlexibleListWrapper<object, IDictionary<string, ParseFile>>), typeof(FlexibleListWrapper<IDictionary<string, ParseFile>, object>), typeof(FlexibleListWrapper<object, IDictionary<string, ParseACL>>), typeof(FlexibleListWrapper<IDictionary<string, ParseACL>, object>), typeof(FlexibleListWrapper<object, IDictionary<string, ParseUser>>), typeof(FlexibleListWrapper<IDictionary<string, ParseUser>, object>), typeof(FlexibleListWrapper<object, IDictionary<string, ParseRole>>), typeof(FlexibleListWrapper<IDictionary<string, ParseRole>, object>), typeof(FlexibleListWrapper<object, Dictionary<string, bool>>), typeof(FlexibleListWrapper<Dictionary<string, bool>, object>), typeof(FlexibleListWrapper<object, Dictionary<string, int>>), typeof(FlexibleListWrapper<Dictionary<string, int>, object>), typeof(FlexibleListWrapper<object, Dictionary<string, float>>), typeof(FlexibleListWrapper<Dictionary<string, float>, object>), typeof(FlexibleListWrapper<object, Dictionary<string, double>>), typeof(FlexibleListWrapper<Dictionary<string, double>, object>), typeof(FlexibleListWrapper<object, Dictionary<string, string>>), typeof(FlexibleListWrapper<Dictionary<string, string>, object>), typeof(FlexibleListWrapper<object, Dictionary<string, object>>), typeof(FlexibleListWrapper<Dictionary<string, object>, object>), typeof(FlexibleListWrapper<object, Dictionary<string, DateTime>>), typeof(FlexibleListWrapper<Dictionary<string, DateTime>, object>), typeof(FlexibleListWrapper<object, Dictionary<string, ParseObject>>), typeof(FlexibleListWrapper<Dictionary<string, ParseObject>, object>), typeof(FlexibleListWrapper<object, Dictionary<string, ParseGeoPoint>>), typeof(FlexibleListWrapper<Dictionary<string, ParseGeoPoint>, object>), typeof(FlexibleListWrapper<object, Dictionary<string, ParseFile>>), typeof(FlexibleListWrapper<Dictionary<string, ParseFile>, object>), typeof(FlexibleListWrapper<object, Dictionary<string, ParseACL>>), typeof(FlexibleListWrapper<Dictionary<string, ParseACL>, object>), typeof(FlexibleListWrapper<object, Dictionary<string, ParseUser>>), typeof(FlexibleListWrapper<Dictionary<string, ParseUser>, object>), typeof(FlexibleListWrapper<object, Dictionary<string, ParseRole>>), typeof(FlexibleListWrapper<Dictionary<string, ParseRole>, object>), typeof(FlexibleDictionaryWrapper<object, object>), typeof(FlexibleDictionaryWrapper<object, bool>), typeof(FlexibleDictionaryWrapper<object, byte>), typeof(FlexibleDictionaryWrapper<object, sbyte>), typeof(FlexibleDictionaryWrapper<object, short>), typeof(FlexibleDictionaryWrapper<object, ushort>), typeof(FlexibleDictionaryWrapper<object, int>), typeof(FlexibleDictionaryWrapper<object, uint>), typeof(FlexibleDictionaryWrapper<object, long>), typeof(FlexibleDictionaryWrapper<object, ulong>), typeof(FlexibleDictionaryWrapper<object, char>), typeof(FlexibleDictionaryWrapper<object, double>), typeof(FlexibleDictionaryWrapper<object, float>), typeof(FlexibleDictionaryWrapper<bool, object>), typeof(FlexibleDictionaryWrapper<bool, bool>), typeof(FlexibleDictionaryWrapper<bool, byte>), typeof(FlexibleDictionaryWrapper<bool, sbyte>), typeof(FlexibleDictionaryWrapper<bool, short>), typeof(FlexibleDictionaryWrapper<bool, ushort>), typeof(FlexibleDictionaryWrapper<bool, int>), typeof(FlexibleDictionaryWrapper<bool, uint>), typeof(FlexibleDictionaryWrapper<bool, long>), typeof(FlexibleDictionaryWrapper<bool, ulong>), typeof(FlexibleDictionaryWrapper<bool, char>), typeof(FlexibleDictionaryWrapper<bool, double>), typeof(FlexibleDictionaryWrapper<bool, float>), typeof(FlexibleDictionaryWrapper<byte, object>), typeof(FlexibleDictionaryWrapper<byte, bool>), typeof(FlexibleDictionaryWrapper<byte, byte>), typeof(FlexibleDictionaryWrapper<byte, sbyte>), typeof(FlexibleDictionaryWrapper<byte, short>), typeof(FlexibleDictionaryWrapper<byte, ushort>), typeof(FlexibleDictionaryWrapper<byte, int>), typeof(FlexibleDictionaryWrapper<byte, uint>), typeof(FlexibleDictionaryWrapper<byte, long>), typeof(FlexibleDictionaryWrapper<byte, ulong>), typeof(FlexibleDictionaryWrapper<byte, char>), typeof(FlexibleDictionaryWrapper<byte, double>), typeof(FlexibleDictionaryWrapper<byte, float>), typeof(FlexibleDictionaryWrapper<sbyte, object>), typeof(FlexibleDictionaryWrapper<sbyte, bool>), typeof(FlexibleDictionaryWrapper<sbyte, byte>), typeof(FlexibleDictionaryWrapper<sbyte, sbyte>), typeof(FlexibleDictionaryWrapper<sbyte, short>), typeof(FlexibleDictionaryWrapper<sbyte, ushort>), typeof(FlexibleDictionaryWrapper<sbyte, int>), typeof(FlexibleDictionaryWrapper<sbyte, uint>), typeof(FlexibleDictionaryWrapper<sbyte, long>), typeof(FlexibleDictionaryWrapper<sbyte, ulong>), typeof(FlexibleDictionaryWrapper<sbyte, char>), typeof(FlexibleDictionaryWrapper<sbyte, double>), typeof(FlexibleDictionaryWrapper<sbyte, float>), typeof(FlexibleDictionaryWrapper<short, object>), typeof(FlexibleDictionaryWrapper<short, bool>), typeof(FlexibleDictionaryWrapper<short, byte>), typeof(FlexibleDictionaryWrapper<short, sbyte>), typeof(FlexibleDictionaryWrapper<short, short>), typeof(FlexibleDictionaryWrapper<short, ushort>), typeof(FlexibleDictionaryWrapper<short, int>), typeof(FlexibleDictionaryWrapper<short, uint>), typeof(FlexibleDictionaryWrapper<short, long>), typeof(FlexibleDictionaryWrapper<short, ulong>), typeof(FlexibleDictionaryWrapper<short, char>), typeof(FlexibleDictionaryWrapper<short, double>), typeof(FlexibleDictionaryWrapper<short, float>), typeof(FlexibleDictionaryWrapper<ushort, object>), typeof(FlexibleDictionaryWrapper<ushort, bool>), typeof(FlexibleDictionaryWrapper<ushort, byte>), typeof(FlexibleDictionaryWrapper<ushort, sbyte>), typeof(FlexibleDictionaryWrapper<ushort, short>), typeof(FlexibleDictionaryWrapper<ushort, ushort>), typeof(FlexibleDictionaryWrapper<ushort, int>), typeof(FlexibleDictionaryWrapper<ushort, uint>), typeof(FlexibleDictionaryWrapper<ushort, long>), typeof(FlexibleDictionaryWrapper<ushort, ulong>), typeof(FlexibleDictionaryWrapper<ushort, char>), typeof(FlexibleDictionaryWrapper<ushort, double>), typeof(FlexibleDictionaryWrapper<ushort, float>), typeof(FlexibleDictionaryWrapper<int, object>), typeof(FlexibleDictionaryWrapper<int, bool>), typeof(FlexibleDictionaryWrapper<int, byte>), typeof(FlexibleDictionaryWrapper<int, sbyte>), typeof(FlexibleDictionaryWrapper<int, short>), typeof(FlexibleDictionaryWrapper<int, ushort>), typeof(FlexibleDictionaryWrapper<int, int>), typeof(FlexibleDictionaryWrapper<int, uint>), typeof(FlexibleDictionaryWrapper<int, long>), typeof(FlexibleDictionaryWrapper<int, ulong>), typeof(FlexibleDictionaryWrapper<int, char>), typeof(FlexibleDictionaryWrapper<int, double>), typeof(FlexibleDictionaryWrapper<int, float>), typeof(FlexibleDictionaryWrapper<uint, object>), typeof(FlexibleDictionaryWrapper<uint, bool>), typeof(FlexibleDictionaryWrapper<uint, byte>), typeof(FlexibleDictionaryWrapper<uint, sbyte>), typeof(FlexibleDictionaryWrapper<uint, short>), typeof(FlexibleDictionaryWrapper<uint, ushort>), typeof(FlexibleDictionaryWrapper<uint, int>), typeof(FlexibleDictionaryWrapper<uint, uint>), typeof(FlexibleDictionaryWrapper<uint, long>), typeof(FlexibleDictionaryWrapper<uint, ulong>), typeof(FlexibleDictionaryWrapper<uint, char>), typeof(FlexibleDictionaryWrapper<uint, double>), typeof(FlexibleDictionaryWrapper<uint, float>), typeof(FlexibleDictionaryWrapper<long, object>), typeof(FlexibleDictionaryWrapper<long, bool>), typeof(FlexibleDictionaryWrapper<long, byte>), typeof(FlexibleDictionaryWrapper<long, sbyte>), typeof(FlexibleDictionaryWrapper<long, short>), typeof(FlexibleDictionaryWrapper<long, ushort>), typeof(FlexibleDictionaryWrapper<long, int>), typeof(FlexibleDictionaryWrapper<long, uint>), typeof(FlexibleDictionaryWrapper<long, long>), typeof(FlexibleDictionaryWrapper<long, ulong>), typeof(FlexibleDictionaryWrapper<long, char>), typeof(FlexibleDictionaryWrapper<long, double>), typeof(FlexibleDictionaryWrapper<long, float>), typeof(FlexibleDictionaryWrapper<ulong, object>), typeof(FlexibleDictionaryWrapper<ulong, bool>), typeof(FlexibleDictionaryWrapper<ulong, byte>), typeof(FlexibleDictionaryWrapper<ulong, sbyte>), typeof(FlexibleDictionaryWrapper<ulong, short>), typeof(FlexibleDictionaryWrapper<ulong, ushort>), typeof(FlexibleDictionaryWrapper<ulong, int>), typeof(FlexibleDictionaryWrapper<ulong, uint>), typeof(FlexibleDictionaryWrapper<ulong, long>), typeof(FlexibleDictionaryWrapper<ulong, ulong>), typeof(FlexibleDictionaryWrapper<ulong, char>), typeof(FlexibleDictionaryWrapper<ulong, double>), typeof(FlexibleDictionaryWrapper<ulong, float>), typeof(FlexibleDictionaryWrapper<char, object>), typeof(FlexibleDictionaryWrapper<char, bool>), typeof(FlexibleDictionaryWrapper<char, byte>), typeof(FlexibleDictionaryWrapper<char, sbyte>), typeof(FlexibleDictionaryWrapper<char, short>), typeof(FlexibleDictionaryWrapper<char, ushort>), typeof(FlexibleDictionaryWrapper<char, int>), typeof(FlexibleDictionaryWrapper<char, uint>), typeof(FlexibleDictionaryWrapper<char, long>), typeof(FlexibleDictionaryWrapper<char, ulong>), typeof(FlexibleDictionaryWrapper<char, char>), typeof(FlexibleDictionaryWrapper<char, double>), typeof(FlexibleDictionaryWrapper<char, float>), typeof(FlexibleDictionaryWrapper<double, object>), typeof(FlexibleDictionaryWrapper<double, bool>), typeof(FlexibleDictionaryWrapper<double, byte>), typeof(FlexibleDictionaryWrapper<double, sbyte>), typeof(FlexibleDictionaryWrapper<double, short>), typeof(FlexibleDictionaryWrapper<double, ushort>), typeof(FlexibleDictionaryWrapper<double, int>), typeof(FlexibleDictionaryWrapper<double, uint>), typeof(FlexibleDictionaryWrapper<double, long>), typeof(FlexibleDictionaryWrapper<double, ulong>), typeof(FlexibleDictionaryWrapper<double, char>), typeof(FlexibleDictionaryWrapper<double, double>), typeof(FlexibleDictionaryWrapper<double, float>), typeof(FlexibleDictionaryWrapper<float, object>), typeof(FlexibleDictionaryWrapper<float, bool>), typeof(FlexibleDictionaryWrapper<float, byte>), typeof(FlexibleDictionaryWrapper<float, sbyte>), typeof(FlexibleDictionaryWrapper<float, short>), typeof(FlexibleDictionaryWrapper<float, ushort>), typeof(FlexibleDictionaryWrapper<float, int>), typeof(FlexibleDictionaryWrapper<float, uint>), typeof(FlexibleDictionaryWrapper<float, long>), typeof(FlexibleDictionaryWrapper<float, ulong>), typeof(FlexibleDictionaryWrapper<float, char>), typeof(FlexibleDictionaryWrapper<float, double>), typeof(FlexibleDictionaryWrapper<float, float>), typeof(FlexibleDictionaryWrapper<object, string>), typeof(FlexibleDictionaryWrapper<string, object>), typeof(FlexibleDictionaryWrapper<object, DateTime>), typeof(FlexibleDictionaryWrapper<DateTime, object>), typeof(FlexibleDictionaryWrapper<object, ParseObject>), typeof(FlexibleDictionaryWrapper<ParseObject, object>), typeof(FlexibleDictionaryWrapper<object, ParseGeoPoint>), typeof(FlexibleDictionaryWrapper<ParseGeoPoint, object>), typeof(FlexibleDictionaryWrapper<object, ParseFile>), typeof(FlexibleDictionaryWrapper<ParseFile, object>), typeof(FlexibleDictionaryWrapper<object, ParseACL>), typeof(FlexibleDictionaryWrapper<ParseACL, object>), typeof(FlexibleDictionaryWrapper<object, ParseUser>), typeof(FlexibleDictionaryWrapper<ParseUser, object>), typeof(FlexibleDictionaryWrapper<object, ParseRole>), typeof(FlexibleDictionaryWrapper<ParseRole, object>), typeof(FlexibleDictionaryWrapper<object, IList<bool>>), typeof(FlexibleDictionaryWrapper<IList<bool>, object>), typeof(FlexibleDictionaryWrapper<object, IList<int>>), typeof(FlexibleDictionaryWrapper<IList<int>, object>), typeof(FlexibleDictionaryWrapper<object, IList<float>>), typeof(FlexibleDictionaryWrapper<IList<float>, object>), typeof(FlexibleDictionaryWrapper<object, IList<double>>), typeof(FlexibleDictionaryWrapper<IList<double>, object>), typeof(FlexibleDictionaryWrapper<object, IList<string>>), typeof(FlexibleDictionaryWrapper<IList<string>, object>), typeof(FlexibleDictionaryWrapper<object, IList<object>>), typeof(FlexibleDictionaryWrapper<IList<object>, object>), typeof(FlexibleDictionaryWrapper<object, IList<DateTime>>), typeof(FlexibleDictionaryWrapper<IList<DateTime>, object>), typeof(FlexibleDictionaryWrapper<object, IList<ParseObject>>), typeof(FlexibleDictionaryWrapper<IList<ParseObject>, object>), typeof(FlexibleDictionaryWrapper<object, IList<ParseGeoPoint>>), typeof(FlexibleDictionaryWrapper<IList<ParseGeoPoint>, object>), typeof(FlexibleDictionaryWrapper<object, IList<ParseFile>>), typeof(FlexibleDictionaryWrapper<IList<ParseFile>, object>), typeof(FlexibleDictionaryWrapper<object, IList<ParseACL>>), typeof(FlexibleDictionaryWrapper<IList<ParseACL>, object>), typeof(FlexibleDictionaryWrapper<object, IList<ParseUser>>), typeof(FlexibleDictionaryWrapper<IList<ParseUser>, object>), typeof(FlexibleDictionaryWrapper<object, IList<ParseRole>>), typeof(FlexibleDictionaryWrapper<IList<ParseRole>, object>), typeof(FlexibleDictionaryWrapper<object, List<bool>>), typeof(FlexibleDictionaryWrapper<List<bool>, object>), typeof(FlexibleDictionaryWrapper<object, List<int>>), typeof(FlexibleDictionaryWrapper<List<int>, object>), typeof(FlexibleDictionaryWrapper<object, List<float>>), typeof(FlexibleDictionaryWrapper<List<float>, object>), typeof(FlexibleDictionaryWrapper<object, List<double>>), typeof(FlexibleDictionaryWrapper<List<double>, object>), typeof(FlexibleDictionaryWrapper<object, List<string>>), typeof(FlexibleDictionaryWrapper<List<string>, object>), typeof(FlexibleDictionaryWrapper<object, List<string>>), typeof(FlexibleDictionaryWrapper<List<string>, object>), typeof(FlexibleDictionaryWrapper<object, List<object>>), typeof(FlexibleDictionaryWrapper<List<object>, object>), typeof(FlexibleDictionaryWrapper<object, List<DateTime>>), typeof(FlexibleDictionaryWrapper<List<DateTime>, object>), typeof(FlexibleDictionaryWrapper<object, List<ParseObject>>), typeof(FlexibleDictionaryWrapper<List<ParseObject>, object>), typeof(FlexibleDictionaryWrapper<object, List<ParseGeoPoint>>), typeof(FlexibleDictionaryWrapper<List<ParseGeoPoint>, object>), typeof(FlexibleDictionaryWrapper<object, List<ParseFile>>), typeof(FlexibleDictionaryWrapper<List<ParseFile>, object>), typeof(FlexibleDictionaryWrapper<object, List<ParseACL>>), typeof(FlexibleDictionaryWrapper<List<ParseACL>, object>), typeof(FlexibleDictionaryWrapper<object, List<ParseUser>>), typeof(FlexibleDictionaryWrapper<List<ParseUser>, object>), typeof(FlexibleDictionaryWrapper<object, List<ParseRole>>), typeof(FlexibleDictionaryWrapper<List<ParseRole>, object>), typeof(FlexibleDictionaryWrapper<object, IDictionary<string, bool>>), typeof(FlexibleDictionaryWrapper<IDictionary<string, bool>, object>), typeof(FlexibleDictionaryWrapper<object, IDictionary<string, int>>), typeof(FlexibleDictionaryWrapper<IDictionary<string, int>, object>), typeof(FlexibleDictionaryWrapper<object, IDictionary<string, float>>), typeof(FlexibleDictionaryWrapper<IDictionary<string, float>, object>), typeof(FlexibleDictionaryWrapper<object, IDictionary<string, double>>), typeof(FlexibleDictionaryWrapper<IDictionary<string, double>, object>), typeof(FlexibleDictionaryWrapper<object, IDictionary<string, string>>), typeof(FlexibleDictionaryWrapper<IDictionary<string, string>, object>), typeof(FlexibleDictionaryWrapper<object, IDictionary<string, object>>), typeof(FlexibleDictionaryWrapper<IDictionary<string, object>, object>), typeof(FlexibleDictionaryWrapper<object, IDictionary<string, DateTime>>), typeof(FlexibleDictionaryWrapper<IDictionary<string, DateTime>, object>), typeof(FlexibleDictionaryWrapper<object, IDictionary<string, ParseObject>>), typeof(FlexibleDictionaryWrapper<IDictionary<string, ParseObject>, object>), typeof(FlexibleDictionaryWrapper<object, IDictionary<string, ParseGeoPoint>>), typeof(FlexibleDictionaryWrapper<IDictionary<string, ParseGeoPoint>, object>), typeof(FlexibleDictionaryWrapper<object, IDictionary<string, ParseFile>>), typeof(FlexibleDictionaryWrapper<IDictionary<string, ParseFile>, object>), typeof(FlexibleDictionaryWrapper<object, IDictionary<string, ParseACL>>), typeof(FlexibleDictionaryWrapper<IDictionary<string, ParseACL>, object>), typeof(FlexibleDictionaryWrapper<object, IDictionary<string, ParseUser>>), typeof(FlexibleDictionaryWrapper<IDictionary<string, ParseUser>, object>), typeof(FlexibleDictionaryWrapper<object, IDictionary<string, ParseRole>>), typeof(FlexibleDictionaryWrapper<IDictionary<string, ParseRole>, object>), typeof(FlexibleDictionaryWrapper<object, Dictionary<string, bool>>), typeof(FlexibleDictionaryWrapper<Dictionary<string, bool>, object>), typeof(FlexibleDictionaryWrapper<object, Dictionary<string, int>>), typeof(FlexibleDictionaryWrapper<Dictionary<string, int>, object>), typeof(FlexibleDictionaryWrapper<object, Dictionary<string, float>>), typeof(FlexibleDictionaryWrapper<Dictionary<string, float>, object>), typeof(FlexibleDictionaryWrapper<object, Dictionary<string, double>>), typeof(FlexibleDictionaryWrapper<Dictionary<string, double>, object>), typeof(FlexibleDictionaryWrapper<object, Dictionary<string, string>>), typeof(FlexibleDictionaryWrapper<Dictionary<string, string>, object>), typeof(FlexibleDictionaryWrapper<object, Dictionary<string, object>>), typeof(FlexibleDictionaryWrapper<Dictionary<string, object>, object>), typeof(FlexibleDictionaryWrapper<object, Dictionary<string, DateTime>>), typeof(FlexibleDictionaryWrapper<Dictionary<string, DateTime>, object>), typeof(FlexibleDictionaryWrapper<object, Dictionary<string, ParseObject>>), typeof(FlexibleDictionaryWrapper<Dictionary<string, ParseObject>, object>), typeof(FlexibleDictionaryWrapper<object, Dictionary<string, ParseGeoPoint>>), typeof(FlexibleDictionaryWrapper<Dictionary<string, ParseGeoPoint>, object>), typeof(FlexibleDictionaryWrapper<object, Dictionary<string, ParseFile>>), typeof(FlexibleDictionaryWrapper<Dictionary<string, ParseFile>, object>), typeof(FlexibleDictionaryWrapper<object, Dictionary<string, ParseACL>>), typeof(FlexibleDictionaryWrapper<Dictionary<string, ParseACL>, object>), typeof(FlexibleDictionaryWrapper<object, Dictionary<string, ParseUser>>), typeof(FlexibleDictionaryWrapper<Dictionary<string, ParseUser>, object>), typeof(FlexibleDictionaryWrapper<object, Dictionary<string, ParseRole>>), typeof(FlexibleDictionaryWrapper<Dictionary<string, ParseRole>, object>), }; } private static readonly ReaderWriterLockSlim dispatchQueueLock = new ReaderWriterLockSlim(); private static readonly Queue<Action> dispatchQueue = new Queue<Action>(); /// <summary> /// Registers a callback for network requests, running the callback on the main thread until /// the network request is complete. /// </summary> internal static void RegisterNetworkRequest(WWW www, Action<WWW> action) { RunOnMainThread(() => { var isDone = www.isDone; action(www); if (!isDone) { RegisterNetworkRequest(www, action); } }); } #region iOS Callbacks /// <summary> /// Warning: iOS only. Registers a callback for device token request. /// </summary> /// <param name="action">Action to be completed when device token is received.</param> internal static void RegisterDeviceTokenRequest(Action<byte[]> action) { RunOnMainThread(() => { var deviceToken = UnityEngine.iOS.NotificationServices.deviceToken; if (deviceToken != null) { action(deviceToken); RegisteriOSPushNotificationListener((payload) => { ParsePush.parsePushNotificationReceived.Invoke(ParseInstallation.CurrentInstallation, new ParsePushNotificationEventArgs(payload)); }); } else { RegisterDeviceTokenRequest(action); } }); } /// <summary> /// Warning: iOS only. Registers a callback for push notification. /// </summary> /// <param name="action">Action to be completed when push notification is received.</param> internal static void RegisteriOSPushNotificationListener(Action<IDictionary<string, object>> action) { RunOnMainThread(() => { int remoteNotificationCount = UnityEngine.iOS.NotificationServices.remoteNotificationCount; if (remoteNotificationCount > 0) { var remoteNotifications = UnityEngine.iOS.NotificationServices.remoteNotifications; foreach (var val in remoteNotifications) { var userInfo = val.userInfo; var payload = new Dictionary<string, object>(); foreach (var key in userInfo.Keys) { payload[key.ToString()] = userInfo[key]; } // Finally, do the action for each remote notification payload. action(payload); } UnityEngine.iOS.NotificationServices.ClearRemoteNotifications(); } // Check in every frame. RegisteriOSPushNotificationListener(action); }); } #endregion /// <summary> /// Runs things inside of a Unity coroutine (some APIs require that you /// access them from the main thread). /// </summary> internal static void RunOnMainThread(Action action) { if (dispatchQueueLock.IsWriteLockHeld) { dispatchQueue.Enqueue(action); return; } dispatchQueueLock.EnterWriteLock(); try { dispatchQueue.Enqueue(action); } finally { dispatchQueueLock.ExitWriteLock(); } } /// <summary> /// Returns an enumerator (for use in a coroutine) that runs actions that have been dispatched. /// </summary> internal static IEnumerator RunDispatcher() { while (true) { dispatchQueueLock.EnterUpgradeableReadLock(); try { // We'll only empty what's already in the dispatch queue in this iteration (so that a // nested dispatch behaves like nextTick()). int count = dispatchQueue.Count; if (count > 0) { dispatchQueueLock.EnterWriteLock(); try { while (count > 0) { try { dispatchQueue.Dequeue()(); } catch (Exception e) { // If an exception occurs, catch it and log it so that dispatches aren't broken. Debug.LogException(e); } count--; } } finally { dispatchQueueLock.ExitWriteLock(); } } } finally { dispatchQueueLock.ExitUpgradeableReadLock(); } yield return null; } } /// <summary> /// Initialize the app. Called from <see cref="ParseClient.Initialize(string, string)"/>. Guaranteed to be run on main thread. /// </summary> public void Initialize() { if (settingsPath != null) { return; } settingsPath = Path.Combine(Application.persistentDataPath, "Parse.settings"); // We can only set some values here since we can be sure that Initialize is always called // from main thread. isWebPlayer = Application.isWebPlayer; osVersion = SystemInfo.deviceModel; appBuildVersion = Application.version; appDisplayVersion = Application.bundleIdentifier; appName = Application.productName; settings = SettingsWrapper.Wrapper; // TODO (hallucinogen): We might not want to do this automagically... ParseFacebookUtils.Initialize(); if (IsAndroid) { try { CallStaticJavaUnityMethod("com.parse.ParsePushUnityHelper", "registerGcm", null); } catch (Exception e) { // We don't care about the exception. If it reaches this point, it means the Plugin is misconfigured/we don't want to use // PushNotification. Let's just log it to developer. Debug.LogException(e); } } } public Task ExecuteParseInstallationSaveHookAsync(ParseInstallation installation) { return Task.Run(() => { installation.SetIfDifferent("badge", installation.Badge); }); } } }
using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.Threading; namespace MediaServer.Utility { [Serializable] public class QueueDisabledException : Exception { public QueueDisabledException() { } public QueueDisabledException(String msg) : base(msg) { } public QueueDisabledException(string message, Exception inner) : base(message, inner) { } protected QueueDisabledException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public class BlockingQueue<T> { #region Data private readonly int _maxCapacity; private readonly Queue<T> _queue = new Queue<T>(); #endregion #region Constructors public BlockingQueue() : this(int.MaxValue) { } public BlockingQueue(int maxCapacity) { _maxCapacity = maxCapacity; } #endregion #region Properties private bool _enabled = true; public bool Enabled { get { lock (this) { return _enabled; } } set { lock (this) { _enabled = value; if (_enabled == false) { Monitor.PulseAll(this); } } } } public int Length { get { lock (this) { return _queue.Count; } } } public bool IsEmpty { get { lock (this) { return (_queue.Count == 0); } } } public bool IsFull { get { lock (this) { return (_queue.Count >= _maxCapacity); } } } #endregion #region Enqueue public void Enqueue(T item) { Enqueue(item, Timeout.Infinite); } public void Enqueue(T item, int timeoutMilliseconds) { lock (this) { if (!_enabled) throw new QueueDisabledException(); while (_queue.Count >= _maxCapacity) { try { if (!Monitor.Wait(this, timeoutMilliseconds)) { throw new TimeoutException(); } } catch { Monitor.PulseAll(this); throw; } if (!_enabled) throw new QueueDisabledException(); } _queue.Enqueue(item); if (_queue.Count == 1) { Monitor.PulseAll(this); } } } public bool TryEnqueue(T item) { lock (this) { if (!IsFull) { Enqueue(item); return true; } return false; } } #endregion #region Dequeue public T Dequeue() { return Dequeue(Timeout.Infinite); } public T Dequeue(int timeoutMilliseconds) { lock (this) { if (!_enabled) throw new QueueDisabledException(); while (_queue.Count <= 0) { try { if (!Monitor.Wait(this, timeoutMilliseconds)) { throw new TimeoutException(); } } catch { Monitor.PulseAll(this); throw; } if (!_enabled) throw new QueueDisabledException(); } T item = _queue.Dequeue(); if (_queue.Count == (_maxCapacity - 1)) { Monitor.PulseAll(this); } return item; } } public bool TryDequeue(out T item) { lock (this) { if (!IsEmpty) { item = Dequeue(); return true; } item = default(T); return false; } } #endregion } }
// *********************************************************************** // Copyright (c) 2013-2015 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Text; namespace NUnit.Framework.Internal { /// <summary> /// Randomizer returns a set of random values in a repeatable /// way, to allow re-running of tests if necessary. It extends /// the .NET Random class, providing random values for a much /// wider range of types. /// /// The class is used internally by the framework to generate /// test case data and is also exposed for use by users through /// the TestContext.Random property. /// </summary> /// <remarks> /// For consistency with the underlying Random Type, methods /// returning a single value use the prefix "Next..." Those /// without an argument return a non-negative value up to /// the full positive range of the Type. Overloads are provided /// for specifying a maximum or a range. Methods that return /// arrays or strings use the prefix "Get..." to avoid /// confusion with the single-value methods. /// </remarks> public class Randomizer : Random { #region Static Members // Static constructor initializes values static Randomizer() { InitialSeed = new Random().Next(); Randomizers = new Dictionary<MemberInfo, Randomizer>(); } // Static Random instance used exclusively for the generation // of seed values for new Randomizers. private static Random _seedGenerator; /// <summary> /// Initial seed used to create randomizers for this run /// </summary> public static int InitialSeed { get { return _initialSeed; } set { _initialSeed = value; // Setting or resetting the initial seed creates seed generator _seedGenerator = new Random(_initialSeed); } } private static int _initialSeed; // Lookup Dictionary used to find randomizers for each member private static readonly Dictionary<MemberInfo, Randomizer> Randomizers; /// <summary> /// Get a Randomizer for a particular member, returning /// one that has already been created if it exists. /// This ensures that the same values are generated /// each time the tests are reloaded. /// </summary> public static Randomizer GetRandomizer(MemberInfo member) { if (Randomizers.ContainsKey(member)) return Randomizers[member]; else { var r = CreateRandomizer(); Randomizers[member] = r; return r; } } /// <summary> /// Get a randomizer for a particular parameter, returning /// one that has already been created if it exists. /// This ensures that the same values are generated /// each time the tests are reloaded. /// </summary> public static Randomizer GetRandomizer(ParameterInfo parameter) { return GetRandomizer(parameter.Member); } /// <summary> /// Create a new Randomizer using the next seed /// available to ensure that each randomizer gives /// a unique sequence of values. /// </summary> /// <returns></returns> public static Randomizer CreateRandomizer() { return new Randomizer(_seedGenerator.Next()); } #endregion #region Constructors /// <summary> /// Default constructor /// </summary> public Randomizer() { } /// <summary> /// Construct based on seed value /// </summary> /// <param name="seed"></param> public Randomizer(int seed) : base(seed) { } #endregion #region Ints // NOTE: Next(), Next(int max) and Next(int min, int max) are // inherited from Random. #endregion #region Unsigned Ints /// <summary> /// Returns a random unsigned int. /// </summary> [CLSCompliant(false)] public uint NextUInt() { return NextUInt(0u, uint.MaxValue); } /// <summary> /// Returns a random unsigned int less than the specified maximum. /// </summary> [CLSCompliant(false)] public uint NextUInt(uint max) { return NextUInt(0u, max); } /// <summary> /// Returns a random unsigned int within a specified range. /// </summary> [CLSCompliant(false)] public uint NextUInt(uint min, uint max) { Guard.ArgumentInRange(max >= min, "Maximum value must be greater than or equal to minimum.", nameof(max)); if (min == max) return min; uint range = max - min; // Avoid introduction of modulo bias uint limit = uint.MaxValue - uint.MaxValue % range; uint raw; do { raw = RawUInt(); } while (raw > limit); return unchecked(raw % range + min); } #endregion #region Shorts /// <summary> /// Returns a non-negative random short. /// </summary> public short NextShort() { return NextShort(0, short.MaxValue); } /// <summary> /// Returns a non-negative random short less than the specified maximum. /// </summary> public short NextShort(short max) { return NextShort((short)0, max); } /// <summary> /// Returns a non-negative random short within a specified range. /// </summary> public short NextShort(short min, short max) { return (short)Next(min, max); } #endregion #region Unsigned Shorts /// <summary> /// Returns a random unsigned short. /// </summary> [CLSCompliant(false)] public ushort NextUShort() { return NextUShort((ushort)0, ushort.MaxValue); } /// <summary> /// Returns a random unsigned short less than the specified maximum. /// </summary> [CLSCompliant(false)] public ushort NextUShort(ushort max) { return NextUShort((ushort)0, max); } /// <summary> /// Returns a random unsigned short within a specified range. /// </summary> [CLSCompliant(false)] public ushort NextUShort(ushort min, ushort max) { return (ushort)Next(min, max); } #endregion #region Longs /// <summary> /// Returns a random long. /// </summary> public long NextLong() { return NextLong(0L, long.MaxValue); } /// <summary> /// Returns a random long less than the specified maximum. /// </summary> public long NextLong(long max) { return NextLong(0L, max); } /// <summary> /// Returns a non-negative random long within a specified range. /// </summary> public long NextLong(long min, long max) { Guard.ArgumentInRange(max >= min, "Maximum value must be greater than or equal to minimum.", nameof(max)); if (min == max) return min; ulong range = (ulong)(max - min); // Avoid introduction of modulo bias ulong limit = ulong.MaxValue - ulong.MaxValue % range; ulong raw; do { raw = RawULong(); } while (raw > limit); return (long)(raw % range + (ulong)min); } #endregion #region Unsigned Longs /// <summary> /// Returns a random ulong. /// </summary> [CLSCompliant(false)] public ulong NextULong() { return NextULong(0ul, ulong.MaxValue); } /// <summary> /// Returns a random ulong less than the specified maximum. /// </summary> [CLSCompliant(false)] public ulong NextULong(ulong max) { return NextULong(0ul, max); } /// <summary> /// Returns a non-negative random long within a specified range. /// </summary> [CLSCompliant(false)] public ulong NextULong(ulong min, ulong max) { Guard.ArgumentInRange(max >= min, "Maximum value must be greater than or equal to minimum.", nameof(max)); ulong range = max - min; if (range == 0) return min; // Avoid introduction of modulo bias ulong limit = ulong.MaxValue - ulong.MaxValue % range; ulong raw; do { raw = RawULong(); } while (raw > limit); return unchecked(raw % range + min); } #endregion #region Bytes /// <summary> /// Returns a random Byte /// </summary> public byte NextByte() { return NextByte((byte)0, Byte.MaxValue); } /// <summary> /// Returns a random Byte less than the specified maximum. /// </summary> public byte NextByte(byte max) { return NextByte((byte)0, max); } /// <summary> /// Returns a random Byte within a specified range /// </summary> public byte NextByte(byte min, byte max) { return (byte)Next(min, max); } #endregion #region SBytes /// <summary> /// Returns a random SByte /// </summary> [CLSCompliant(false)] public sbyte NextSByte() { return NextSByte((sbyte)0, SByte.MaxValue); } /// <summary> /// Returns a random sbyte less than the specified maximum. /// </summary> [CLSCompliant(false)] public sbyte NextSByte(sbyte max) { return NextSByte((sbyte)0, max); } /// <summary> /// Returns a random sbyte within a specified range /// </summary> [CLSCompliant(false)] public sbyte NextSByte(sbyte min, sbyte max) { return (sbyte)Next(min, max); } #endregion #region Bools /// <summary> /// Returns a random bool /// </summary> public bool NextBool() { return NextDouble() < 0.5; } /// <summary> /// Returns a random bool based on the probability a true result /// </summary> public bool NextBool(double probability) { Guard.ArgumentInRange(probability >= 0.0 && probability <= 1.0, "Probability must be from 0.0 to 1.0", nameof(probability)); return NextDouble() < probability; } #endregion #region Doubles // NOTE: NextDouble() is inherited from Random. /// <summary> /// Returns a random double between 0.0 and the specified maximum. /// </summary> public double NextDouble(double max) { return NextDouble() * max; } /// <summary> /// Returns a random double within a specified range. /// </summary> public double NextDouble(double min, double max) { Guard.ArgumentInRange(max >= min, "Maximum value must be greater than or equal to minimum.", nameof(max)); if (max == min) return min; double range = max - min; return NextDouble() * range + min; } #endregion #region Floats /// <summary> /// Returns a random float. /// </summary> public float NextFloat() { return (float)NextDouble(); } /// <summary> /// Returns a random float between 0.0 and the specified maximum. /// </summary> public float NextFloat(float max) { return (float)NextDouble(max); } /// <summary> /// Returns a random float within a specified range. /// </summary> public float NextFloat(float min, float max) { return (float)NextDouble(min, max); } #endregion #region Enums /// <summary> /// Returns a random enum value of the specified Type as an object. /// </summary> public object NextEnum(Type type) { Array enums = Enum.GetValues(type); return enums.GetValue(Next(0, enums.Length)); } /// <summary> /// Returns a random enum value of the specified Type. /// </summary> public T NextEnum<T>() { return (T)NextEnum(typeof(T)); } #endregion #region String /// <summary> /// Default characters for random functions. /// </summary> /// <remarks>Default characters are the English alphabet (uppercase &amp; lowercase), Arabic numerals, and underscore</remarks> public const string DefaultStringChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789_"; private const int DefaultStringLength = 25; /// <summary> /// Generate a random string based on the characters from the input string. /// </summary> /// <param name="outputLength">desired length of output string.</param> /// <param name="allowedChars">string representing the set of characters from which to construct the resulting string</param> /// <returns>A random string of arbitrary length</returns> public string GetString(int outputLength, string allowedChars) { var sb = new StringBuilder(outputLength); for (int i = 0; i < outputLength ; i++) { sb.Append(allowedChars[Next(0,allowedChars.Length)]); } return sb.ToString(); } /// <summary> /// Generate a random string based on the characters from the input string. /// </summary> /// <param name="outputLength">desired length of output string.</param> /// <returns>A random string of arbitrary length</returns> /// <remarks>Uses <see cref="DefaultStringChars">DefaultStringChars</see> as the input character set </remarks> public string GetString(int outputLength) { return GetString(outputLength, DefaultStringChars); } /// <summary> /// Generate a random string based on the characters from the input string. /// </summary> /// <returns>A random string of the default length</returns> /// <remarks>Uses <see cref="DefaultStringChars">DefaultStringChars</see> as the input character set </remarks> public string GetString() { return GetString(DefaultStringLength, DefaultStringChars); } #endregion #region Decimal // We treat decimal as an integral type for now. // The scaling factor is always zero. /// <summary> /// Returns a random decimal. /// </summary> public decimal NextDecimal() { int low = Next(0, int.MaxValue); int mid = Next(0, int.MaxValue); int high = Next(0, int.MaxValue); return new Decimal(low, mid, high, false, 0); } /// <summary> /// Returns a random decimal between positive zero and the specified maximum. /// </summary> public decimal NextDecimal(decimal max) { return NextDecimal() % max; } /// <summary> /// Returns a random decimal within a specified range, which is not /// permitted to exceed decimal.MaxVal in the current implementation. /// </summary> /// <remarks> /// A limitation of this implementation is that the range from min /// to max must not exceed decimal.MaxVal. /// </remarks> public decimal NextDecimal(decimal min, decimal max) { Guard.ArgumentInRange(max >= min, "Maximum value must be greater than or equal to minimum.", nameof(max)); // Check that the range is not greater than MaxValue without // first calculating it, since this would cause overflow Guard.ArgumentValid(max < 0M == min < 0M || min + decimal.MaxValue >= max, "Range too great for decimal data, use double range", nameof(max)); if (min == max) return min; decimal range = max - min; // Avoid introduction of modulo bias decimal limit = decimal.MaxValue - decimal.MaxValue % range; decimal raw; do { raw = NextDecimal(); } while (raw > limit); return unchecked(raw % range + min); } #endregion #region Guid /// <summary> /// Generates a valid version 4 <see cref="Guid"/>. /// </summary> public Guid NextGuid() { //We use the algorithm described in https://tools.ietf.org/html/rfc4122#section-4.4 var b = new byte[16]; NextBytes(b); //set the version to 4 b[7] = (byte)((b[7] & 0x0f) | 0x40); //set the 2-bits indicating the variant to 1 and 0 b[8] = (byte)((b[8] & 0x3f) | 0x80); return new Guid(b); } #endregion #region Helper Methods private uint RawUInt() { var buffer = new byte[sizeof(uint)]; NextBytes(buffer); return BitConverter.ToUInt32(buffer, 0); } private uint RawUShort() { var buffer = new byte[sizeof(uint)]; NextBytes(buffer); return BitConverter.ToUInt32(buffer, 0); } private ulong RawULong() { var buffer = new byte[sizeof(ulong)]; NextBytes(buffer); return BitConverter.ToUInt64(buffer, 0); } private long RawLong() { var buffer = new byte[sizeof(long)]; NextBytes(buffer); return BitConverter.ToInt64(buffer, 0); } private decimal RawDecimal() { int low = Next(0, int.MaxValue); int mid = Next(0, int.MaxValue); int hi = Next(0, int.MaxValue); bool isNegative = NextBool(); byte scale = NextByte(29); return new Decimal(low, mid, hi, isNegative, scale); } #endregion } }
namespace Factotum { partial class GridSizeEdit { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(GridSizeEdit)); this.btnOK = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.errorProvider1 = new System.Windows.Forms.ErrorProvider(this.components); this.btnCancel = new System.Windows.Forms.Button(); this.ckActive = new System.Windows.Forms.CheckBox(); this.txtName = new Factotum.TextBoxWithUndo(); this.txtAxialDistance = new Factotum.TextBoxWithUndo(); this.label3 = new System.Windows.Forms.Label(); this.txtRadialDistance = new Factotum.TextBoxWithUndo(); this.label2 = new System.Windows.Forms.Label(); this.txtMaxOD = new Factotum.TextBoxWithUndo(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.errorProvider1)).BeginInit(); this.SuspendLayout(); // // btnOK // this.btnOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnOK.Location = new System.Drawing.Point(144, 143); this.btnOK.Name = "btnOK"; this.btnOK.Size = new System.Drawing.Size(64, 22); this.btnOK.TabIndex = 8; this.btnOK.Text = "OK"; this.btnOK.UseVisualStyleBackColor = true; this.btnOK.Click += new System.EventHandler(this.btnOK_Click); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(16, 15); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(35, 13); this.label1.TabIndex = 0; this.label1.Text = "Name"; // // errorProvider1 // this.errorProvider1.ContainerControl = this; // // btnCancel // this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnCancel.Location = new System.Drawing.Point(214, 143); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(64, 22); this.btnCancel.TabIndex = 9; this.btnCancel.Text = "Cancel"; this.btnCancel.UseVisualStyleBackColor = true; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // ckActive // this.ckActive.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.ckActive.AutoSize = true; this.ckActive.Location = new System.Drawing.Point(27, 143); this.ckActive.Name = "ckActive"; this.ckActive.Size = new System.Drawing.Size(56, 17); this.ckActive.TabIndex = 10; this.ckActive.TabStop = false; this.ckActive.Text = "Active"; this.ckActive.UseVisualStyleBackColor = true; this.ckActive.Click += new System.EventHandler(this.ckActive_Click); // // txtName // this.txtName.Location = new System.Drawing.Point(57, 12); this.txtName.Name = "txtName"; this.txtName.Size = new System.Drawing.Size(147, 20); this.txtName.TabIndex = 1; this.txtName.TextChanged += new System.EventHandler(this.txtName_TextChanged); this.txtName.Validating += new System.ComponentModel.CancelEventHandler(this.txtName_Validating); // // txtAxialDistance // this.txtAxialDistance.Location = new System.Drawing.Point(138, 38); this.txtAxialDistance.Name = "txtAxialDistance"; this.txtAxialDistance.Size = new System.Drawing.Size(66, 20); this.txtAxialDistance.TabIndex = 3; this.txtAxialDistance.TextChanged += new System.EventHandler(this.txtAxialDistance_TextChanged); this.txtAxialDistance.Validating += new System.ComponentModel.CancelEventHandler(this.txtAxialDistance_Validating); // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(61, 41); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(71, 13); this.label3.TabIndex = 2; this.label3.Text = "AxialDistance"; // // txtRadialDistance // this.txtRadialDistance.Location = new System.Drawing.Point(138, 64); this.txtRadialDistance.Name = "txtRadialDistance"; this.txtRadialDistance.Size = new System.Drawing.Size(66, 20); this.txtRadialDistance.TabIndex = 5; this.txtRadialDistance.TextChanged += new System.EventHandler(this.txtRadialDistance_TextChanged); this.txtRadialDistance.Validating += new System.ComponentModel.CancelEventHandler(this.txtRadialDistance_Validating); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(50, 67); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(82, 13); this.label2.TabIndex = 4; this.label2.Text = "Radial Distance"; // // txtMaxOD // this.txtMaxOD.Location = new System.Drawing.Point(138, 90); this.txtMaxOD.Name = "txtMaxOD"; this.txtMaxOD.Size = new System.Drawing.Size(66, 20); this.txtMaxOD.TabIndex = 7; this.txtMaxOD.TextChanged += new System.EventHandler(this.txtMaxOD_TextChanged); this.txtMaxOD.Validating += new System.ComponentModel.CancelEventHandler(this.txtMaxOD_Validating); // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(62, 93); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(70, 13); this.label4.TabIndex = 6; this.label4.Text = "Max Pipe OD"; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(220, 93); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(18, 13); this.label5.TabIndex = 13; this.label5.Text = "in."; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(220, 67); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(18, 13); this.label6.TabIndex = 12; this.label6.Text = "in."; // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(220, 41); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(18, 13); this.label7.TabIndex = 11; this.label7.Text = "in."; // // GridSizeEdit // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(290, 177); this.Controls.Add(this.label5); this.Controls.Add(this.label6); this.Controls.Add(this.label7); this.Controls.Add(this.txtMaxOD); this.Controls.Add(this.label4); this.Controls.Add(this.txtRadialDistance); this.Controls.Add(this.label2); this.Controls.Add(this.txtAxialDistance); this.Controls.Add(this.label3); this.Controls.Add(this.txtName); this.Controls.Add(this.ckActive); this.Controls.Add(this.btnCancel); this.Controls.Add(this.label1); this.Controls.Add(this.btnOK); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MinimumSize = new System.Drawing.Size(298, 207); this.Name = "GridSizeEdit"; this.Text = "Edit Grid Size"; ((System.ComponentModel.ISupportInitialize)(this.errorProvider1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button btnOK; private System.Windows.Forms.Label label1; private System.Windows.Forms.ErrorProvider errorProvider1; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.CheckBox ckActive; private TextBoxWithUndo txtName; private TextBoxWithUndo txtAxialDistance; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label7; private TextBoxWithUndo txtMaxOD; private System.Windows.Forms.Label label4; private TextBoxWithUndo txtRadialDistance; private System.Windows.Forms.Label label2; } }
/* * Copyright 2008 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. */ /* * A web-safe Base64 encoding and decoding utility class. See RFC 3548 * * @author [email protected] (Steve Weis) * * * 8/2012 Directly ported to C# and added JsonConverters - [email protected] (James Tuley) */ using System; using System.IO; using System.Numerics; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Bson; namespace Keyczar.Util { /// <summary> /// Encodes bytes into websafe base 64 /// </summary> public static class WebSafeBase64 { #region Helpers private static readonly char[] ALPHABET = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_' }; /** * Mapping table from Base64 characters to 6-bit nibbles. */ private static readonly sbyte[] DECODE = new sbyte[128]; private static readonly char[] WHITESPACE = {'\t', '\n', '\r', ' ', '\f'}; static WebSafeBase64() { for (int i = 0; i < DECODE.Length; i++) { DECODE[i] = -1; } for (int i = 0; i < WHITESPACE.Length; i++) { DECODE[WHITESPACE[i]] = -2; } for (int i = 0; i < ALPHABET.Length; i++) { DECODE[ALPHABET[i]] = (sbyte) i; } } private static byte GetByte(int i) { if (i < 0 || i > 127 || DECODE[i] == -1) { throw new Base64DecodingException("Invalid Encoding"); } return (byte) DECODE[i]; } /// <summary> /// Decoding exception /// </summary> [Serializable] public class Base64DecodingException : Exception { /// <summary> /// Initializes a new instance of the <see cref="Base64DecodingException"/> class. /// </summary> /// <param name="message">The message.</param> public Base64DecodingException(string message) { } /// <summary> /// Initializes a new instance of the <see cref="Base64DecodingException" /> class. /// </summary> public Base64DecodingException() : base() { } /// <summary> /// Initializes a new instance of the <see cref="Base64DecodingException" /> class. /// </summary> /// <param name="message">The message.</param> /// <param name="innerException">The inner exception.</param> public Base64DecodingException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Initializes a new instance of the <see cref="Base64DecodingException" /> class. /// </summary> /// <param name="info">The info.</param> /// <param name="context">The context.</param> protected Base64DecodingException(SerializationInfo info, StreamingContext context) : base(info, context) { } } private static bool IsWhiteSpace(int i) { return DECODE[i] == -2; } #endregion /// <summary> /// Encodes the specified input. /// </summary> /// <param name="input">The input.</param> /// <returns></returns> public static char[] Encode(byte[] input) { int inputBlocks = input.Length/3; int remainder = input.Length%3; int outputLen = inputBlocks*4; switch (remainder) { case 1: outputLen += 2; break; case 2: outputLen += 3; break; } char[] outChar = new char[outputLen]; int outPos = 0; int inPos = 0; for (int i = 0; i < inputBlocks; i++) { int buffer = (0xFF & input[inPos++]) << 16 | (0xFF & input[inPos++]) << 8 | (0xFF & input[inPos++]); outChar[outPos++] = ALPHABET[(buffer >> 18) & 0x3F]; outChar[outPos++] = ALPHABET[(buffer >> 12) & 0x3F]; outChar[outPos++] = ALPHABET[(buffer >> 6) & 0x3F]; outChar[outPos++] = ALPHABET[buffer & 0x3F]; } if (remainder > 0) { int buffer = (0xFF & input[inPos++]) << 16; if (remainder == 2) { // ReSharper disable once RedundantAssignment buffer |= (0xFF & input[inPos++]) << 8; //might be unnecessary but is more readable - lgtm [cs/useless-assignment-to-local] } outChar[outPos++] = ALPHABET[(buffer >> 18) & 0x3F]; outChar[outPos++] = ALPHABET[(buffer >> 12) & 0x3F]; if (remainder == 2) { // ReSharper disable once RedundantAssignment outChar[outPos++] = ALPHABET[(buffer >> 6) & 0x3F]; //might be unnecessary but is more readable - lgtm [cs/useless-assignment-to-local] } } return outChar; } /// <summary> /// Decodes the specified input. /// </summary> /// <param name="input">The input.</param> /// <returns></returns> public static Byte[] Decode(char[] input) { int inLen = input.Length; if (inLen == 0) return new byte[0]; // Trim up to two trailing '=' padding characters if (input[inLen - 1] == '=') { inLen--; } if (input[inLen - 1] == '=') { inLen--; } // Ignore whitespace int whiteSpaceChars = 0; foreach (char c in input) { if (IsWhiteSpace(c)) { whiteSpaceChars++; } } inLen -= whiteSpaceChars; int inputBlocks = inLen/4; int remainder = inLen%4; int outputLen = inputBlocks*3; switch (remainder) { case 1: throw new Base64DecodingException("Invalid Length"); case 2: outputLen += 1; break; case 3: outputLen += 2; break; } byte[] outChar = new byte[outputLen]; int buffer = 0; int buffCount = 0; int outPos = 0; for (int i = 0; i < inLen + whiteSpaceChars; i++) { if (!IsWhiteSpace(input[i])) { buffer = (buffer << 6) | GetByte(input[i]); buffCount++; } if (buffCount == 4) { outChar[outPos++] = (byte) (buffer >> 16); outChar[outPos++] = (byte) (buffer >> 8); outChar[outPos++] = (byte) buffer; buffer = 0; buffCount = 0; } } switch (buffCount) { case 2: // ReSharper disable once RedundantAssignment outChar[outPos++] = (byte) (buffer >> 4); //might be unnecessary but is more readable - lgtm [cs/useless-assignment-to-local] break; case 3: outChar[outPos++] = (byte) (buffer >> 10); // ReSharper disable once RedundantAssignment outChar[outPos++] = (byte) (buffer >> 2); //might be unnecessary but is more readable - lgtm [cs/useless-assignment-to-local] break; } return outChar; } } /// <summary> /// Converts json string to the strong typed WebBase64 and viceversa /// </summary> public class WebBase64JsonConverter : Newtonsoft.Json.JsonConverter { /// <summary> /// Writes the JSON representation of the object. /// </summary> /// <param name="writer">The <see cref="T:Newtonsoft.Json.JsonWriter"/> to write to.</param> /// <param name="value">The value.</param> /// <param name="serializer">The calling serializer.</param> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { serializer.Serialize(writer, value.ToString()); } /// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader"/> to read from.</param> /// <param name="objectType">Type of the object.</param> /// <param name="existingValue">The existing value of object being read.</param> /// <param name="serializer">The calling serializer.</param> /// <returns>The object value.</returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var value = serializer.Deserialize<String>(reader); return (WebBase64) value; } /// <summary> /// Determines whether this instance can convert the specified object type. /// </summary> /// <param name="objectType">Type of the object.</param> /// <returns> /// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>. /// </returns> public override bool CanConvert(Type objectType) { return typeof (WebBase64).IsAssignableFrom(objectType); } } /// <summary> /// Encodes byte arrays to websafe base64 in json and vice versa /// </summary> public class BigIntegerWebSafeBase64ByteConverter : WebSafeBase64ByteConverter { /// <summary> /// Writes the JSON representation of the object. /// </summary> /// <param name="writer">The <see cref="T:Newtonsoft.Json.JsonWriter"/> to write to.</param> /// <param name="value">The value.</param> /// <param name="serializer">The calling serializer.</param> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { base.WriteJson(writer, Utility.GetBytes((BigInteger) value), serializer); } /// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader"/> to read from.</param> /// <param name="objectType">Type of the object.</param> /// <param name="existingValue">The existing value of object being read.</param> /// <param name="serializer">The calling serializer.</param> /// <returns>The object value.</returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var value = (byte[]) base.ReadJson(reader, objectType, existingValue, serializer); var final = Utility.ToBigInteger(value); Secure.Clear(value); return final; } /// <summary> /// Determines whether this instance can convert the specified object type. /// </summary> /// <param name="objectType">Type of the object.</param> /// <returns> /// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>. /// </returns> public override bool CanConvert(Type objectType) { return objectType == typeof (BigInteger); } } /// <summary> /// Encodes byte arrays to websafe base64 in json and vice versa /// </summary> public class WebSafeBase64ByteConverter : JsonConverter { /// <summary> /// Writes the JSON representation of the object. /// </summary> /// <param name="writer">The <see cref="T:Newtonsoft.Json.JsonWriter"/> to write to.</param> /// <param name="value">The value.</param> /// <param name="serializer">The calling serializer.</param> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (writer is BsonDataWriter) { serializer.Serialize(writer, value); } else { var encoded = WebSafeBase64.Encode(((byte[]) value)); serializer.Serialize(writer, new string(encoded)); Secure.Clear(encoded); } } /// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader"/> to read from.</param> /// <param name="objectType">Type of the object.</param> /// <param name="existingValue">The existing value of object being read.</param> /// <param name="serializer">The calling serializer.</param> /// <returns>The object value.</returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { byte[] final; if (reader is BsonDataReader || reader is RawJsonReader) { final = serializer.Deserialize<byte[]>(reader); } else { var base64 = (serializer.Deserialize<string>(reader) ?? String.Empty).ToCharArray(); final = WebSafeBase64.Decode(base64); Secure.Clear(base64); } return final; } /// <summary> /// Raw json reader /// </summary> public class RawJsonReader : JsonTextReader { /// <summary> /// Initializes a new instance of the <see cref="RawJsonReader" /> class. /// </summary> /// <param name="reader">The reader.</param> public RawJsonReader(TextReader reader) : base(reader) { } } /// <summary> /// Determines whether this instance can convert the specified object type. /// </summary> /// <param name="objectType">Type of the object.</param> /// <returns> /// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>. /// </returns> public override bool CanConvert(Type objectType) { return objectType == typeof (byte[]); } } }
// 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.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.LanguageServices { internal partial class CSharpSymbolDisplayService { protected class SymbolDescriptionBuilder : AbstractSymbolDescriptionBuilder { private static readonly SymbolDisplayFormat s_minimallyQualifiedFormat = SymbolDisplayFormat.MinimallyQualifiedFormat .AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName) .RemoveParameterOptions(SymbolDisplayParameterOptions.IncludeDefaultValue) .WithKindOptions(SymbolDisplayKindOptions.None); private static readonly SymbolDisplayFormat s_minimallyQualifiedFormatWithConstants = s_minimallyQualifiedFormat .AddLocalOptions(SymbolDisplayLocalOptions.IncludeConstantValue) .AddMemberOptions(SymbolDisplayMemberOptions.IncludeConstantValue) .AddParameterOptions(SymbolDisplayParameterOptions.IncludeDefaultValue); private static readonly SymbolDisplayFormat s_propertySignatureDisplayFormat = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints, memberOptions: SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeContainingType, kindOptions: SymbolDisplayKindOptions.IncludeMemberKeyword, propertyStyle: SymbolDisplayPropertyStyle.ShowReadWriteDescriptor, parameterOptions: SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeDefaultValue | SymbolDisplayParameterOptions.IncludeOptionalBrackets, localOptions: SymbolDisplayLocalOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName); public SymbolDescriptionBuilder( ISymbolDisplayService displayService, SemanticModel semanticModel, int position, Workspace workspace, IAnonymousTypeDisplayService anonymousTypeDisplayService, CancellationToken cancellationToken) : base(displayService, semanticModel, position, workspace, anonymousTypeDisplayService, cancellationToken) { } protected override void AddDeprecatedPrefix() { AddToGroup(SymbolDescriptionGroups.MainDescription, Punctuation("["), PlainText(CSharpFeaturesResources.Deprecated), Punctuation("]"), Space()); } protected override void AddExtensionPrefix() { AddToGroup(SymbolDescriptionGroups.MainDescription, Punctuation("("), PlainText(CSharpFeaturesResources.Extension), Punctuation(")"), Space()); } protected override void AddAwaitablePrefix() { AddToGroup(SymbolDescriptionGroups.MainDescription, Punctuation("("), PlainText(CSharpFeaturesResources.Awaitable), Punctuation(")"), Space()); } protected override void AddAwaitableExtensionPrefix() { AddToGroup(SymbolDescriptionGroups.MainDescription, Punctuation("("), PlainText(CSharpFeaturesResources.AwaitableExtension), Punctuation(")"), Space()); } protected override void AddDescriptionForProperty(IPropertySymbol symbol) { if (symbol.ContainingType?.TypeKind == TypeKind.Interface) { base.AddDescriptionForProperty(symbol); } else { var fullParts = ToMinimalDisplayParts(symbol, s_propertySignatureDisplayFormat); var neededParts = fullParts.SkipWhile(p => p.Symbol == null); AddToGroup(SymbolDescriptionGroups.MainDescription, neededParts); } } protected override Task<IEnumerable<SymbolDisplayPart>> GetInitializerSourcePartsAsync( ISymbol symbol) { // Actually check for C# symbol types here. if (symbol is IParameterSymbol) { return GetInitializerSourcePartsAsync((IParameterSymbol)symbol); } else if (symbol is ILocalSymbol) { return GetInitializerSourcePartsAsync((ILocalSymbol)symbol); } else if (symbol is IFieldSymbol) { return GetInitializerSourcePartsAsync((IFieldSymbol)symbol); } return SpecializedTasks.Default<IEnumerable<SymbolDisplayPart>>(); } private async Task<IEnumerable<SymbolDisplayPart>> GetInitializerSourcePartsAsync(IFieldSymbol symbol) { EqualsValueClauseSyntax initializer = null; var variableDeclarator = await this.GetFirstDeclaration<VariableDeclaratorSyntax>(symbol).ConfigureAwait(false); if (variableDeclarator != null) { initializer = variableDeclarator.Initializer; } if (initializer == null) { var enumMemberDeclaration = await this.GetFirstDeclaration<EnumMemberDeclarationSyntax>(symbol).ConfigureAwait(false); if (enumMemberDeclaration != null) { initializer = enumMemberDeclaration.EqualsValue; } } if (initializer != null) { return await GetInitializerSourcePartsAsync(initializer).ConfigureAwait(false); } return null; } private async Task<IEnumerable<SymbolDisplayPart>> GetInitializerSourcePartsAsync(ILocalSymbol symbol) { var syntax = await this.GetFirstDeclaration<VariableDeclaratorSyntax>(symbol).ConfigureAwait(false); if (syntax != null) { return await GetInitializerSourcePartsAsync(syntax.Initializer).ConfigureAwait(false); } return null; } private async Task<IEnumerable<SymbolDisplayPart>> GetInitializerSourcePartsAsync(IParameterSymbol symbol) { var syntax = await this.GetFirstDeclaration<ParameterSyntax>(symbol).ConfigureAwait(false); if (syntax != null) { return await GetInitializerSourcePartsAsync(syntax.Default).ConfigureAwait(false); } return null; } private async Task<T> GetFirstDeclaration<T>(ISymbol symbol) where T : SyntaxNode { foreach (var syntaxRef in symbol.DeclaringSyntaxReferences) { var syntax = await syntaxRef.GetSyntaxAsync(this.CancellationToken).ConfigureAwait(false); if (syntax is T) { return (T)syntax; } } return null; } private async Task<IEnumerable<SymbolDisplayPart>> GetInitializerSourcePartsAsync(EqualsValueClauseSyntax equalsValue) { if (equalsValue != null && equalsValue.Value != null) { var semanticModel = GetSemanticModel(equalsValue.SyntaxTree); if (semanticModel == null) { return null; } var classifications = Classifier.GetClassifiedSpans(semanticModel, equalsValue.Value.Span, this.Workspace, this.CancellationToken); var text = await semanticModel.SyntaxTree.GetTextAsync(this.CancellationToken).ConfigureAwait(false); return ConvertClassifications(text, classifications); } return null; } protected override void AddAwaitableUsageText(IMethodSymbol method, SemanticModel semanticModel, int position) { AddToGroup(SymbolDescriptionGroups.AwaitableUsageText, method.ToAwaitableParts(CSharpFeaturesResources.Await, "x", semanticModel, position)); } protected override SymbolDisplayFormat MinimallyQualifiedFormat { get { return s_minimallyQualifiedFormat; } } protected override SymbolDisplayFormat MinimallyQualifiedFormatWithConstants { get { return s_minimallyQualifiedFormatWithConstants; } } } } }
namespace SimpleErrorHandler { using System; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.Mail; using NameValueCollection = System.Collections.Specialized.NameValueCollection; using Comparer = System.Collections.Comparer; using StringWriter = System.IO.StringWriter; using System.Text.RegularExpressions; /// <summary> /// Renders an HTML page displaying details about an error from the error log. /// </summary> internal sealed class ErrorDetailPage : ErrorPageBase { private ErrorLogEntry _errorEntry; protected override void OnLoad(EventArgs e) { string errorId = this.Request.QueryString["id"] ?? ""; if (errorId.Length == 0) return; _errorEntry = this.ErrorLog.GetError(errorId); if (_errorEntry == null) return; this.Title = string.Format("Error: {0} [{1}]", _errorEntry.Error.Type, _errorEntry.Id); base.OnLoad(e); } protected override void RenderHead(HtmlTextWriter w) { base.RenderHead(w); } protected override void RenderContents(HtmlTextWriter w) { if (_errorEntry != null) { RenderError(w); } else { RenderNoError(w); } } private void RenderNoError(HtmlTextWriter w) { w.RenderBeginTag(HtmlTextWriterTag.P); w.Write("Error not found in log."); w.RenderEndTag(); // </p> w.WriteLine(); } private void RenderError(HtmlTextWriter w) { Error error = _errorEntry.Error; if (error.WebHostHtmlMessage.Length != 0) { w.Write(@"<div id=""error-view"">"); string htmlUrl = this.BasePageName + "/html?id=" + _errorEntry.Id; w.Write(String.Format(@"<a href=""{0}"" title="""">view original error message (as seen by user)</a>", htmlUrl)); w.Write("</div>"); } w.AddAttribute(HtmlTextWriterAttribute.Id, "PageTitle"); w.RenderBeginTag(HtmlTextWriterTag.P); Server.HtmlEncode(error.Message, w); w.RenderEndTag(); // </p> w.WriteLine(); w.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorTitle"); w.RenderBeginTag(HtmlTextWriterTag.P); w.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorType"); w.RenderBeginTag(HtmlTextWriterTag.Span); Server.HtmlEncode(error.Type, w); w.RenderEndTag(); // </span> w.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorTypeMessageSeparator"); w.RenderBeginTag(HtmlTextWriterTag.Span); w.Write(": "); w.RenderEndTag(); // </span> //w.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorMessage"); //w.RenderBeginTag(HtmlTextWriterTag.Span); //Server.HtmlEncode(error.Message, w); //w.RenderEndTag(); // </span> w.RenderEndTag(); // </p> w.WriteLine(); // Do we have details, like the stack trace? If so, then write // them out in a pre-formatted (pre) element. if (error.Detail.Length != 0) { w.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorDetail"); w.RenderBeginTag(HtmlTextWriterTag.Pre); w.Flush(); Server.HtmlEncode(error.Detail, w.InnerWriter); w.RenderEndTag(); // </pre> w.WriteLine(); } // Write out the error log time, in local server time w.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorLogTime"); w.RenderBeginTag(HtmlTextWriterTag.P); w.Write(string.Format(@"occurred <b>{2}</b> on {0} at {1}", error.Time.ToLongDateString(), error.Time.ToLongTimeString(), error.Time.ToRelativeTime()), w); w.RenderEndTag(); // </p> w.WriteLine(); // If this error has context, then write it out. RenderCollection(w, error.ServerVariables, "ServerVariables", "Server Variables"); RenderCollection(w, error.Form, "Form", "Form"); RenderCollection(w, error.Cookies, "Cookies", "Cookies"); RenderCollection(w, error.QueryString, "QueryString", "QueryString"); base.RenderContents(w); } private string PrepareCell(string s) { if (Regex.IsMatch(s, @"%[A-Z0-9][A-Z0-9]")) { s = Server.UrlDecode(s); } if (Regex.IsMatch(s, "^(https?|ftp|file)://")) { return Regex.Replace(s, @"((?:https?|ftp|file)://.*)", @"<a href=""$1"">$1</a>"); } if (Regex.IsMatch(s, "/[^ /,]+/")) { // block special case of "/LM/W3SVC/1" if (!s.Contains("/LM")) { return Regex.Replace(s, @"(.*)", @"<a href=""$1"">$1</a>"); } } return Server.HtmlEncode(s); } private string _hidden_keys = "|ALL_HTTP|ALL_RAW|HTTP_COOKIE|HTTP_CONTENT_LENGTH|HTTP_CONTENT_TYPE|QUERY_STRING|"; private string _unimportant_keys = "|HTTP_ACCEPT_ENCODING|HTTP_ACCEPT_LANGUAGE|HTTP_CONNECTION|HTTP_HOST|HTTP_KEEP_ALIVE|PATH_TRANSLATED|SERVER_NAME|SERVER_PORT|SERVER_PORT_SECURE|SERVER_PROTOCOL|HTTP_ACCEPT|HTTP_ACCEPT_CHARSET|APPL_PHYSICAL_PATH|GATEWAY_INTERFACE|HTTPS|INSTANCE_ID|INSTANCE_META_PATH|SERVER_SOFTWARE|APPL_MD_PATH|PATH_INFO|SCRIPT_NAME|REMOTE_PORT|"; private void RenderCollection(HtmlTextWriter w, NameValueCollection c, string id, string title) { if (c == null || c.Count == 0) return; w.AddAttribute(HtmlTextWriterAttribute.Id, id); w.RenderBeginTag(HtmlTextWriterTag.Div); w.AddAttribute(HtmlTextWriterAttribute.Class, "table-caption"); w.RenderBeginTag(HtmlTextWriterTag.P); this.Server.HtmlEncode(title, w); w.RenderEndTag(); // </p> w.WriteLine(); w.AddAttribute(HtmlTextWriterAttribute.Class, "scroll-view"); w.RenderBeginTag(HtmlTextWriterTag.Div); Table table = new Table(); table.CellSpacing = 0; string[] keys = c.AllKeys; Array.Sort(keys, Comparer.DefaultInvariant); int i = 0; foreach (var key in keys) { string value = c[key]; if (!String.IsNullOrEmpty(value) && !IsHidden(key)) { bool unimportant = IsUnimportant(key); string matchingKeys = ""; if (!unimportant) { matchingKeys = GetMatchingKeys(c, value); if (matchingKeys != null) { _hidden_keys += matchingKeys.Replace(", ", "|") + "|"; } } TableRow bodyRow = new TableRow(); if (unimportant) bodyRow.CssClass = "unimportant-row"; else { i++; bodyRow.CssClass = i % 2 == 0 ? "even-row" : "odd-row"; } TableCell cell; // key cell = new TableCell(); if (!String.IsNullOrEmpty(matchingKeys)) cell.Text = Server.HtmlEncode(matchingKeys); else cell.Text = Server.HtmlEncode(key); cell.CssClass = "key-col"; bodyRow.Cells.Add(cell); // value cell = new TableCell(); cell.Text = PrepareCell(value); cell.CssClass = "value-col"; bodyRow.Cells.Add(cell); table.Rows.Add(bodyRow); } } table.RenderControl(w); w.RenderEndTag(); // </div> w.WriteLine(); w.RenderEndTag(); // </div> w.WriteLine(); } /// <summary> /// returns true of the target is contained in the list; /// presumes list is pipe delimited like |apples|oranges|pears| /// </summary> private bool Matches(string list, string target) { return list.Contains("|" + target + "|"); } private bool IsUnimportant(string key) { return Matches(_unimportant_keys, key); } private bool IsHidden(string key) { return Matches(_hidden_keys, key); } private string GetMatchingKeys(NameValueCollection nvc, string s) { string matchingKeys = ""; int matches = 0; foreach (string key in nvc.Keys) { if (nvc[key] == s && !IsUnimportant(key) && !IsHidden(key)) { matches++; matchingKeys += key + ", "; } } if (matches == 1) return null; else return matchingKeys.Substring(0, matchingKeys.Length - 2); } } }
//------------------------------------------------------------------------------ // <copyright file="WebBrowserEvent.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // // Description: // WebBrowserSite is a sub-class of ActiveXSite. // Used to implement IDocHostUIHandler. // // Copied from WebBrowser.cs in [....] // // History // 06/16/05 - marka - Created // 04/24/08 - [....] - Implemented hosting the WebOC in the browser process for IE 7+ Protected Mode. // //------------------------------------------------------------------------------ using System; using System.ComponentModel; using System.Diagnostics; using System.Runtime.InteropServices; using System.Windows; using MS.Win32; using System.Security ; using MS.Internal.Interop; using MS.Internal.PresentationFramework; using System.Windows.Controls; using System.Windows.Interop; using System.Windows.Input; using System.Windows.Threading; using System.Threading; using IComDataObject = System.Runtime.InteropServices.ComTypes.IDataObject; namespace MS.Internal.Controls { // // WebBrowserSite class: // /// /// <summary> /// Provides a default WebBrowserSite implementation for use in the CreateWebBrowserSite /// method in the WebBrowser class. /// </summary> /// <SecurityNote> /// WebOCHostedInBrowserProcess - defense in depth: /// These interface implementations are exposed across a security boundary. We must not allow a /// compromised low-integrity-level browser process to gain elevation of privilege via our process or /// tamper with its state. (Attacking the WebOC via this interface is not interesting, because the WebOC /// is directly accessible in the browser process.) Each interface implementation method must be /// carefully reviewed to ensure that it cannot be abused by disclosing protected resources or by passing /// malicious data to it. /// </SecurityNote> /// <remarks> /// THREADING ISSUE: When WebBrowser.IsWebOCHostedInBrowserProcess, calls on the interfaces implemented here /// (and on ActiveXSite) arrive on RPC worker threads. This is because CLR objects don't like to stick to /// STA threads. Fortunately, most of the current implementation methods are okay to be called on any thread. /// And if not, switching to the WebBrowser object's thread via the Dispatcher is usually possible & safe. /// In a few scenarios, when we need to call a WebOC method from one of these callback interfaces, we get /// RPC_E_CANTCALLOUT_ININPUTSYNCCALL, which happens because the CLR actually tries to switch to the right /// thread to make the COM call, but that thread is already blocked on an outgoing call (to the WebOC). /// One example is IOleInPlaceSite.OnInPlaceActivate(). /// These failures are silent and safely ignorable for now. If this threading issue becomes more troubling, /// a solution like ActiveXHelper.CreateIDispatchSTAForwarder() is possible. /// </remarks> internal class WebBrowserSite : ActiveXSite, UnsafeNativeMethods.IDocHostUIHandler, UnsafeNativeMethods.IOleControlSite // partial override { /// /// <summary> /// WebBrowser implementation of ActiveXSite. Used to override GetHostInfo. /// and "turn on" our redirect notifications. /// </summary> /// <SecurityNote> /// Critical - calls base class ctor which is critical. /// </SecurityNote> [ SecurityCritical ] internal WebBrowserSite(WebBrowser host) : base(host) { } #region IDocHostUIHandler Implementation int UnsafeNativeMethods.IDocHostUIHandler.ShowContextMenu(int dwID, NativeMethods.POINT pt, object pcmdtReserved, object pdispReserved) { // // Returning S_FALSE will allow the native control to do default processing, // i.e., execute the shortcut key. Returning S_OK will cancel the context menu // return NativeMethods.S_FALSE; } ///<SecurityNote> /// Critical - calls critical code. /// If you change this method - you could affect mitigations. /// **Needs to be critical.** /// TreatAsSafe - information returned from this method is innocous. /// lists the set of browser features/options we've enabled. ///</SecurityNote> [ SecurityCritical, SecurityTreatAsSafe ] int UnsafeNativeMethods.IDocHostUIHandler.GetHostInfo(NativeMethods.DOCHOSTUIINFO info) { WebBrowser wb = (WebBrowser) Host; info.dwDoubleClick = (int) NativeMethods.DOCHOSTUIDBLCLICK.DEFAULT; // // These are the current flags shdocvw uses. Assumed we want the same. // info.dwFlags = (int) ( NativeMethods.DOCHOSTUIFLAG.DISABLE_HELP_MENU | NativeMethods.DOCHOSTUIFLAG.DISABLE_SCRIPT_INACTIVE | NativeMethods.DOCHOSTUIFLAG.ENABLE_INPLACE_NAVIGATION | NativeMethods.DOCHOSTUIFLAG.IME_ENABLE_RECONVERSION | NativeMethods.DOCHOSTUIFLAG.THEME | NativeMethods.DOCHOSTUIFLAG.ENABLE_FORMS_AUTOCOMPLETE | NativeMethods.DOCHOSTUIFLAG.DISABLE_UNTRUSTEDPROTOCOL | NativeMethods.DOCHOSTUIFLAG.LOCAL_MACHINE_ACCESS_CHECK | NativeMethods.DOCHOSTUIFLAG.ENABLE_REDIRECT_NOTIFICATION | NativeMethods.DOCHOSTUIFLAG.NO3DOUTERBORDER); return NativeMethods.S_OK; } int UnsafeNativeMethods.IDocHostUIHandler.EnableModeless(bool fEnable) { return NativeMethods.E_NOTIMPL; } /// <SecurityNote> /// Critical : Accepts critical IOleInPlaceActiveObject, IOleCommandTarget, IOleInPlaceFrame, IOleInPlaceUIWindow as argument /// Safe : Performs no actions on critical argument, exposes no critical data to caller /// </SecurityNote> [SecuritySafeCritical] int UnsafeNativeMethods.IDocHostUIHandler.ShowUI(int dwID, UnsafeNativeMethods.IOleInPlaceActiveObject activeObject, NativeMethods.IOleCommandTarget commandTarget, UnsafeNativeMethods.IOleInPlaceFrame frame, UnsafeNativeMethods.IOleInPlaceUIWindow doc) { return NativeMethods.E_NOTIMPL; } int UnsafeNativeMethods.IDocHostUIHandler.HideUI() { return NativeMethods.E_NOTIMPL; } int UnsafeNativeMethods.IDocHostUIHandler.UpdateUI() { return NativeMethods.E_NOTIMPL; } int UnsafeNativeMethods.IDocHostUIHandler.OnDocWindowActivate(bool fActivate) { return NativeMethods.E_NOTIMPL; } int UnsafeNativeMethods.IDocHostUIHandler.OnFrameWindowActivate(bool fActivate) { return NativeMethods.E_NOTIMPL; } /// <SecurityNote> /// Critical : Accepts critical IOleInPlaceUIWindow as argument /// Safe : Performs no actions on critical argument, exposes no critical data to caller /// </SecurityNote> [SecuritySafeCritical] int UnsafeNativeMethods.IDocHostUIHandler.ResizeBorder(NativeMethods.COMRECT rect, UnsafeNativeMethods.IOleInPlaceUIWindow doc, bool fFrameWindow) { return NativeMethods.E_NOTIMPL; } int UnsafeNativeMethods.IDocHostUIHandler.GetOptionKeyPath(string[] pbstrKey, int dw) { return NativeMethods.E_NOTIMPL; } /// <SecurityNote> /// Critical : Accepts critical IOleDropTarget as argument /// </SecurityNote> [SecurityCritical] int UnsafeNativeMethods.IDocHostUIHandler.GetDropTarget(UnsafeNativeMethods.IOleDropTarget pDropTarget, out UnsafeNativeMethods.IOleDropTarget ppDropTarget) { // // Set to null no matter what we return, to prevent the marshaller // from going crazy if the pointer points to random stuff. ppDropTarget = null; return NativeMethods.E_NOTIMPL; } /// <summary> /// Critical: This code access critical member Host. /// TreatAsSafe: The object returned is sandboxed in the managed environment. /// </summary> [SecurityCritical, SecurityTreatAsSafe] int UnsafeNativeMethods.IDocHostUIHandler.GetExternal(out object ppDispatch) { WebBrowser wb = (WebBrowser) Host; ppDispatch = wb.HostingAdaptor.ObjectForScripting; return NativeMethods.S_OK; } /// <summary> /// Called by the WebOC whenever its IOleInPlaceActiveObject::TranslateAccelerator() is called. /// See also the IOleControlSite.TranslateAccelerator() implementation here. /// </summary> int UnsafeNativeMethods.IDocHostUIHandler.TranslateAccelerator(ref System.Windows.Interop.MSG msg, ref Guid group, int nCmdID) { // // Returning S_FALSE will allow the native control to do default processing, // i.e., execute the shortcut key. Returning S_OK will cancel the shortcut key. /* WebBrowser wb = (WebBrowser)this.Host; if (!wb.WebBrowserShortcutsEnabled) { int keyCode = (int)msg.wParam | (int)Control.ModifierKeys; if (msg.message != WindowMessage.WM_CHAR && Enum.IsDefined(typeof(Shortcut), (Shortcut)keyCode)) { return NativeMethods.S_OK; } return NativeMethods.S_FALSE; } */ return NativeMethods.S_FALSE; } int UnsafeNativeMethods.IDocHostUIHandler.TranslateUrl(int dwTranslate, string strUrlIn, out string pstrUrlOut) { // // Set to null no matter what we return, to prevent the marshaller // from going crazy if the pointer points to random stuff. pstrUrlOut = null; return NativeMethods.E_NOTIMPL; } int UnsafeNativeMethods.IDocHostUIHandler.FilterDataObject(IComDataObject pDO, out IComDataObject ppDORet) { // // Set to null no matter what we return, to prevent the marshaller // from going crazy if the pointer points to random stuff. ppDORet = null; return NativeMethods.E_NOTIMPL; } #endregion /// <remarks> See overview of keyboard input handling in WebBrowser.cs. </remarks> /// <SecurityNote> /// Critical: Access the critical Host property. /// TAS: Host is not exposed. /// WebOCHostedInBrowserProcess: Potential for input spoofing. Currently we handle only the Tab key, /// which is safe. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] int UnsafeNativeMethods.IOleControlSite.TranslateAccelerator(ref MSG msg, int grfModifiers) { // Handle tabbing out of the WebOC if ((WindowMessage)msg.message == WindowMessage.WM_KEYDOWN && (int)msg.wParam == NativeMethods.VK_TAB) { FocusNavigationDirection direction = (grfModifiers & 1/*KEYMOD_SHIFT*/) != 0 ? FocusNavigationDirection.Previous : FocusNavigationDirection.Next; // For the WebOCHostedInBrowserProcess case, we need to switch to the right thread. Host.Dispatcher.Invoke( DispatcherPriority.Send, new SendOrPostCallback(MoveFocusCallback), direction); return NativeMethods.S_OK; } return NativeMethods.S_FALSE; } /// <SecurityNote> /// Critical: Access the critical Host property. /// TAS: Host is not exposed. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] private void MoveFocusCallback(object direction) { Host.MoveFocus(new TraversalRequest((FocusNavigationDirection)direction)); } }; }
// 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.Collections.Generic; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Extensions.LocalisationExtensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Sprites; using osu.Framework.Localisation; using osu.Game.Beatmaps; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; using osu.Game.Resources.Localisation.Web; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.UI; using osu.Game.Scoring; using osuTK; namespace osu.Game.Overlays.BeatmapSet.Scores { public class TopScoreStatisticsSection : CompositeDrawable { private const float margin = 10; private const float top_columns_min_width = 64; private const float bottom_columns_min_width = 45; private readonly FontUsage smallFont = OsuFont.GetFont(size: 16); private readonly FontUsage largeFont = OsuFont.GetFont(size: 22, weight: FontWeight.Light); private readonly TextColumn totalScoreColumn; private readonly TextColumn accuracyColumn; private readonly TextColumn maxComboColumn; private readonly TextColumn ppColumn; private readonly FillFlowContainer<InfoColumn> statisticsColumns; private readonly ModsInfoColumn modsColumn; [Resolved] private ScoreManager scoreManager { get; set; } public TopScoreStatisticsSection() { RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; InternalChild = new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Vertical, Children = new Drawable[] { new FillFlowContainer { Anchor = Anchor.TopRight, Origin = Anchor.TopRight, AutoSizeAxes = Axes.Both, Direction = FillDirection.Horizontal, Spacing = new Vector2(margin, 0), Children = new Drawable[] { totalScoreColumn = new TextColumn(BeatmapsetsStrings.ShowScoreboardHeadersScoreTotal, largeFont, top_columns_min_width), accuracyColumn = new TextColumn(BeatmapsetsStrings.ShowScoreboardHeadersAccuracy, largeFont, top_columns_min_width), maxComboColumn = new TextColumn(BeatmapsetsStrings.ShowScoreboardHeadersCombo, largeFont, top_columns_min_width) } }, new FillFlowContainer { Anchor = Anchor.TopRight, Origin = Anchor.TopRight, AutoSizeAxes = Axes.Both, Direction = FillDirection.Horizontal, Spacing = new Vector2(margin, 0), Children = new Drawable[] { statisticsColumns = new FillFlowContainer<InfoColumn> { AutoSizeAxes = Axes.Both, Direction = FillDirection.Horizontal, Spacing = new Vector2(margin, 0), }, ppColumn = new TextColumn(BeatmapsetsStrings.ShowScoreboardHeaderspp, smallFont, bottom_columns_min_width), modsColumn = new ModsInfoColumn(), } }, } }; } [BackgroundDependencyLoader] private void load() { if (score != null) totalScoreColumn.Current = scoreManager.GetBindableTotalScoreString(score); } private ScoreInfo score; /// <summary> /// Sets the score to be displayed. /// </summary> public ScoreInfo Score { set { if (score == null && value == null) return; if (score?.Equals(value) == true) return; score = value; accuracyColumn.Text = value.DisplayAccuracy; maxComboColumn.Text = value.MaxCombo.ToLocalisableString(@"0\x"); ppColumn.Alpha = value.BeatmapInfo.Status.GrantsPerformancePoints() ? 1 : 0; ppColumn.Text = value.PP?.ToLocalisableString(@"N0"); statisticsColumns.ChildrenEnumerable = value.GetStatisticsForDisplay().Select(createStatisticsColumn); modsColumn.Mods = value.Mods; if (scoreManager != null) totalScoreColumn.Current = scoreManager.GetBindableTotalScoreString(value); } } private TextColumn createStatisticsColumn(HitResultDisplayStatistic stat) => new TextColumn(stat.DisplayName, smallFont, bottom_columns_min_width) { Text = stat.MaxCount == null ? stat.Count.ToLocalisableString(@"N0") : (LocalisableString)$"{stat.Count}/{stat.MaxCount}" }; private class InfoColumn : CompositeDrawable { private readonly Box separator; private readonly OsuSpriteText text; public InfoColumn(LocalisableString title, Drawable content, float? minWidth = null) { AutoSizeAxes = Axes.Both; Margin = new MarginPadding { Vertical = 5 }; InternalChild = new GridContainer { AutoSizeAxes = Axes.Both, ColumnDimensions = new[] { new Dimension(GridSizeMode.AutoSize, minSize: minWidth ?? 0) }, RowDimensions = new[] { new Dimension(GridSizeMode.AutoSize), new Dimension(GridSizeMode.Absolute, 2), new Dimension(GridSizeMode.AutoSize) }, Content = new[] { new Drawable[] { text = new OsuSpriteText { Font = OsuFont.GetFont(size: 10, weight: FontWeight.Bold), Text = title.ToUpper(), // 2px padding bottom + 1px vertical to compensate for the additional spacing because of 1.25 line-height in osu-web Padding = new MarginPadding { Top = 1, Bottom = 3 } } }, new Drawable[] { separator = new Box { Anchor = Anchor.TopLeft, RelativeSizeAxes = Axes.X, Height = 2, }, }, new[] { // osu-web has 4px margin here but also uses 0.9 line-height, reducing margin to 2px seems like a good alternative to that content.With(c => c.Margin = new MarginPadding { Top = 2 }) } } }; } [BackgroundDependencyLoader] private void load(OverlayColourProvider colourProvider) { text.Colour = colourProvider.Foreground1; separator.Colour = colourProvider.Background3; } } private class TextColumn : InfoColumn { private readonly SpriteText text; public TextColumn(LocalisableString title, FontUsage font, float? minWidth = null) : this(title, new OsuSpriteText { Font = font }, minWidth) { } private TextColumn(LocalisableString title, SpriteText text, float? minWidth = null) : base(title, text, minWidth) { this.text = text; } public LocalisableString Text { set => text.Text = value; } public Bindable<string> Current { get => text.Current; set => text.Current = value; } } private class ModsInfoColumn : InfoColumn { private readonly FillFlowContainer modsContainer; public ModsInfoColumn() : this(new FillFlowContainer { AutoSizeAxes = Axes.X, Direction = FillDirection.Horizontal, Spacing = new Vector2(1), Height = 18f }) { } private ModsInfoColumn(FillFlowContainer modsContainer) : base(BeatmapsetsStrings.ShowScoreboardHeadersMods, modsContainer) { this.modsContainer = modsContainer; } public IEnumerable<Mod> Mods { set { modsContainer.Clear(); modsContainer.Children = value.Select(mod => new ModIcon(mod) { AutoSizeAxes = Axes.Both, Scale = new Vector2(0.25f), }).ToList(); } } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; namespace PcapDotNet.Packets.Http { /// <summary> /// RFC 2616 /// /// Message: /// <pre> /// HTTP-message = Request | Response /// /// generic-message = start-line /// *(message-header CRLF) /// CRLF /// [ message-body ] /// /// start-line = Request-Line | Status-Line /// /// message-header = field-name ":" [ field-value ] /// field-name = token /// field-value = *( field-content | LWS ) /// field-content = &lt;the OCTETs making up the field-value and consisting of either *TEXT or combinations of token, separators, and quoted-string> /// /// message-body = entity-body /// | &lt;entity-body encoded as per Transfer-Encoding> /// general-header = Cache-Control /// | Connection /// | Date /// | Pragma /// | Trailer /// | Transfer-Encoding /// | Upgrade /// | Via /// | Warning /// </pre> /// /// Request: /// <pre> /// Request = Request-Line /// *(( general-header /// | request-header /// | entity-header ) CRLF) /// CRLF /// [ message-body ] /// /// Request-Line = Method SP Request-URI SP HTTP-Version CRLF /// /// Method = "OPTIONS" /// | "GET" /// | "HEAD" /// | "POST" /// | "PUT" /// | "DELETE" /// | "TRACE" /// | "CONNECT" /// | extension-method /// /// extension-method = token /// /// Request-URI = "*" | absoluteURI | abs_path | authority /// absoluteURI = scheme ":" ( hier_part | opaque_part ) /// scheme = alpha *( alpha | digit | "+" | "-" | "." ) /// hier_part = ( net_path | abs_path ) [ "?" query ] /// opaque_part = uric_no_slash *uric /// net_path = "//" authority [ abs_path ] /// abs_path = "/" path_segments /// query = *uric /// uric_no_slash = unreserved | escaped | ";" | "?" | ":" | "@" | "&amp;" | "=" | "+" | "$" | "," /// uric = reserved | unreserved | escaped /// authority = server | reg_name /// path_segments = segment *( "/" segment ) /// unreserved = alphanum | mark /// escaped = "%" hex hex /// reserved = ";" | "/" | "?" | ":" | "@" | "&amp;" | "=" | "+" | "$" | "," /// server = [ [ userinfo "@" ] hostport ] /// reg_name = 1*( unreserved | escaped | "$" | "," | ";" | ":" | "@" | "&amp;" | "=" | "+" ) /// segment = *pchar *( ";" param ) /// mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")" /// userinfo = *( unreserved | escaped | ";" | ":" | "&amp;" | "=" | "+" | "$" | "," ) /// hostport = host [ ":" port ] /// pchar = unreserved | escaped | ":" | "@" | "&amp;" | "=" | "+" | "$" | "," /// param = *pchar /// host = hostname | IPv4address /// port = *digit /// hostname = *( domainlabel "." ) toplabel [ "." ] /// IPv4address = 1*digit "." 1*digit "." 1*digit "." 1*digit /// domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum /// toplabel = alpha | alpha *( alphanum | "-" ) alphanum /// alphanum = alpha | digit /// alpha = lowalpha | upalpha /// lowalpha = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j" | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" | "s" | "t" | "u" | "v" | /// "w" | "x" | "y" | "z" /// upalpha = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" | "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" | "S" | "T" | "U" | "V" | /// "W" | "X" | "Y" | "Z" /// digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" /// /// request-header = Accept /// | Accept-Charset /// | Accept-Encoding /// | Accept-Language /// | Authorization /// | Expect /// | From /// | Host /// | If-Match /// | If-Modified-Since /// | If-None-Match /// | If-Range /// | If-Unmodified-Since /// | Max-Forwards /// | Proxy-Authorization /// | Range /// | Referer /// | TE /// | User-Agent /// </pre> /// /// Response: /// <pre> /// Response = Status-Line /// *(( general-header /// | response-header /// | entity-header ) CRLF) /// CRLF /// [ message-body ] /// /// Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF /// /// Status-Code = "100" /// | "101" /// | "200" /// | "201" /// | "202" /// | "203" /// | "204" /// | "205" /// | "206" /// | "300" /// | "301" /// | "302" /// | "303" /// | "304" /// | "305" /// | "307" /// | "400" /// | "401" /// | "402" /// | "403" /// | "404" /// | "405" /// | "406" /// | "407" /// | "408" /// | "409" /// | "410" /// | "411" /// | "412" /// | "413" /// | "414" /// | "415" /// | "416" /// | "417" /// | "500" /// | "501" /// | "502" /// | "503" /// | "504" /// | "505" /// | extension-code /// /// extension-code = 3DIGIT /// Reason-Phrase = *&lt;TEXT, excluding CR, LF> /// /// response-header = Accept-Ranges /// | Age /// | ETag /// | Location /// | Proxy-Authenticate /// | Retry-After /// | Server /// | Vary /// | WWW-Authenticate /// /// entity-header = Allow /// | Content-Encoding /// | Content-Language /// | Content-Length /// | Content-Location /// | Content-MD5 /// | Content-Range /// | Content-Type /// | Expires /// | Last-Modified /// | extension-header /// /// extension-header = message-header /// /// entity-body = *OCTET /// /// entity-body := Content-Encoding( Content-Type( data ) ) /// </pre> /// </summary> public abstract class HttpDatagram : Datagram { internal class ParseInfoBase { public int Length { get; set; } public HttpVersion Version { get; set; } public HttpHeader Header { get; set; } public Datagram Body { get; set; } } /// <summary> /// True iff the message is a request and iff the message is not a response. /// </summary> public abstract bool IsRequest { get; } /// <summary> /// True iff the message is a response and iff the message is not a request. /// </summary> public bool IsResponse { get { return !IsRequest; } } /// <summary> /// The version of this HTTP message. /// </summary> public HttpVersion Version { get; private set;} /// <summary> /// The header of the HTTP message. /// </summary> public HttpHeader Header { get; private set;} /// <summary> /// Message Body. /// </summary> public Datagram Body { get; private set; } internal static HttpDatagram CreateDatagram(byte[] buffer, int offset, int length) { if (length >= _httpSlash.Length && buffer.SequenceEqual(offset, _httpSlash, 0, _httpSlash.Length)) return new HttpResponseDatagram(buffer, offset, length); return new HttpRequestDatagram(buffer, offset, length); } internal HttpDatagram(byte[] buffer, int offset, int length, HttpVersion version, HttpHeader header, Datagram body) : base(buffer, offset, length) { Version = version; Header = header; Body = body; } internal static Datagram ParseBody(byte[] buffer, int offset, int length, bool isBodyPossible, HttpHeader header) { if (!isBodyPossible) return Empty; HttpTransferEncodingField transferEncodingField = header.TransferEncoding; if (transferEncodingField != null && transferEncodingField.TransferCodings != null && transferEncodingField.TransferCodings.Any(coding => coding != "identity")) { return ParseChunkedBody(buffer, offset, length); } HttpContentLengthField contentLengthField = header.ContentLength; if (contentLengthField != null) { uint? contentLength = contentLengthField.ContentLength; if (contentLength != null) return new Datagram(buffer, offset, Math.Min((int)contentLength.Value, length)); } HttpContentTypeField contentTypeField = header.ContentType; if (contentTypeField != null) { if (contentTypeField.MediaType == "multipart" && contentTypeField.MediaSubtype == "byteranges") { string boundary = contentTypeField.Parameters["boundary"]; if (boundary != null) { byte[] lastBoundaryBuffer = Encoding.ASCII.GetBytes(string.Format(CultureInfo.InvariantCulture, "\r\n--{0}--", boundary)); int lastBoundaryOffset = buffer.Find(offset, length, lastBoundaryBuffer); int lastBoundaryEnd = lastBoundaryOffset + lastBoundaryBuffer.Length; return new Datagram(buffer, offset, Math.Min(lastBoundaryEnd - offset, length)); } } } return new Datagram(buffer, offset, length); } private static Datagram ParseChunkedBody(byte[] buffer, int offset, int length) { List<Datagram> contentData = new List<Datagram>(); HttpParser parser = new HttpParser(buffer, offset, length); uint? chunkSize; while (parser.HexadecimalNumber(out chunkSize).SkipChunkExtensions().CarriageReturnLineFeed().Success) { uint chunkSizeValue = chunkSize.Value; if (chunkSizeValue == 0) { int? endOffset; GetHeaderFields(out endOffset, buffer, parser.Offset, offset + length - parser.Offset); if (endOffset != null) parser.Skip(endOffset.Value - parser.Offset); break; } int actualChunkSize = (int)Math.Min(chunkSizeValue, offset + length - parser.Offset); contentData.Add(new Datagram(buffer, parser.Offset, actualChunkSize)); parser.Skip(actualChunkSize); parser.CarriageReturnLineFeed(); } int contentLength = contentData.Sum(datagram => datagram.Length); byte[] contentBuffer = new byte[contentLength]; int contentBufferOffset = 0; foreach (Datagram datagram in contentData) { datagram.Write(contentBuffer, contentBufferOffset); contentBufferOffset += datagram.Length; } return new Datagram(buffer, offset, parser.Offset - offset); } internal static List<KeyValuePair<string, IEnumerable<byte>>> GetHeaderFields(out int? endOffset, byte[] buffer, int offset, int length) { endOffset = null; var headerFields = new List<KeyValuePair<string, IEnumerable<byte>>>(); HttpParser parser = new HttpParser(buffer, offset, length); while (parser.Success) { if (parser.IsCarriageReturnLineFeed()) { endOffset = parser.Offset + 2; break; } string fieldName; IEnumerable<byte> fieldValue; parser.Token(out fieldName).Colon().FieldValue(out fieldValue).CarriageReturnLineFeed(); if (parser.Success) headerFields.Add(new KeyValuePair<string, IEnumerable<byte>>(fieldName, fieldValue)); } return headerFields; } private static readonly byte[] _httpSlash = Encoding.ASCII.GetBytes("HTTP/"); } }
using ParadoxCraft.Terrain; using ParadoxCraft.Blocks; using SiliconStudio.Core.Mathematics; using SiliconStudio.Paradox; using SiliconStudio.Paradox.Effects; using SiliconStudio.Paradox.Graphics; using SiliconStudio.Paradox.Input; using SiliconStudio.Paradox.EntityModel; using SiliconStudio.Paradox.Engine; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SiliconStudio.Paradox.DataModel; using ParadoxCraft.Blocks.Chunks; using ParadoxCraft.Helpers; using SiliconStudio.Paradox.Effects.ShadowMaps; using SiliconStudio.Paradox.Effects.Renderers; using SiliconStudio.Paradox.Effects.Processors; namespace ParadoxCraft { /// <summary> /// Main game instance /// </summary> public class ParadoxCraftGame : Game { #region Variables /// <summary> /// Bool to switch wireframe mode /// </summary> private bool isWireframe = false; /// <summary> /// Player camera entity /// </summary> private Entity Camera { get; set; } /// <summary> /// Terrain entity /// </summary> private GraphicalTerrain Terrain { get; set; } /// <summary> /// Player movement helper /// </summary> private Movement PlayerMovement { get; set; } /// <summary> /// Chunk handling factory /// </summary> public ChunkFactory Factory { get; private set; } /// <summary> /// The player its cursor /// </summary> public PrimitiveRender Cursor { get; set; } /// <summary> /// Component for the sunlight /// </summary> private LightComponent Sunlight { get; set; } /// <summary> /// Component#1 for the background lighting /// </summary> private LightComponent EnviromentLight1 { get; set; } /// <summary> /// Component#2 for the background lighting /// </summary> private LightComponent EnviromentLight2 { get; set; } /// <summary> /// Atmosphere handler for the sunlight /// </summary> private AtmosphereData Atmosphere { get; set; } #endregion #region Initialization /// <summary> /// Creates a new instance of <see cref="ParadoxCraftGame"/> /// </summary> public ParadoxCraftGame() { // Target 11.0 profile by default GraphicsDeviceManager.PreferredGraphicsProfile = new[] { GraphicsProfile.Level_11_0 }; Factory = new ChunkFactory(); } /// <summary> /// Loads the game content /// </summary> protected override async Task LoadContent() { await base.LoadContent(); // Hides the mouse IsMouseVisible = false; // Set fog values GraphicsDevice.Parameters.Set(FogEffectKeys.fogNearPlaneZ, 100f); GraphicsDevice.Parameters.Set(FogEffectKeys.fogFarPlaneZ, 160f); // Create the Atmosphere lighting Atmosphere = AtmosphereBuilder.Generate(GraphicsDevice, EffectSystem); CreateSunLight(); // Lights EnviromentLight1 = CreateDirectLight(new Vector3(-1, -1, -1), new Color3(1, 1, 1), .3f); EnviromentLight2 = CreateDirectLight(new Vector3(1, 1, 1), new Color3(1, 1, 1), .3f); // Create the pipeline CreatePipeline(); CreateCursor(); // Entities LoadTerrain(); LoadCamera(); // Scripts Script.Add(MovementScript); Script.Add(RenderChunksScript); Script.Add(BuildTerrain); Script.Add(LightCycleScript); } /// <summary> /// Creates the rendering pipeline /// </summary> private void CreatePipeline() { var renderers = RenderSystem.Pipeline.Renderers; var width = GraphicsDevice.BackBuffer.Width; var height = GraphicsDevice.BackBuffer.Height; var viewport = new Viewport(0, 0, width, height); var clearColor = Color.Black; var effectName = "ParadoxCraftEffectMain"; var fowardEffectName = "ParadoxCraftEffectForward"; var prepassEffectName = "ParadoxCraftPrepassEffect"; // Adds a light processor that will track all the entities that have a light component. // This will also handle the shadows (allocation, activation etc.). var lightProcessor = Entities.GetProcessor<LightShadowProcessor>(); if (lightProcessor == null) Entities.Processors.Add(new DynamicLightShadowProcessor(GraphicsDevice, false)); // Camera renderers.Add(new CameraSetter(Services)); // Create G-buffer pass var gbufferPipeline = new RenderPipeline("GBuffer"); // Renders the G-buffer for opaque geometry. gbufferPipeline.Renderers.Add(new ModelRenderer(Services, effectName + ".ParadoxGBufferShaderPass").AddOpaqueFilter()); var gbufferProcessor = new GBufferRenderProcessor(Services, gbufferPipeline, GraphicsDevice.DepthStencilBuffer, false); // Add sthe G-buffer pass to the pipeline. renderers.Add(gbufferProcessor); // Performs the light prepass on opaque geometry. // Adds this pass to the pipeline. var lightDeferredProcessor = new LightingPrepassRenderer(Services, prepassEffectName, GraphicsDevice.DepthStencilBuffer, gbufferProcessor.GBufferTexture); renderers.Add(lightDeferredProcessor); renderers.Add(new RenderTargetSetter(Services) { ClearColor = clearColor, EnableClearDepth = false, RenderTarget = GraphicsDevice.BackBuffer, DepthStencil = GraphicsDevice.DepthStencilBuffer, Viewport = viewport }); renderers.Add(new RenderStateSetter(Services) { DepthStencilState = GraphicsDevice.DepthStencilStates.Default, RasterizerState = GraphicsDevice.RasterizerStates.CullBack }); // Renders all the meshes with the correct lighting. renderers.Add(new ModelRenderer(Services, fowardEffectName).AddLightForwardSupport()); // Blend atmoshpere inscatter on top renderers.Add(new AtmosphereRenderer(Services, Atmosphere, Sunlight)); // Wireframe mode if (isWireframe) GraphicsDevice.Parameters.Set(Effect.RasterizerStateKey, RasterizerState.New(GraphicsDevice, new RasterizerStateDescription(CullMode.None) { FillMode = FillMode.Wireframe })); GraphicsDevice.Parameters.Set(RenderingParameters.UseDeferred, true); } /// <summary> /// Creates the entity for the player camera /// </summary> private void LoadCamera() { // Initialize player (camera) var campos = new Vector3(0, 0, 0); Camera = new Entity(campos) { new CameraComponent(null, .1f, 18 * 2 * 16) { VerticalFieldOfView = 1.5f, TargetUp = Vector3.UnitY }, }; PlayerMovement = new Movement(Camera); RenderSystem.Pipeline.SetCamera(Camera.Get<CameraComponent>()); Entities.Add(Camera); } /// <summary> /// Creates the entity for the terrain /// </summary> private void LoadTerrain() { Terrain = new GraphicalTerrain(GraphicsDevice, Asset.Load<Material>("Materials/Terrain")); Factory.Terrain = Terrain; Entities.Add(Terrain); } private void CreateCursor() { // Initialize the cursor float res = (float)Window.ClientBounds.Width / Window.ClientBounds.Height; Cursor = new PrimitiveRender { DrawEffect = new SimpleEffect(GraphicsDevice) { Color = Color.White }, Primitives = new[] { GeometricPrimitive.Plane.New(GraphicsDevice, .06f / res, .01f), GeometricPrimitive.Plane.New(GraphicsDevice, .01f / res, .06f) } }; // Cursor render RenderSystem.Pipeline.Renderers.Add(new DelegateRenderer(Services) { Render = RenderCursor }); } /// <summary> /// Renders the cursor /// </summary> private void RenderCursor(RenderContext renderContext) { Cursor.DrawEffect.Apply(); foreach (var primitive in Cursor.Primitives) primitive.Draw(); } #endregion #region Scripts /// <summary> /// Script for tracking key inputs to move the player /// </summary> private async Task MovementScript() { float dragX = 0f, dragY = 0f; double time = UpdateTime.Total.TotalSeconds; Input.ResetMousePosition(); while (IsRunning) { await Script.NextFrame(); //Else the player slows down on a lower framerate var diff = UpdateTime.Total.TotalSeconds - time; time = UpdateTime.Total.TotalSeconds; if (Input.IsKeyDown(Keys.W)) PlayerMovement.Add(Direction.Foward); if (Input.IsKeyDown(Keys.S)) PlayerMovement.Add(Direction.Back); if (Input.IsKeyDown(Keys.A)) PlayerMovement.Add(Direction.Left); if (Input.IsKeyDown(Keys.D)) PlayerMovement.Add(Direction.Right); if (Input.IsKeyDown(Keys.Q)) PlayerMovement.Add(Direction.Up); if (Input.IsKeyDown(Keys.E)) PlayerMovement.Add(Direction.Down); PlayerMovement.Move(diff); //Move the 'camera' dragX *= .01f; dragY *= .01f; dragX += (Input.MousePosition.X - .5f) * .3f; dragY += (Input.MousePosition.Y - .5f) * .3f; if (Input.ResetMousePosition()) PlayerMovement.YawPitch(dragX, dragY); } } /// <summary> /// Script for checking chunks that should be rendered /// </summary> private async Task RenderChunksScript() { while (IsRunning) { double playerX = PlayerMovement.X; double playerZ = PlayerMovement.Z; //playerX += StartPosition.X; //playerZ += StartPosition.Z; playerX /= Constants.ChunkSize; playerZ /= Constants.ChunkSize; // TODO: handle y for (int i = 0; i < Constants.DrawRadius * Constants.DrawRadius; i++) { int x = i % Constants.DrawRadius; int z = (i - x) / Constants.DrawRadius; if ((x * x) + (z * z) > (Constants.DrawRadius * Constants.DrawRadius)) continue; Factory.CheckLoad(playerX + x, -1, playerZ + z); Factory.CheckLoad(playerX - x, -1, playerZ + z); Factory.CheckLoad(playerX + x, -1, playerZ - z); Factory.CheckLoad(playerX - x, -1, playerZ - z); Factory.CheckLoad(playerX + x, 0, playerZ + z); Factory.CheckLoad(playerX - x, 0, playerZ + z); Factory.CheckLoad(playerX + x, 0, playerZ - z); Factory.CheckLoad(playerX - x, 0, playerZ - z); Factory.CheckLoad(playerX + x, 1, playerZ + z); Factory.CheckLoad(playerX - x, 1, playerZ + z); Factory.CheckLoad(playerX + x, 1, playerZ - z); Factory.CheckLoad(playerX - x, 1, playerZ - z); Factory.CheckLoad(playerX + x, 2, playerZ + z); Factory.CheckLoad(playerX - x, 2, playerZ + z); Factory.CheckLoad(playerX + x, 2, playerZ - z); Factory.CheckLoad(playerX - x, 2, playerZ - z); Factory.CheckLoad(playerX + x, 3, playerZ + z); Factory.CheckLoad(playerX - x, 3, playerZ + z); Factory.CheckLoad(playerX + x, 3, playerZ - z); Factory.CheckLoad(playerX - x, 3, playerZ - z); if (i % Constants.DrawRadius == 0) await Task.Delay(100); } } } /// <summary> /// Checks and re-builds the terrain /// </summary> private async Task BuildTerrain() { while (IsRunning) { double playerX = PlayerMovement.X; double playerZ = PlayerMovement.Z; //playerX += StartPosition.X; //playerZ += StartPosition.Z; playerX /= Constants.ChunkSize; playerZ /= Constants.ChunkSize; // TODO: handle y Factory.PurgeDistancedChunks(playerX, 0, playerZ, Constants.DrawRadius + 1); Terrain.Build(); await Task.Delay(100); } } /// <summary> /// Script for the "Day/Night Cycle" /// </summary> private async Task LightCycleScript() { float sunlightIntensity = Sunlight.Intensity, lightIntensity = EnviromentLight1.Intensity, sunZenith = MathUtil.RevolutionsToRadians(0.2f), intensityPercentage = 1f, realAngle; double time; while (IsRunning) { await Task.Delay(500); time = UpdateTime.Total.TotalSeconds; float curAngle = (float)time / (Constants.DayNightCycle / 360f); float angle = curAngle / Constants.Degrees90 / 90; angle %= Constants.Degrees90 * 4; if (angle > 0 && angle < Constants.Degrees90 * 2) { //Day realAngle = angle * (180 / (float)Math.PI); if (realAngle < 20) intensityPercentage = realAngle * .05f; if (realAngle > 160) intensityPercentage = (180 - realAngle) * .05f; Sunlight.Intensity = sunlightIntensity + (.1f * intensityPercentage); EnviromentLight1.Intensity = lightIntensity + (.1f * intensityPercentage); EnviromentLight2.Intensity = lightIntensity + (.1f * intensityPercentage); float height = (float)Math.Sin(angle); float width = (float)Math.Cos(angle); Sunlight.Color = new Color3(1f, .4f + (.6f * height), .2f + height * .8f); } sunZenith = MathUtil.Mod2PI(angle - Constants.Degrees90); Sunlight.LightDirection = new Vector3((float)Math.Sin(sunZenith), -(float)Math.Cos(sunZenith), 0); } } #endregion #region Lights /// <summary> /// Creates a light entity based on the deferred lightning example /// </summary> /// <param name="direction">Light direction</param> /// <param name="color">Light color</param> /// <param name="intensity">Light intensity</param> private LightComponent CreateDirectLight(Vector3 direction, Color3 color, float intensity) { var directLightEntity = new Entity(); LightComponent directLightComponent = new LightComponent { Type = LightType.Directional, Color = color, Deferred = false, Enabled = true, Intensity = intensity, LightDirection = direction }; directLightEntity.Add(directLightComponent); Entities.Add(directLightEntity); return directLightComponent; } private void CreateSunLight() { // create the lights var directLightEntity = new Entity(); Sunlight = new LightComponent { Type = LightType.Directional, Color = new Color3(1, 1, 1), Deferred = false, Enabled = true, Intensity = .2f, LightDirection = new Vector3(0) }; directLightEntity.Add(Sunlight); Entities.Add(directLightEntity); } #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.Xml; using System.Xml.Schema; using System.Reflection; using System.Reflection.Emit; using System.Collections; using System.Collections.Generic; using System.Security; #if NET_NATIVE using Internal.Runtime.Augments; #endif namespace System.Runtime.Serialization { #if USE_REFEMIT || NET_NATIVE public delegate object XmlFormatClassReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces); public delegate object XmlFormatCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, CollectionDataContract collectionContract); public delegate void XmlFormatGetOnlyCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, CollectionDataContract collectionContract); public sealed class XmlFormatReaderGenerator #else internal delegate object XmlFormatClassReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces); internal delegate object XmlFormatCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, CollectionDataContract collectionContract); internal delegate void XmlFormatGetOnlyCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, CollectionDataContract collectionContract); internal sealed class XmlFormatReaderGenerator #endif { private static readonly Func<Type, object> s_getUninitializedObjectDelegate = (Func<Type, object>) typeof(string) .GetTypeInfo() .Assembly .GetType("System.Runtime.Serialization.FormatterServices") ?.GetMethod("GetUninitializedObject", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static) ?.CreateDelegate(typeof(Func<Type, object>)); private static readonly Dictionary<Type, bool> s_typeHasDefaultConstructorMap = new Dictionary<Type, bool>(); #if !NET_NATIVE [SecurityCritical] /// <SecurityNote> /// Critical - holds instance of CriticalHelper which keeps state that was produced within an assert /// </SecurityNote> private CriticalHelper _helper; /// <SecurityNote> /// Critical - initializes SecurityCritical field 'helper' /// </SecurityNote> [SecurityCritical] public XmlFormatReaderGenerator() { _helper = new CriticalHelper(); } /// <SecurityNote> /// Critical - accesses SecurityCritical helper class 'CriticalHelper' /// </SecurityNote> [SecurityCritical] public XmlFormatClassReaderDelegate GenerateClassReader(ClassDataContract classContract) { return _helper.GenerateClassReader(classContract); } /// <SecurityNote> /// Critical - accesses SecurityCritical helper class 'CriticalHelper' /// </SecurityNote> [SecurityCritical] public XmlFormatCollectionReaderDelegate GenerateCollectionReader(CollectionDataContract collectionContract) { return _helper.GenerateCollectionReader(collectionContract); } /// <SecurityNote> /// Critical - accesses SecurityCritical helper class 'CriticalHelper' /// </SecurityNote> [SecurityCritical] public XmlFormatGetOnlyCollectionReaderDelegate GenerateGetOnlyCollectionReader(CollectionDataContract collectionContract) { return _helper.GenerateGetOnlyCollectionReader(collectionContract); } /// <SecurityNote> /// Review - handles all aspects of IL generation including initializing the DynamicMethod. /// changes to how IL generated could affect how data is deserialized and what gets access to data, /// therefore we mark it for review so that changes to generation logic are reviewed. /// </SecurityNote> private class CriticalHelper { private CodeGenerator _ilg; private LocalBuilder _objectLocal; private Type _objectType; private ArgBuilder _xmlReaderArg; private ArgBuilder _contextArg; private ArgBuilder _memberNamesArg; private ArgBuilder _memberNamespacesArg; private ArgBuilder _collectionContractArg; private bool _useReflection = true; public XmlFormatClassReaderDelegate GenerateClassReader(ClassDataContract classContract) { if (_useReflection) { return new ReflectionXmlFormatReader(classContract).ReflectionReadClass; } else { _ilg = new CodeGenerator(); bool memberAccessFlag = classContract.RequiresMemberAccessForRead(null); try { _ilg.BeginMethod("Read" + classContract.StableName.Name + "FromXml", Globals.TypeOfXmlFormatClassReaderDelegate, memberAccessFlag); } catch (SecurityException securityException) { if (memberAccessFlag) { classContract.RequiresMemberAccessForRead(securityException); } else { throw; } } InitArgs(); CreateObject(classContract); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, _objectLocal); InvokeOnDeserializing(classContract); LocalBuilder objectId = null; ReadClass(classContract); InvokeOnDeserialized(classContract); if (objectId == null) { _ilg.Load(_objectLocal); // Do a conversion back from DateTimeOffsetAdapter to DateTimeOffset after deserialization. // DateTimeOffsetAdapter is used here for deserialization purposes to bypass the ISerializable implementation // on DateTimeOffset; which does not work in partial trust. if (classContract.UnderlyingType == Globals.TypeOfDateTimeOffsetAdapter) { _ilg.ConvertValue(_objectLocal.LocalType, Globals.TypeOfDateTimeOffsetAdapter); _ilg.Call(XmlFormatGeneratorStatics.GetDateTimeOffsetMethod); _ilg.ConvertValue(Globals.TypeOfDateTimeOffset, _ilg.CurrentMethod.ReturnType); } //Copy the KeyValuePairAdapter<K,T> to a KeyValuePair<K,T>. else if (classContract.IsKeyValuePairAdapter) { _ilg.Call(classContract.GetKeyValuePairMethodInfo); _ilg.ConvertValue(Globals.TypeOfKeyValuePair.MakeGenericType(classContract.KeyValuePairGenericArguments), _ilg.CurrentMethod.ReturnType); } else { _ilg.ConvertValue(_objectLocal.LocalType, _ilg.CurrentMethod.ReturnType); } } return (XmlFormatClassReaderDelegate)_ilg.EndMethod(); } } public XmlFormatCollectionReaderDelegate GenerateCollectionReader(CollectionDataContract collectionContract) { if (_useReflection) { return new ReflectionXmlFormatReader(collectionContract).ReflectionReadCollection; } else { _ilg = GenerateCollectionReaderHelper(collectionContract, false /*isGetOnlyCollection*/); ReadCollection(collectionContract); _ilg.Load(_objectLocal); _ilg.ConvertValue(_objectLocal.LocalType, _ilg.CurrentMethod.ReturnType); return (XmlFormatCollectionReaderDelegate)_ilg.EndMethod(); } } public XmlFormatGetOnlyCollectionReaderDelegate GenerateGetOnlyCollectionReader(CollectionDataContract collectionContract) { if (_useReflection) { return new ReflectionXmlFormatReader(collectionContract).ReflectionReadGetOnlyCollection; } else { _ilg = GenerateCollectionReaderHelper(collectionContract, true /*isGetOnlyCollection*/); ReadGetOnlyCollection(collectionContract); return (XmlFormatGetOnlyCollectionReaderDelegate)_ilg.EndMethod(); } } private CodeGenerator GenerateCollectionReaderHelper(CollectionDataContract collectionContract, bool isGetOnlyCollection) { _ilg = new CodeGenerator(); bool memberAccessFlag = collectionContract.RequiresMemberAccessForRead(null); try { if (isGetOnlyCollection) { _ilg.BeginMethod("Read" + collectionContract.StableName.Name + "FromXml" + "IsGetOnly", Globals.TypeOfXmlFormatGetOnlyCollectionReaderDelegate, memberAccessFlag); } else { _ilg.BeginMethod("Read" + collectionContract.StableName.Name + "FromXml" + string.Empty, Globals.TypeOfXmlFormatCollectionReaderDelegate, memberAccessFlag); } } catch (SecurityException securityException) { if (memberAccessFlag) { collectionContract.RequiresMemberAccessForRead(securityException); } else { throw; } } InitArgs(); _collectionContractArg = _ilg.GetArg(4); return _ilg; } private void InitArgs() { _xmlReaderArg = _ilg.GetArg(0); _contextArg = _ilg.GetArg(1); _memberNamesArg = _ilg.GetArg(2); _memberNamespacesArg = _ilg.GetArg(3); } private void CreateObject(ClassDataContract classContract) { Type type = _objectType = classContract.UnderlyingType; if (type.GetTypeInfo().IsValueType && !classContract.IsNonAttributedType) type = Globals.TypeOfValueType; _objectLocal = _ilg.DeclareLocal(type, "objectDeserialized"); if (classContract.UnderlyingType == Globals.TypeOfDBNull) { _ilg.LoadMember(Globals.TypeOfDBNull.GetField("Value")); _ilg.Stloc(_objectLocal); } else if (classContract.IsNonAttributedType) { if (type.GetTypeInfo().IsValueType) { _ilg.Ldloca(_objectLocal); _ilg.InitObj(type); } else { _ilg.New(classContract.GetNonAttributedTypeConstructor()); _ilg.Stloc(_objectLocal); } } else { _ilg.Call(null, XmlFormatGeneratorStatics.GetUninitializedObjectMethod, DataContract.GetIdForInitialization(classContract)); _ilg.ConvertValue(Globals.TypeOfObject, type); _ilg.Stloc(_objectLocal); } } private void InvokeOnDeserializing(ClassDataContract classContract) { if (classContract.BaseContract != null) InvokeOnDeserializing(classContract.BaseContract); if (classContract.OnDeserializing != null) { _ilg.LoadAddress(_objectLocal); _ilg.ConvertAddress(_objectLocal.LocalType, _objectType); _ilg.Load(_contextArg); _ilg.LoadMember(XmlFormatGeneratorStatics.GetStreamingContextMethod); _ilg.Call(classContract.OnDeserializing); } } private void InvokeOnDeserialized(ClassDataContract classContract) { if (classContract.BaseContract != null) InvokeOnDeserialized(classContract.BaseContract); if (classContract.OnDeserialized != null) { _ilg.LoadAddress(_objectLocal); _ilg.ConvertAddress(_objectLocal.LocalType, _objectType); _ilg.Load(_contextArg); _ilg.LoadMember(XmlFormatGeneratorStatics.GetStreamingContextMethod); _ilg.Call(classContract.OnDeserialized); } } private void ReadClass(ClassDataContract classContract) { ReadMembers(classContract, null /*extensionDataLocal*/); } private void ReadMembers(ClassDataContract classContract, LocalBuilder extensionDataLocal) { int memberCount = classContract.MemberNames.Length; _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, memberCount); LocalBuilder memberIndexLocal = _ilg.DeclareLocal(Globals.TypeOfInt, "memberIndex", -1); int firstRequiredMember; bool[] requiredMembers = GetRequiredMembers(classContract, out firstRequiredMember); bool hasRequiredMembers = (firstRequiredMember < memberCount); LocalBuilder requiredIndexLocal = hasRequiredMembers ? _ilg.DeclareLocal(Globals.TypeOfInt, "requiredIndex", firstRequiredMember) : null; object forReadElements = _ilg.For(null, null, null); _ilg.Call(null, XmlFormatGeneratorStatics.MoveToNextElementMethod, _xmlReaderArg); _ilg.IfFalseBreak(forReadElements); if (hasRequiredMembers) _ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetMemberIndexWithRequiredMembersMethod, _xmlReaderArg, _memberNamesArg, _memberNamespacesArg, memberIndexLocal, requiredIndexLocal, extensionDataLocal); else _ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetMemberIndexMethod, _xmlReaderArg, _memberNamesArg, _memberNamespacesArg, memberIndexLocal, extensionDataLocal); Label[] memberLabels = _ilg.Switch(memberCount); ReadMembers(classContract, requiredMembers, memberLabels, memberIndexLocal, requiredIndexLocal); _ilg.EndSwitch(); _ilg.EndFor(); if (hasRequiredMembers) { _ilg.If(requiredIndexLocal, Cmp.LessThan, memberCount); _ilg.Call(null, XmlFormatGeneratorStatics.ThrowRequiredMemberMissingExceptionMethod, _xmlReaderArg, memberIndexLocal, requiredIndexLocal, _memberNamesArg); _ilg.EndIf(); } } private int ReadMembers(ClassDataContract classContract, bool[] requiredMembers, Label[] memberLabels, LocalBuilder memberIndexLocal, LocalBuilder requiredIndexLocal) { int memberCount = (classContract.BaseContract == null) ? 0 : ReadMembers(classContract.BaseContract, requiredMembers, memberLabels, memberIndexLocal, requiredIndexLocal); for (int i = 0; i < classContract.Members.Count; i++, memberCount++) { DataMember dataMember = classContract.Members[i]; Type memberType = dataMember.MemberType; _ilg.Case(memberLabels[memberCount], dataMember.Name); if (dataMember.IsRequired) { int nextRequiredIndex = memberCount + 1; for (; nextRequiredIndex < requiredMembers.Length; nextRequiredIndex++) if (requiredMembers[nextRequiredIndex]) break; _ilg.Set(requiredIndexLocal, nextRequiredIndex); } LocalBuilder value = null; if (dataMember.IsGetOnlyCollection) { _ilg.LoadAddress(_objectLocal); _ilg.LoadMember(dataMember.MemberInfo); value = _ilg.DeclareLocal(memberType, dataMember.Name + "Value"); _ilg.Stloc(value); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.StoreCollectionMemberInfoMethod, value); ReadValue(memberType, dataMember.Name, classContract.StableName.Namespace); } else { value = ReadValue(memberType, dataMember.Name, classContract.StableName.Namespace); _ilg.LoadAddress(_objectLocal); _ilg.ConvertAddress(_objectLocal.LocalType, _objectType); _ilg.Ldloc(value); _ilg.StoreMember(dataMember.MemberInfo); } #if FEATURE_LEGACYNETCF // The DataContractSerializer in the full framework doesn't support unordered elements: // deserialization will fail if the data members in the XML are not sorted alphabetically. // But the NetCF DataContractSerializer does support unordered element. To maintain compatibility // with Mango we always search for the member from the beginning of the member list. // We set memberIndexLocal to -1 because GetMemberIndex always starts from memberIndex+1. if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) ilg.Set(memberIndexLocal, (int)-1); else #endif // FEATURE_LEGACYNETCF _ilg.Set(memberIndexLocal, memberCount); _ilg.EndCase(); } return memberCount; } private bool[] GetRequiredMembers(ClassDataContract contract, out int firstRequiredMember) { int memberCount = contract.MemberNames.Length; bool[] requiredMembers = new bool[memberCount]; GetRequiredMembers(contract, requiredMembers); for (firstRequiredMember = 0; firstRequiredMember < memberCount; firstRequiredMember++) if (requiredMembers[firstRequiredMember]) break; return requiredMembers; } private int GetRequiredMembers(ClassDataContract contract, bool[] requiredMembers) { int memberCount = (contract.BaseContract == null) ? 0 : GetRequiredMembers(contract.BaseContract, requiredMembers); List<DataMember> members = contract.Members; for (int i = 0; i < members.Count; i++, memberCount++) { requiredMembers[memberCount] = members[i].IsRequired; } return memberCount; } private LocalBuilder ReadValue(Type type, string name, string ns) { LocalBuilder value = _ilg.DeclareLocal(type, "valueRead"); LocalBuilder nullableValue = null; int nullables = 0; while (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable) { nullables++; type = type.GetGenericArguments()[0]; } PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type); if ((primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) || nullables != 0 || type.GetTypeInfo().IsValueType) { LocalBuilder objectId = _ilg.DeclareLocal(Globals.TypeOfString, "objectIdRead"); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.ReadAttributesMethod, _xmlReaderArg); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.ReadIfNullOrRefMethod, _xmlReaderArg, type, DataContract.IsTypeSerializable(type)); _ilg.Stloc(objectId); // Deserialize null _ilg.If(objectId, Cmp.EqualTo, Globals.NullObjectId); if (nullables != 0) { _ilg.LoadAddress(value); _ilg.InitObj(value.LocalType); } else if (type.GetTypeInfo().IsValueType) ThrowValidationException(SR.Format(SR.ValueTypeCannotBeNull, DataContract.GetClrTypeFullName(type))); else { _ilg.Load(null); _ilg.Stloc(value); } // Deserialize value // Compare against Globals.NewObjectId, which is set to string.Empty _ilg.ElseIfIsEmptyString(objectId); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetObjectIdMethod); _ilg.Stloc(objectId); if (type.GetTypeInfo().IsValueType) { _ilg.IfNotIsEmptyString(objectId); ThrowValidationException(SR.Format(SR.ValueTypeCannotHaveId, DataContract.GetClrTypeFullName(type))); _ilg.EndIf(); } if (nullables != 0) { nullableValue = value; value = _ilg.DeclareLocal(type, "innerValueRead"); } if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) { _ilg.Call(_xmlReaderArg, primitiveContract.XmlFormatReaderMethod); _ilg.Stloc(value); if (!type.GetTypeInfo().IsValueType) _ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, value); } else { InternalDeserialize(value, type, name, ns); } // Deserialize ref _ilg.Else(); if (type.GetTypeInfo().IsValueType) ThrowValidationException(SR.Format(SR.ValueTypeCannotHaveRef, DataContract.GetClrTypeFullName(type))); else { _ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetExistingObjectMethod, objectId, type, name, ns); _ilg.ConvertValue(Globals.TypeOfObject, type); _ilg.Stloc(value); } _ilg.EndIf(); if (nullableValue != null) { _ilg.If(objectId, Cmp.NotEqualTo, Globals.NullObjectId); WrapNullableObject(value, nullableValue, nullables); _ilg.EndIf(); value = nullableValue; } } else { InternalDeserialize(value, type, name, ns); } return value; } private void InternalDeserialize(LocalBuilder value, Type type, string name, string ns) { _ilg.Load(_contextArg); _ilg.Load(_xmlReaderArg); Type declaredType = type; _ilg.Load(DataContract.GetId(declaredType.TypeHandle)); _ilg.Ldtoken(declaredType); _ilg.Load(name); _ilg.Load(ns); _ilg.Call(XmlFormatGeneratorStatics.InternalDeserializeMethod); _ilg.ConvertValue(Globals.TypeOfObject, type); _ilg.Stloc(value); } private void WrapNullableObject(LocalBuilder innerValue, LocalBuilder outerValue, int nullables) { Type innerType = innerValue.LocalType, outerType = outerValue.LocalType; _ilg.LoadAddress(outerValue); _ilg.Load(innerValue); for (int i = 1; i < nullables; i++) { Type type = Globals.TypeOfNullable.MakeGenericType(innerType); _ilg.New(type.GetConstructor(new Type[] { innerType })); innerType = type; } _ilg.Call(outerType.GetConstructor(new Type[] { innerType })); } private void ReadCollection(CollectionDataContract collectionContract) { Type type = collectionContract.UnderlyingType; Type itemType = collectionContract.ItemType; bool isArray = (collectionContract.Kind == CollectionKind.Array); ConstructorInfo constructor = collectionContract.Constructor; if (type.GetTypeInfo().IsInterface) { switch (collectionContract.Kind) { case CollectionKind.GenericDictionary: type = Globals.TypeOfDictionaryGeneric.MakeGenericType(itemType.GetGenericArguments()); constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>()); break; case CollectionKind.Dictionary: type = Globals.TypeOfHashtable; constructor = XmlFormatGeneratorStatics.HashtableCtor; break; case CollectionKind.Collection: case CollectionKind.GenericCollection: case CollectionKind.Enumerable: case CollectionKind.GenericEnumerable: case CollectionKind.List: case CollectionKind.GenericList: type = itemType.MakeArrayType(); isArray = true; break; } } string itemName = collectionContract.ItemName; string itemNs = collectionContract.StableName.Namespace; _objectLocal = _ilg.DeclareLocal(type, "objectDeserialized"); if (!isArray) { if (type.GetTypeInfo().IsValueType) { _ilg.Ldloca(_objectLocal); _ilg.InitObj(type); } else { _ilg.New(constructor); _ilg.Stloc(_objectLocal); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, _objectLocal); } } LocalBuilder size = _ilg.DeclareLocal(Globals.TypeOfInt, "arraySize"); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetArraySizeMethod); _ilg.Stloc(size); LocalBuilder objectId = _ilg.DeclareLocal(Globals.TypeOfString, "objectIdRead"); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetObjectIdMethod); _ilg.Stloc(objectId); bool canReadPrimitiveArray = false; if (isArray && TryReadPrimitiveArray(type, itemType, size)) { canReadPrimitiveArray = true; _ilg.IfNot(); } _ilg.If(size, Cmp.EqualTo, -1); LocalBuilder growingCollection = null; if (isArray) { growingCollection = _ilg.DeclareLocal(type, "growingCollection"); _ilg.NewArray(itemType, 32); _ilg.Stloc(growingCollection); } LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt, "i"); object forLoop = _ilg.For(i, 0, Int32.MaxValue); IsStartElement(_memberNamesArg, _memberNamespacesArg); _ilg.If(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1); LocalBuilder value = ReadCollectionItem(collectionContract, itemType, itemName, itemNs); if (isArray) { MethodInfo ensureArraySizeMethod = XmlFormatGeneratorStatics.EnsureArraySizeMethod.MakeGenericMethod(itemType); _ilg.Call(null, ensureArraySizeMethod, growingCollection, i); _ilg.Stloc(growingCollection); _ilg.StoreArrayElement(growingCollection, i, value); } else StoreCollectionValue(_objectLocal, value, collectionContract); _ilg.Else(); IsEndElement(); _ilg.If(); _ilg.Break(forLoop); _ilg.Else(); HandleUnexpectedItemInCollection(i); _ilg.EndIf(); _ilg.EndIf(); _ilg.EndFor(); if (isArray) { MethodInfo trimArraySizeMethod = XmlFormatGeneratorStatics.TrimArraySizeMethod.MakeGenericMethod(itemType); _ilg.Call(null, trimArraySizeMethod, growingCollection, i); _ilg.Stloc(_objectLocal); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectWithIdMethod, objectId, _objectLocal); } _ilg.Else(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, size); if (isArray) { _ilg.NewArray(itemType, size); _ilg.Stloc(_objectLocal); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, _objectLocal); } LocalBuilder j = _ilg.DeclareLocal(Globals.TypeOfInt, "j"); _ilg.For(j, 0, size); IsStartElement(_memberNamesArg, _memberNamespacesArg); _ilg.If(); LocalBuilder itemValue = ReadCollectionItem(collectionContract, itemType, itemName, itemNs); if (isArray) _ilg.StoreArrayElement(_objectLocal, j, itemValue); else StoreCollectionValue(_objectLocal, itemValue, collectionContract); _ilg.Else(); HandleUnexpectedItemInCollection(j); _ilg.EndIf(); _ilg.EndFor(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.CheckEndOfArrayMethod, _xmlReaderArg, size, _memberNamesArg, _memberNamespacesArg); _ilg.EndIf(); if (canReadPrimitiveArray) { _ilg.Else(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectWithIdMethod, objectId, _objectLocal); _ilg.EndIf(); } } private void ReadGetOnlyCollection(CollectionDataContract collectionContract) { Type type = collectionContract.UnderlyingType; Type itemType = collectionContract.ItemType; bool isArray = (collectionContract.Kind == CollectionKind.Array); string itemName = collectionContract.ItemName; string itemNs = collectionContract.StableName.Namespace; _objectLocal = _ilg.DeclareLocal(type, "objectDeserialized"); _ilg.Load(_contextArg); _ilg.LoadMember(XmlFormatGeneratorStatics.GetCollectionMemberMethod); _ilg.ConvertValue(Globals.TypeOfObject, type); _ilg.Stloc(_objectLocal); //check that items are actually going to be deserialized into the collection IsStartElement(_memberNamesArg, _memberNamespacesArg); _ilg.If(); _ilg.If(_objectLocal, Cmp.EqualTo, null); _ilg.Call(null, XmlFormatGeneratorStatics.ThrowNullValueReturnedForGetOnlyCollectionExceptionMethod, type); _ilg.Else(); LocalBuilder size = _ilg.DeclareLocal(Globals.TypeOfInt, "arraySize"); if (isArray) { _ilg.Load(_objectLocal); _ilg.Call(XmlFormatGeneratorStatics.GetArrayLengthMethod); _ilg.Stloc(size); } _ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, _objectLocal); LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt, "i"); object forLoop = _ilg.For(i, 0, Int32.MaxValue); IsStartElement(_memberNamesArg, _memberNamespacesArg); _ilg.If(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1); LocalBuilder value = ReadCollectionItem(collectionContract, itemType, itemName, itemNs); if (isArray) { _ilg.If(size, Cmp.EqualTo, i); _ilg.Call(null, XmlFormatGeneratorStatics.ThrowArrayExceededSizeExceptionMethod, size, type); _ilg.Else(); _ilg.StoreArrayElement(_objectLocal, i, value); _ilg.EndIf(); } else StoreCollectionValue(_objectLocal, value, collectionContract); _ilg.Else(); IsEndElement(); _ilg.If(); _ilg.Break(forLoop); _ilg.Else(); HandleUnexpectedItemInCollection(i); _ilg.EndIf(); _ilg.EndIf(); _ilg.EndFor(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.CheckEndOfArrayMethod, _xmlReaderArg, size, _memberNamesArg, _memberNamespacesArg); _ilg.EndIf(); _ilg.EndIf(); } private bool TryReadPrimitiveArray(Type type, Type itemType, LocalBuilder size) { PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); if (primitiveContract == null) return false; string readArrayMethod = null; switch (itemType.GetTypeCode()) { case TypeCode.Boolean: readArrayMethod = "TryReadBooleanArray"; break; case TypeCode.DateTime: readArrayMethod = "TryReadDateTimeArray"; break; case TypeCode.Decimal: readArrayMethod = "TryReadDecimalArray"; break; case TypeCode.Int32: readArrayMethod = "TryReadInt32Array"; break; case TypeCode.Int64: readArrayMethod = "TryReadInt64Array"; break; case TypeCode.Single: readArrayMethod = "TryReadSingleArray"; break; case TypeCode.Double: readArrayMethod = "TryReadDoubleArray"; break; default: break; } if (readArrayMethod != null) { _ilg.Load(_xmlReaderArg); _ilg.Load(_contextArg); _ilg.Load(_memberNamesArg); _ilg.Load(_memberNamespacesArg); _ilg.Load(size); _ilg.Ldloca(_objectLocal); _ilg.Call(typeof(XmlReaderDelegator).GetMethod(readArrayMethod, Globals.ScanAllMembers)); return true; } return false; } private LocalBuilder ReadCollectionItem(CollectionDataContract collectionContract, Type itemType, string itemName, string itemNs) { if (collectionContract.Kind == CollectionKind.Dictionary || collectionContract.Kind == CollectionKind.GenericDictionary) { _ilg.Call(_contextArg, XmlFormatGeneratorStatics.ResetAttributesMethod); LocalBuilder value = _ilg.DeclareLocal(itemType, "valueRead"); _ilg.Load(_collectionContractArg); _ilg.Call(XmlFormatGeneratorStatics.GetItemContractMethod); _ilg.Load(_xmlReaderArg); _ilg.Load(_contextArg); _ilg.Call(XmlFormatGeneratorStatics.ReadXmlValueMethod); _ilg.ConvertValue(Globals.TypeOfObject, itemType); _ilg.Stloc(value); return value; } else { return ReadValue(itemType, itemName, itemNs); } } private void StoreCollectionValue(LocalBuilder collection, LocalBuilder value, CollectionDataContract collectionContract) { if (collectionContract.Kind == CollectionKind.GenericDictionary || collectionContract.Kind == CollectionKind.Dictionary) { ClassDataContract keyValuePairContract = DataContract.GetDataContract(value.LocalType) as ClassDataContract; if (keyValuePairContract == null) { DiagnosticUtility.DebugAssert("Failed to create contract for KeyValuePair type"); } DataMember keyMember = keyValuePairContract.Members[0]; DataMember valueMember = keyValuePairContract.Members[1]; LocalBuilder pairKey = _ilg.DeclareLocal(keyMember.MemberType, keyMember.Name); LocalBuilder pairValue = _ilg.DeclareLocal(valueMember.MemberType, valueMember.Name); _ilg.LoadAddress(value); _ilg.LoadMember(keyMember.MemberInfo); _ilg.Stloc(pairKey); _ilg.LoadAddress(value); _ilg.LoadMember(valueMember.MemberInfo); _ilg.Stloc(pairValue); _ilg.Call(collection, collectionContract.AddMethod, pairKey, pairValue); if (collectionContract.AddMethod.ReturnType != Globals.TypeOfVoid) _ilg.Pop(); } else { _ilg.Call(collection, collectionContract.AddMethod, value); if (collectionContract.AddMethod.ReturnType != Globals.TypeOfVoid) _ilg.Pop(); } } private void HandleUnexpectedItemInCollection(LocalBuilder iterator) { IsStartElement(); _ilg.If(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.SkipUnknownElementMethod, _xmlReaderArg); _ilg.Dec(iterator); _ilg.Else(); ThrowUnexpectedStateException(XmlNodeType.Element); _ilg.EndIf(); } private void IsStartElement(ArgBuilder nameArg, ArgBuilder nsArg) { _ilg.Call(_xmlReaderArg, XmlFormatGeneratorStatics.IsStartElementMethod2, nameArg, nsArg); } private void IsStartElement() { _ilg.Call(_xmlReaderArg, XmlFormatGeneratorStatics.IsStartElementMethod0); } private void IsEndElement() { _ilg.Load(_xmlReaderArg); _ilg.LoadMember(XmlFormatGeneratorStatics.NodeTypeProperty); _ilg.Load(XmlNodeType.EndElement); _ilg.Ceq(); } private void ThrowUnexpectedStateException(XmlNodeType expectedState) { _ilg.Call(null, XmlFormatGeneratorStatics.CreateUnexpectedStateExceptionMethod, expectedState, _xmlReaderArg); _ilg.Throw(); } private void ThrowValidationException(string msg, params object[] values) { { _ilg.Load(msg); } ThrowValidationException(); } private void ThrowValidationException() { //SerializationException is internal in SL and so cannot be directly invoked from DynamicMethod //So use helper function to create SerializationException _ilg.Call(XmlFormatGeneratorStatics.CreateSerializationExceptionMethod); _ilg.Throw(); } } #endif [SecuritySafeCritical] static internal object UnsafeGetUninitializedObject(Type type) { #if !NET_NATIVE if (type.GetTypeInfo().IsValueType) { return Activator.CreateInstance(type); } bool hasDefaultConstructor; if (!s_typeHasDefaultConstructorMap.TryGetValue(type, out hasDefaultConstructor)) { hasDefaultConstructor = type.GetConstructor(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Array.Empty<Type>()) != null; s_typeHasDefaultConstructorMap[type] = hasDefaultConstructor; } return hasDefaultConstructor ? Activator.CreateInstance(type) : TryGetUninitializedObjectWithFormatterServices(type) ?? Activator.CreateInstance(type); #else return RuntimeAugments.NewObject(type.TypeHandle); #endif } /// <SecurityNote> /// Critical - Elevates by calling GetUninitializedObject which has a LinkDemand /// Safe - marked as such so that it's callable from transparent generated IL. Takes id as parameter which /// is guaranteed to be in internal serialization cache. /// </SecurityNote> [SecuritySafeCritical] #if USE_REFEMIT public static object UnsafeGetUninitializedObject(int id) #else static internal object UnsafeGetUninitializedObject(int id) #endif { var type = DataContract.GetDataContractForInitialization(id).TypeForInitialization; return UnsafeGetUninitializedObject(type); } static internal object TryGetUninitializedObjectWithFormatterServices(Type type) => s_getUninitializedObjectDelegate?.Invoke(type); } }
using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Discord.API; using Discord.Rest; namespace Discord.WebSocket { /// <summary> /// Represents the base of a WebSocket-based Discord client. /// </summary> public abstract partial class BaseSocketClient : BaseDiscordClient, IDiscordClient { protected readonly DiscordSocketConfig BaseConfig; /// <summary> /// Gets the estimated round-trip latency, in milliseconds, to the gateway server. /// </summary> /// <returns> /// An <see cref="int"/> that represents the round-trip latency to the WebSocket server. Please /// note that this value does not represent a "true" latency for operations such as sending a message. /// </returns> public abstract int Latency { get; protected set; } /// <summary> /// Gets the status for the logged-in user. /// </summary> /// <returns> /// A status object that represents the user's online presence status. /// </returns> public abstract UserStatus Status { get; protected set; } /// <summary> /// Gets the activity for the logged-in user. /// </summary> /// <returns> /// An activity object that represents the user's current activity. /// </returns> public abstract IActivity Activity { get; protected set; } /// <summary> /// Provides access to a REST-only client with a shared state from this client. /// </summary> public abstract DiscordSocketRestClient Rest { get; } internal new DiscordSocketApiClient ApiClient => base.ApiClient as DiscordSocketApiClient; /// <summary> /// Gets the current logged-in user. /// </summary> public new SocketSelfUser CurrentUser { get => base.CurrentUser as SocketSelfUser; protected set => base.CurrentUser = value; } /// <summary> /// Gets a collection of guilds that the user is currently in. /// </summary> /// <returns> /// A read-only collection of guilds that the current user is in. /// </returns> public abstract IReadOnlyCollection<SocketGuild> Guilds { get; } /// <summary> /// Gets a collection of private channels opened in this session. /// </summary> /// <remarks> /// This method will retrieve all private channels (including direct-message, group channel and such) that /// are currently opened in this session. /// <note type="warning"> /// This method will not return previously opened private channels outside of the current session! If /// you have just started the client, this may return an empty collection. /// </note> /// </remarks> /// <returns> /// A read-only collection of private channels that the user currently partakes in. /// </returns> public abstract IReadOnlyCollection<ISocketPrivateChannel> PrivateChannels { get; } /// <summary> /// Gets a collection of available voice regions. /// </summary> /// <returns> /// A read-only collection of voice regions that the user has access to. /// </returns> [Obsolete("This property is obsolete, use the GetVoiceRegionsAsync method instead.")] public abstract IReadOnlyCollection<RestVoiceRegion> VoiceRegions { get; } internal BaseSocketClient(DiscordSocketConfig config, DiscordRestApiClient client) : base(config, client) => BaseConfig = config; private static DiscordSocketApiClient CreateApiClient(DiscordSocketConfig config) => new DiscordSocketApiClient(config.RestClientProvider, config.WebSocketProvider, DiscordRestConfig.UserAgent, rateLimitPrecision: config.RateLimitPrecision, useSystemClock: config.UseSystemClock); /// <summary> /// Gets a Discord application information for the logged-in user. /// </summary> /// <remarks> /// This method reflects your application information you submitted when creating a Discord application via /// the Developer Portal. /// </remarks> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task that represents the asynchronous get operation. The task result contains the application /// information. /// </returns> public abstract Task<RestApplication> GetApplicationInfoAsync(RequestOptions options = null); /// <summary> /// Gets a generic user. /// </summary> /// <param name="id">The user snowflake ID.</param> /// <remarks> /// This method gets the user present in the WebSocket cache with the given condition. /// <note type="warning"> /// Sometimes a user may return <c>null</c> due to Discord not sending offline users in large guilds /// (i.e. guild with 100+ members) actively. To download users on startup and to see more information /// about this subject, see <see cref="Discord.WebSocket.DiscordSocketConfig.AlwaysDownloadUsers" />. /// </note> /// <note> /// This method does not attempt to fetch users that the logged-in user does not have access to (i.e. /// users who don't share mutual guild(s) with the current user). If you wish to get a user that you do /// not have access to, consider using the REST implementation of /// <see cref="DiscordRestClient.GetUserAsync(System.UInt64,Discord.RequestOptions)" />. /// </note> /// </remarks> /// <returns> /// A generic WebSocket-based user; <c>null</c> when the user cannot be found. /// </returns> public abstract SocketUser GetUser(ulong id); /// <summary> /// Gets a user. /// </summary> /// <remarks> /// This method gets the user present in the WebSocket cache with the given condition. /// <note type="warning"> /// Sometimes a user may return <c>null</c> due to Discord not sending offline users in large guilds /// (i.e. guild with 100+ members) actively. To download users on startup and to see more information /// about this subject, see <see cref="Discord.WebSocket.DiscordSocketConfig.AlwaysDownloadUsers" />. /// </note> /// <note> /// This method does not attempt to fetch users that the logged-in user does not have access to (i.e. /// users who don't share mutual guild(s) with the current user). If you wish to get a user that you do /// not have access to, consider using the REST implementation of /// <see cref="DiscordRestClient.GetUserAsync(System.UInt64,Discord.RequestOptions)" />. /// </note> /// </remarks> /// <param name="username">The name of the user.</param> /// <param name="discriminator">The discriminator value of the user.</param> /// <returns> /// A generic WebSocket-based user; <c>null</c> when the user cannot be found. /// </returns> public abstract SocketUser GetUser(string username, string discriminator); /// <summary> /// Gets a channel. /// </summary> /// <param name="id">The snowflake identifier of the channel (e.g. `381889909113225237`).</param> /// <returns> /// A generic WebSocket-based channel object (voice, text, category, etc.) associated with the identifier; /// <c>null</c> when the channel cannot be found. /// </returns> public abstract SocketChannel GetChannel(ulong id); /// <summary> /// Gets a guild. /// </summary> /// <param name="id">The guild snowflake identifier.</param> /// <returns> /// A WebSocket-based guild associated with the snowflake identifier; <c>null</c> when the guild cannot be /// found. /// </returns> public abstract SocketGuild GetGuild(ulong id); /// <summary> /// Gets a voice region. /// </summary> /// <param name="id">The identifier of the voice region (e.g. <c>eu-central</c> ).</param> /// <returns> /// A REST-based voice region associated with the identifier; <c>null</c> if the voice region is not /// found. /// </returns> [Obsolete("This method is obsolete, use GetVoiceRegionAsync instead.")] public abstract RestVoiceRegion GetVoiceRegion(string id); /// <summary> /// Gets all voice regions. /// </summary> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task that contains a read-only collection of REST-based voice regions. /// </returns> public abstract ValueTask<IReadOnlyCollection<RestVoiceRegion>> GetVoiceRegionsAsync(RequestOptions options = null); /// <summary> /// Gets a voice region. /// </summary> /// <param name="id">The identifier of the voice region (e.g. <c>eu-central</c> ).</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task that contains a REST-based voice region associated with the identifier; <c>null</c> if the /// voice region is not found. /// </returns> public abstract ValueTask<RestVoiceRegion> GetVoiceRegionAsync(string id, RequestOptions options = null); /// <inheritdoc /> public abstract Task StartAsync(); /// <inheritdoc /> public abstract Task StopAsync(); /// <summary> /// Sets the current status of the user (e.g. Online, Do not Disturb). /// </summary> /// <param name="status">The new status to be set.</param> /// <returns> /// A task that represents the asynchronous set operation. /// </returns> public abstract Task SetStatusAsync(UserStatus status); /// <summary> /// Sets the game of the user. /// </summary> /// <param name="name">The name of the game.</param> /// <param name="streamUrl">If streaming, the URL of the stream. Must be a valid Twitch URL.</param> /// <param name="type">The type of the game.</param> /// <returns> /// A task that represents the asynchronous set operation. /// </returns> public abstract Task SetGameAsync(string name, string streamUrl = null, ActivityType type = ActivityType.Playing); /// <summary> /// Sets the <paramref name="activity"/> of the logged-in user. /// </summary> /// <remarks> /// This method sets the <paramref name="activity"/> of the user. /// <note type="note"> /// Discord will only accept setting of name and the type of activity. /// </note> /// <note type="warning"> /// Rich Presence cannot be set via this method or client. Rich Presence is strictly limited to RPC /// clients only. /// </note> /// </remarks> /// <param name="activity">The activity to be set.</param> /// <returns> /// A task that represents the asynchronous set operation. /// </returns> public abstract Task SetActivityAsync(IActivity activity); /// <summary> /// Attempts to download users into the user cache for the selected guilds. /// </summary> /// <param name="guilds">The guilds to download the members from.</param> /// <returns> /// A task that represents the asynchronous download operation. /// </returns> public abstract Task DownloadUsersAsync(IEnumerable<IGuild> guilds); /// <summary> /// Creates a guild for the logged-in user who is in less than 10 active guilds. /// </summary> /// <remarks> /// This method creates a new guild on behalf of the logged-in user. /// <note type="warning"> /// Due to Discord's limitation, this method will only work for users that are in less than 10 guilds. /// </note> /// </remarks> /// <param name="name">The name of the new guild.</param> /// <param name="region">The voice region to create the guild with.</param> /// <param name="jpegIcon">The icon of the guild.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task that represents the asynchronous creation operation. The task result contains the created guild. /// </returns> public Task<RestGuild> CreateGuildAsync(string name, IVoiceRegion region, Stream jpegIcon = null, RequestOptions options = null) => ClientHelper.CreateGuildAsync(this, name, region, jpegIcon, options ?? RequestOptions.Default); /// <summary> /// Gets the connections that the user has set up. /// </summary> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task that represents the asynchronous get operation. The task result contains a read-only collection of connections. /// </returns> public Task<IReadOnlyCollection<RestConnection>> GetConnectionsAsync(RequestOptions options = null) => ClientHelper.GetConnectionsAsync(this, options ?? RequestOptions.Default); /// <summary> /// Gets an invite. /// </summary> /// <param name="inviteId">The invitation identifier.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task that represents the asynchronous get operation. The task result contains the invite information. /// </returns> public Task<RestInviteMetadata> GetInviteAsync(string inviteId, RequestOptions options = null) => ClientHelper.GetInviteAsync(this, inviteId, options ?? RequestOptions.Default); // IDiscordClient /// <inheritdoc /> async Task<IApplication> IDiscordClient.GetApplicationInfoAsync(RequestOptions options) => await GetApplicationInfoAsync(options).ConfigureAwait(false); /// <inheritdoc /> Task<IChannel> IDiscordClient.GetChannelAsync(ulong id, CacheMode mode, RequestOptions options) => Task.FromResult<IChannel>(GetChannel(id)); /// <inheritdoc /> Task<IReadOnlyCollection<IPrivateChannel>> IDiscordClient.GetPrivateChannelsAsync(CacheMode mode, RequestOptions options) => Task.FromResult<IReadOnlyCollection<IPrivateChannel>>(PrivateChannels); /// <inheritdoc /> async Task<IReadOnlyCollection<IConnection>> IDiscordClient.GetConnectionsAsync(RequestOptions options) => await GetConnectionsAsync(options).ConfigureAwait(false); /// <inheritdoc /> async Task<IInvite> IDiscordClient.GetInviteAsync(string inviteId, RequestOptions options) => await GetInviteAsync(inviteId, options).ConfigureAwait(false); /// <inheritdoc /> Task<IGuild> IDiscordClient.GetGuildAsync(ulong id, CacheMode mode, RequestOptions options) => Task.FromResult<IGuild>(GetGuild(id)); /// <inheritdoc /> Task<IReadOnlyCollection<IGuild>> IDiscordClient.GetGuildsAsync(CacheMode mode, RequestOptions options) => Task.FromResult<IReadOnlyCollection<IGuild>>(Guilds); /// <inheritdoc /> async Task<IGuild> IDiscordClient.CreateGuildAsync(string name, IVoiceRegion region, Stream jpegIcon, RequestOptions options) => await CreateGuildAsync(name, region, jpegIcon, options).ConfigureAwait(false); /// <inheritdoc /> Task<IUser> IDiscordClient.GetUserAsync(ulong id, CacheMode mode, RequestOptions options) => Task.FromResult<IUser>(GetUser(id)); /// <inheritdoc /> Task<IUser> IDiscordClient.GetUserAsync(string username, string discriminator, RequestOptions options) => Task.FromResult<IUser>(GetUser(username, discriminator)); /// <inheritdoc /> Task<IVoiceRegion> IDiscordClient.GetVoiceRegionAsync(string id, RequestOptions options) => Task.FromResult<IVoiceRegion>(GetVoiceRegion(id)); /// <inheritdoc /> Task<IReadOnlyCollection<IVoiceRegion>> IDiscordClient.GetVoiceRegionsAsync(RequestOptions options) => Task.FromResult<IReadOnlyCollection<IVoiceRegion>>(VoiceRegions); } }
// Copyright (c) 2014 SIL International // This software is licensed under the MIT License (http://opensource.org/licenses/MIT) using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; #if !MONO using Keyman7Interop; using Keyman10Interop; #endif using Microsoft.Win32; using SIL.Keyboarding; namespace SIL.Windows.Forms.Keyboarding.Windows { /// <summary> /// Class for handling Keyman keyboards not associated with a Windows language /// </summary> internal class KeymanKeyboardAdaptor : IKeyboardRetrievingAdaptor { private enum KeymanVersion { NotInstalled, Keyman6, Keyman7to9, Keyman10 } public KeymanKeyboardAdaptor() { InstalledKeymanVersion = GetInstalledKeymanVersion(); } private KeymanVersion InstalledKeymanVersion { get; set; } #region IKeyboardRetrievingAdaptor Members /// <summary> /// The type of keyboards this adaptor handles: system or other (like Keyman, ibus...) /// </summary> public KeyboardAdaptorType Type { get { CheckDisposed(); return KeyboardAdaptorType.OtherIm; } } public bool IsApplicable { get { #if !MONO switch (InstalledKeymanVersion) { case KeymanVersion.Keyman10: var keyman10 = new KeymanClass(); if (keyman10.Keyboards != null && keyman10.Keyboards.Count > 0) { return true; } break; case KeymanVersion.Keyman7to9: var keyman = new TavultesoftKeymanClass(); if (keyman.Keyboards != null && keyman.Keyboards.Count > 0) { return true; } break; case KeymanVersion.Keyman6: var keymanLink = new KeymanLink.KeymanLink(); if (keymanLink.Initialize()) { if (keymanLink.Keyboards != null && keymanLink.Keyboards.Length > 0) { return true; } } break; case KeymanVersion.NotInstalled: return false; default: throw new NotSupportedException($"{InstalledKeymanVersion} not yet supported in IsApplicable"); } #endif return false; } } public IKeyboardSwitchingAdaptor SwitchingAdaptor { get; set; } public void Initialize() { CheckDisposed(); SwitchingAdaptor = GetKeymanSwitchingAdapter(InstalledKeymanVersion); UpdateAvailableKeyboards(); } private IKeyboardSwitchingAdaptor GetKeymanSwitchingAdapter(KeymanVersion installedKeymanVersion) { switch (installedKeymanVersion) { case KeymanVersion.Keyman10: return new KeymanKeyboardSwitchingAdapter(); case KeymanVersion.Keyman6: case KeymanVersion.Keyman7to9: return new LegacyKeymanKeyboardSwitchingAdapter(); } return null; } private KeymanVersion GetInstalledKeymanVersion() { #if !MONO // limit the COMException catching by determining the current version once and assuming it for the // rest of the adaptor's lifetime try { var keyman10 = new KeymanClass(); return KeymanVersion.Keyman10; } catch (COMException) { // not 10 } try { var keyman = new TavultesoftKeymanClass(); return KeymanVersion.Keyman7to9; } catch (COMException) { // Not 7-9 } try { var keymanLink = new KeymanLink.KeymanLink(); return KeymanVersion.Keyman6; } catch (COMException) { } #endif return KeymanVersion.NotInstalled; } public void UpdateAvailableKeyboards() { CheckDisposed(); Dictionary<string, KeymanKeyboardDescription> curKeyboards = KeyboardController.Instance.Keyboards.OfType<KeymanKeyboardDescription>().ToDictionary(kd => kd.Id); #if !MONO switch (InstalledKeymanVersion) { case KeymanVersion.Keyman10: // Keyman10 keyboards are handled by the WinKeyboardAdapter and WindowsKeyboardSwitchingAdapter break; case KeymanVersion.Keyman7to9: var keyman = new TavultesoftKeymanClass(); UpdateKeyboards(curKeyboards, keyman.Keyboards.OfType<Keyman7Interop.IKeymanKeyboard>().Select(kb => kb.Name), false); break; case KeymanVersion.Keyman6: var keymanLink = new KeymanLink.KeymanLink(); if (keymanLink.Initialize()) { UpdateKeyboards(curKeyboards, keymanLink.Keyboards.Select(kb => kb.KbdName), true); } break; } #endif } private void UpdateKeyboards(Dictionary<string, KeymanKeyboardDescription> curKeyboards, IEnumerable<string> availableKeyboardNames, bool isKeyman6) { foreach (string keyboardName in availableKeyboardNames) { KeymanKeyboardDescription existingKeyboard; if (curKeyboards.TryGetValue(keyboardName, out existingKeyboard)) { if (!existingKeyboard.IsAvailable) { existingKeyboard.SetIsAvailable(true); existingKeyboard.IsKeyman6 = isKeyman6; if (existingKeyboard.Format == KeyboardFormat.Unknown) existingKeyboard.Format = KeyboardFormat.CompiledKeyman; } curKeyboards.Remove(keyboardName); } else { KeyboardController.Instance.Keyboards.Add(new KeymanKeyboardDescription(keyboardName, isKeyman6, this, true) { Format = KeyboardFormat.CompiledKeyman }); } } } /// <summary> /// Creates and returns a keyboard definition object based on the ID. /// Note that this method is used when we do NOT have a matching available keyboard. /// Therefore we can presume that the created one is NOT available. /// </summary> public KeyboardDescription CreateKeyboardDefinition(string id) { CheckDisposed(); switch (InstalledKeymanVersion) { case KeymanVersion.Keyman10: string layout, locale; KeyboardController.GetLayoutAndLocaleFromLanguageId(id, out layout, out locale); string cultureName; var inputLanguage = WinKeyboardUtils.GetInputLanguage(locale, layout, out cultureName); return new KeymanKeyboardDescription(id, false, this, false) { InputLanguage = inputLanguage }; default: return new KeymanKeyboardDescription(id, false, this, false); } } public string GetKeyboardSetupApplication(out string arguments) { arguments = null; string keyman; int version = 0; string keymanPath = GetKeymanRegistryValue(@"root path", ref version); if (keymanPath != null) { keyman = Path.Combine(keymanPath, @"kmshell.exe"); if (File.Exists(keyman)) { arguments = @""; if (version > 6) arguments = @"-c"; return keyman; } } return null; } /// <summary> /// This method returns the path to Keyman Configuration if it is installed. Otherwise it returns null. /// It also sets the version of Keyman that it found. /// </summary> /// <param name="key">The key.</param> /// <param name="version">The version.</param> private static string GetKeymanRegistryValue(string key, ref int version) { using (var olderKeyman = Registry.LocalMachine.OpenSubKey(@"Software\Tavultesoft\Keyman", false)) using (var olderKeyman32 = Registry.LocalMachine.OpenSubKey(@"Software\WOW6432Node\Tavultesoft\Keyman", false)) { var keymanKey = olderKeyman32 ?? olderKeyman; if (keymanKey == null) return null; int[] versions = {9, 8, 7, 6, 5}; foreach (var vers in versions) { using (var rkApplication = keymanKey.OpenSubKey($"{vers}.0", false)) { if (rkApplication != null) { foreach (var sKey in rkApplication.GetValueNames()) { if (sKey == key) { version = vers; return (string) rkApplication.GetValue(sKey); } } } } } } return null; } public Action GetKeyboardSetupAction() { switch (InstalledKeymanVersion) { #if !MONO case KeymanVersion.Keyman10: return () => { var keymanClass = new KeymanClass(); keymanClass.Control.OpenConfiguration(); }; case KeymanVersion.Keyman7to9: case KeymanVersion.Keyman6: return () => { string args; var setupApp = GetKeyboardSetupApplication(out args); Process.Start(setupApp, args); }; #endif default: throw new NotSupportedException($"No keyboard setup action defined for keyman version {InstalledKeymanVersion}"); } } public Action GetSecondaryKeyboardSetupAction() => GetKeyboardSetupAction(); public bool IsSecondaryKeyboardSetupApplication => true; public bool CanHandleFormat(KeyboardFormat format) { CheckDisposed(); switch (format) { case KeyboardFormat.CompiledKeyman: case KeyboardFormat.Keyman: case KeyboardFormat.KeymanPackage: return true; } return false; } #endregion #region IDisposable & Co. implementation // Region last reviewed: never /// <summary> /// Check to see if the object has been disposed. /// All public Properties and Methods should call this /// before doing anything else. /// </summary> public void CheckDisposed() { if (IsDisposed) throw new ObjectDisposedException(String.Format("'{0}' in use after being disposed.", GetType().Name)); } /// <summary> /// See if the object has been disposed. /// </summary> public bool IsDisposed { get; private set; } /// <summary> /// Finalizer, in case client doesn't dispose it. /// Force Dispose(false) if not already called (i.e. m_isDisposed is true) /// </summary> /// <remarks> /// In case some clients forget to dispose it directly. /// </remarks> ~KeymanKeyboardAdaptor() { Dispose(false); // The base class finalizer is called automatically. } /// <summary> /// /// </summary> /// <remarks>Must not be virtual.</remarks> public void Dispose() { Dispose(true); // This object will be cleaned up by the Dispose method. // Therefore, you should call GC.SupressFinalize to // take this object off the finalization queue // and prevent finalization code for this object // from executing a second time. GC.SuppressFinalize(this); } /// <summary> /// Executes in two distinct scenarios. /// /// 1. If disposing is true, the method has been called directly /// or indirectly by a user's code via the Dispose method. /// Both managed and unmanaged resources can be disposed. /// /// 2. If disposing is false, the method has been called by the /// runtime from inside the finalizer and you should not reference (access) /// other managed objects, as they already have been garbage collected. /// Only unmanaged resources can be disposed. /// </summary> /// <param name="disposing"></param> /// <remarks> /// If any exceptions are thrown, that is fine. /// If the method is being done in a finalizer, it will be ignored. /// If it is thrown by client code calling Dispose, /// it needs to be handled by fixing the bug. /// /// If subclasses override this method, they should call the base implementation. /// </remarks> protected virtual void Dispose(bool disposing) { Debug.WriteLineIf(!disposing, "****************** " + GetType().Name + " 'disposing' is false. ******************"); // Must not be run more than once. if (IsDisposed) return; if (disposing) { // Dispose managed resources here. } // Dispose unmanaged resources here, whether disposing is true or false. IsDisposed = true; } #endregion IDisposable & Co. implementation } }
//------------------------------------------------------------------------------ // <copyright file="DBBindings.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> // <owner current="true" primary="false">[....]</owner> //------------------------------------------------------------------------------ namespace System.Data.OleDb { using System; using System.ComponentModel; using System.Diagnostics; using System.Data; using System.Data.Common; using System.Globalization; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; sealed internal class Bindings { private readonly tagDBPARAMBINDINFO[] _bindInfo; private readonly tagDBBINDING[] _dbbindings; private readonly tagDBCOLUMNACCESS[] _dbcolumns; private OleDbParameter[] _parameters; private int _collectionChangeID; private OleDbDataReader _dataReader; private ColumnBinding[] _columnBindings; private RowBinding _rowBinding; private int _index; private int _count; private int _dataBufferSize; private bool _ifIRowsetElseIRow; private bool _forceRebind; private bool _needToReset; private Bindings(int count) { _count = count; _dbbindings = new tagDBBINDING[count]; for(int i = 0;i < _dbbindings.Length;++i) { _dbbindings[i] = new tagDBBINDING(); } _dbcolumns = new tagDBCOLUMNACCESS[count]; } internal Bindings(OleDbParameter[] parameters, int collectionChangeID) : this(parameters.Length) { _bindInfo = new tagDBPARAMBINDINFO[parameters.Length]; _parameters = parameters; _collectionChangeID = collectionChangeID; _ifIRowsetElseIRow = true; } internal Bindings(OleDbDataReader dataReader, bool ifIRowsetElseIRow, int count) : this(count) { _dataReader = dataReader; _ifIRowsetElseIRow = ifIRowsetElseIRow; } internal tagDBPARAMBINDINFO[] BindInfo { get { return _bindInfo; } } internal tagDBCOLUMNACCESS[] DBColumnAccess { get { return _dbcolumns; } } internal int CurrentIndex { //get { return _index; } set { Debug.Assert((0 <= value) && (value < _count), "bad binding index"); _index = value; } } internal ColumnBinding[] ColumnBindings() { Debug.Assert(null != _columnBindings, "null ColumnBindings"); return _columnBindings; } internal OleDbParameter[] Parameters() { Debug.Assert(null != _parameters, "null Parameters"); return _parameters; } internal RowBinding RowBinding() { //Debug.Assert(null != _rowBinding, "null RowBinding"); return _rowBinding; } internal bool ForceRebind { get { return _forceRebind; } set { _forceRebind = value; } } // tagDBPARAMBINDINFO member access internal IntPtr DataSourceType { //get { return _bindInfo[_index].pwszDataSourceType; } set { _bindInfo[_index].pwszDataSourceType = value; } } internal IntPtr Name { //get { return _bindInfo[_index].pwszName; } set { _bindInfo[_index].pwszName= value; } } internal IntPtr ParamSize { get { if (null != _bindInfo) { return _bindInfo[_index].ulParamSize; } return IntPtr.Zero; } set { _bindInfo[_index].ulParamSize= value; } } internal int Flags { //get { return _bindInfo[_index].dwFlag; } set { _bindInfo[_index].dwFlags= value; } } // tagDBBINDING member access // internal IntPtr Ordinal { // iOrdinal //get { return _dbbindings[_index].iOrdinal.ToInt32(); } set { _dbbindings[_index].iOrdinal = value; } } #if DEBUG /*internal int ValueOffset { // obValue get { return _dbbindings[_index].obValue.ToInt32(); } } internal int LengthOffset { // obLength get { return _dbbindings[_index].obLength.ToInt32(); } } internal int StatusOffset { // obStatus get { return _dbbindings[_index].obStatus.ToInt32(); } }*/ #endif internal int Part { // dwPart #if DEBUG //get { return _dbbindings[_index].dwPart; } #endif set { _dbbindings[_index].dwPart = value; } } internal int ParamIO { // eParamIO #if DEBUG //get { return _dbbindings[_index].eParamIO; } #endif set { _dbbindings[_index].eParamIO = value; } } internal int MaxLen { // cbMaxLen //get { return (int) _dbbindings[_index].cbMaxLen; } set { Debug.Assert(0 <= value, "invalid MaxLen"); _dbbindings[_index].obStatus = (IntPtr) (_dataBufferSize + 0); _dbbindings[_index].obLength = (IntPtr) (_dataBufferSize + ADP.PtrSize); _dbbindings[_index].obValue = (IntPtr) (_dataBufferSize + ADP.PtrSize + ADP.PtrSize); _dataBufferSize += ADP.PtrSize + ADP.PtrSize; switch(DbType) { case (NativeDBType.BSTR): // ADP.PtrSize case (NativeDBType.HCHAPTER): // ADP.PtrSize case (NativeDBType.PROPVARIANT): // sizeof(PROPVARIANT) case (NativeDBType.VARIANT): // 16 or 24 (8 + ADP.PtrSize *2) case (NativeDBType.BYREF | NativeDBType.BYTES): // ADP.PtrSize case (NativeDBType.BYREF | NativeDBType.WSTR): // ADP.PtrSize // allocate extra space to cache original value for disposal _dataBufferSize += System.Data.OleDb.RowBinding.AlignDataSize(value*2); _needToReset = true; break; default: _dataBufferSize += System.Data.OleDb.RowBinding.AlignDataSize(value); break; } _dbbindings[_index].cbMaxLen = (IntPtr)value; _dbcolumns[_index].cbMaxLen = (IntPtr)value; } } internal int DbType { // wType get { return _dbbindings[_index].wType; } set { _dbbindings[_index].wType = (short) value; _dbcolumns[_index].wType = (short) value; } } internal byte Precision { // bPrecision #if DEBUG //get { return _dbbindings[_index].bPrecision; } #endif set { if (null != _bindInfo) { _bindInfo[_index].bPrecision = value; } _dbbindings[_index].bPrecision = value; _dbcolumns[_index].bPrecision = value; } } internal byte Scale { // bScale #if DEBUG //get { return _dbbindings[_index].bScale; } #endif set { if (null != _bindInfo) { _bindInfo[_index].bScale = value; } _dbbindings[_index].bScale = value; _dbcolumns[_index].bScale = value; } } internal int AllocateForAccessor(OleDbDataReader dataReader, int indexStart, int indexForAccessor) { Debug.Assert(null == _rowBinding, "row binding already allocated"); Debug.Assert(null == _columnBindings, "column bindings already allocated"); RowBinding rowBinding = System.Data.OleDb.RowBinding.CreateBuffer(_count, _dataBufferSize, _needToReset); _rowBinding = rowBinding; ColumnBinding[] columnBindings = rowBinding.SetBindings(dataReader, this, indexStart, indexForAccessor, _parameters, _dbbindings, _ifIRowsetElseIRow); Debug.Assert(null != columnBindings, "null column bindings"); _columnBindings = columnBindings; if (!_ifIRowsetElseIRow) { Debug.Assert(columnBindings.Length == _dbcolumns.Length, "length mismatch"); for(int i = 0; i < columnBindings.Length; ++i) { // WebData 94427 _dbcolumns[i].pData = rowBinding.DangerousGetDataPtr(columnBindings[i].ValueOffset); // We are simply pointing at a location later in the buffer, so we're OK to not addref the buffer. } } #if DEBUG int index = -1; foreach(ColumnBinding binding in columnBindings) { Debug.Assert(index < binding.Index, "invaild index"); index = binding.Index; } #endif return (indexStart + columnBindings.Length); } internal void ApplyInputParameters() { ColumnBinding[] columnBindings = this.ColumnBindings(); OleDbParameter[] parameters = this.Parameters(); RowBinding().StartDataBlock(); for(int i = 0; i < parameters.Length; ++i) { if (ADP.IsDirection(parameters[i], ParameterDirection.Input)) { columnBindings[i].SetOffset(parameters[i].Offset); // MDAC 80657 columnBindings[i].Value(parameters[i].GetCoercedValue()); } else { // always set ouput only and return value parameter values to null when executing parameters[i].Value = null; //columnBindings[i].SetValueEmpty(); // webdata 115079 } } } internal void ApplyOutputParameters() { ColumnBinding[] columnBindings = this.ColumnBindings(); OleDbParameter[] parameters = this.Parameters(); for(int i = 0; i < parameters.Length; ++i) { if (ADP.IsDirection(parameters[i], ParameterDirection.Output)) { parameters[i].Value = columnBindings[i].Value(); } } CleanupBindings(); } internal bool AreParameterBindingsInvalid(OleDbParameterCollection collection) { Debug.Assert(null != collection, "null parameter collection"); Debug.Assert(null != _parameters, "null parameters"); ColumnBinding[] columnBindings = this.ColumnBindings(); if (!ForceRebind && ((collection.ChangeID == _collectionChangeID) && (_parameters.Length == collection.Count))) { for(int i = 0; i < columnBindings.Length; ++i) { ColumnBinding binding = columnBindings[i]; Debug.Assert(null != binding, "null column binding"); Debug.Assert(binding.Parameter() == _parameters[i], "parameter mismatch"); if (binding.IsParameterBindingInvalid(collection[i])) { //Debug.WriteLine("ParameterBindingsInvalid"); return true; } } //Debug.WriteLine("ParameterBindingsValid"); return false; // collection and cached values are the same } //Debug.WriteLine("ParameterBindingsInvalid"); return true; } internal void CleanupBindings() { RowBinding rowBinding = this.RowBinding(); if (null != rowBinding) { rowBinding.ResetValues(); ColumnBinding[] columnBindings = this.ColumnBindings(); for(int i = 0; i < columnBindings.Length; ++i) { ColumnBinding binding = columnBindings[i]; if (null != binding) { binding.ResetValue(); } } } } internal void CloseFromConnection() { if (null != _rowBinding) { _rowBinding.CloseFromConnection(); } Dispose(); } internal OleDbHResult CreateAccessor(UnsafeNativeMethods.IAccessor iaccessor, int flags) { Debug.Assert(null != _rowBinding, "no row binding"); Debug.Assert(null != _columnBindings, "no column bindings"); return _rowBinding.CreateAccessor(iaccessor, flags, _columnBindings); } public void Dispose() { _parameters = null; _dataReader = null; _columnBindings = null; RowBinding rowBinding = _rowBinding; _rowBinding = null; if (null != rowBinding) { rowBinding.Dispose(); } } internal void GuidKindName(Guid guid, int eKind, IntPtr propid) { tagDBCOLUMNACCESS[] dbcolumns = DBColumnAccess; dbcolumns[_index].columnid.uGuid = guid; dbcolumns[_index].columnid.eKind = eKind; dbcolumns[_index].columnid.ulPropid = propid; } internal void ParameterStatus(StringBuilder builder) { ColumnBinding[] columnBindings = ColumnBindings(); for(int i = 0; i < columnBindings.Length; ++i) { ODB.CommandParameterStatus(builder, i, columnBindings[i].StatusValue()); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml.Xsl.XsltOld { using System; using System.Diagnostics; using System.Xml; using System.Text; using System.Collections; using System.Globalization; internal abstract class SequentialOutput : RecordOutput { private const char s_Colon = ':'; private const char s_GreaterThan = '>'; private const char s_LessThan = '<'; private const char s_Space = ' '; private const char s_Quote = '\"'; private const char s_Semicolon = ';'; private const char s_NewLine = '\n'; private const char s_Return = '\r'; private const char s_Ampersand = '&'; private const string s_LessThanQuestion = "<?"; private const string s_QuestionGreaterThan = "?>"; private const string s_LessThanSlash = "</"; private const string s_SlashGreaterThan = " />"; private const string s_EqualQuote = "=\""; private const string s_DocType = "<!DOCTYPE "; private const string s_CommentBegin = "<!--"; private const string s_CommentEnd = "-->"; private const string s_CDataBegin = "<![CDATA["; private const string s_CDataEnd = "]]>"; private const string s_VersionAll = " version=\"1.0\""; private const string s_Standalone = " standalone=\""; private const string s_EncodingStart = " encoding=\""; private const string s_Public = "PUBLIC "; private const string s_System = "SYSTEM "; private const string s_Html = "html"; private const string s_QuoteSpace = "\" "; private const string s_CDataSplit = "]]]]><![CDATA[>"; private const string s_EnLessThan = "&lt;"; private const string s_EnGreaterThan = "&gt;"; private const string s_EnAmpersand = "&amp;"; private const string s_EnQuote = "&quot;"; private const string s_EnNewLine = "&#xA;"; private const string s_EnReturn = "&#xD;"; private const string s_EndOfLine = "\r\n"; private static char[] s_TextValueFind = new char[] { s_Ampersand, s_GreaterThan, s_LessThan }; private static string[] s_TextValueReplace = new string[] { s_EnAmpersand, s_EnGreaterThan, s_EnLessThan }; private static char[] s_XmlAttributeValueFind = new char[] { s_Ampersand, s_GreaterThan, s_LessThan, s_Quote, s_NewLine, s_Return }; private static string[] s_XmlAttributeValueReplace = new string[] { s_EnAmpersand, s_EnGreaterThan, s_EnLessThan, s_EnQuote, s_EnNewLine, s_EnReturn }; // Instance members private Processor _processor; protected Encoding encoding; private ArrayList _outputCache; private bool _firstLine = true; private bool _secondRoot; // Cached Output propertes: private XsltOutput _output; private bool _isHtmlOutput; private bool _isXmlOutput; private Hashtable _cdataElements; private bool _indentOutput; private bool _outputDoctype; private bool _outputXmlDecl; private bool _omitXmlDeclCalled; // Uri Escaping: private byte[] _byteBuffer; private Encoding _utf8Encoding; private XmlCharType _xmlCharType = XmlCharType.Instance; private void CacheOuptutProps(XsltOutput output) { _output = output; _isXmlOutput = _output.Method == XsltOutput.OutputMethod.Xml; _isHtmlOutput = _output.Method == XsltOutput.OutputMethod.Html; _cdataElements = _output.CDataElements; _indentOutput = _output.Indent; _outputDoctype = _output.DoctypeSystem != null || (_isHtmlOutput && _output.DoctypePublic != null); _outputXmlDecl = _isXmlOutput && !_output.OmitXmlDeclaration && !_omitXmlDeclCalled; } // // Constructor // internal SequentialOutput(Processor processor) { _processor = processor; CacheOuptutProps(processor.Output); } public void OmitXmlDecl() { _omitXmlDeclCalled = true; _outputXmlDecl = false; } // // Particular outputs // private void WriteStartElement(RecordBuilder record) { Debug.Assert(record.MainNode.NodeType == XmlNodeType.Element); BuilderInfo mainNode = record.MainNode; HtmlElementProps htmlProps = null; if (_isHtmlOutput) { if (mainNode.Prefix.Length == 0) { htmlProps = mainNode.htmlProps; if (htmlProps == null && mainNode.search) { htmlProps = HtmlElementProps.GetProps(mainNode.LocalName); } record.Manager.CurrentElementScope.HtmlElementProps = htmlProps; mainNode.IsEmptyTag = false; } } else if (_isXmlOutput) { if (mainNode.Depth == 0) { if ( _secondRoot && ( _output.DoctypeSystem != null || _output.Standalone ) ) { throw XsltException.Create(SR.Xslt_MultipleRoots); } _secondRoot = true; } } if (_outputDoctype) { WriteDoctype(mainNode); _outputDoctype = false; } if (_cdataElements != null && _cdataElements.Contains(new XmlQualifiedName(mainNode.LocalName, mainNode.NamespaceURI)) && _isXmlOutput) { record.Manager.CurrentElementScope.ToCData = true; } Indent(record); Write(s_LessThan); WriteName(mainNode.Prefix, mainNode.LocalName); WriteAttributes(record.AttributeList, record.AttributeCount, htmlProps); if (mainNode.IsEmptyTag) { Debug.Assert(!_isHtmlOutput || mainNode.Prefix != null, "Html can't have abbreviated elements"); Write(s_SlashGreaterThan); } else { Write(s_GreaterThan); } if (htmlProps != null && htmlProps.Head) { mainNode.Depth++; Indent(record); mainNode.Depth--; Write("<META http-equiv=\"Content-Type\" content=\""); Write(_output.MediaType); Write("; charset="); Write(this.encoding.WebName); Write("\">"); } } private void WriteTextNode(RecordBuilder record) { BuilderInfo mainNode = record.MainNode; OutputScope scope = record.Manager.CurrentElementScope; scope.Mixed = true; if (scope.HtmlElementProps != null && scope.HtmlElementProps.NoEntities) { // script or stile Write(mainNode.Value); } else if (scope.ToCData) { WriteCDataSection(mainNode.Value); } else { WriteTextNode(mainNode); } } private void WriteTextNode(BuilderInfo node) { for (int i = 0; i < node.TextInfoCount; i++) { string text = node.TextInfo[i]; if (text == null) { // disableEscaping marker i++; Debug.Assert(i < node.TextInfoCount, "disableEscaping marker can't be last TextInfo record"); Write(node.TextInfo[i]); } else { WriteWithReplace(text, s_TextValueFind, s_TextValueReplace); } } } private void WriteCDataSection(string value) { Write(s_CDataBegin); WriteCData(value); Write(s_CDataEnd); } private void WriteDoctype(BuilderInfo mainNode) { Debug.Assert(_outputDoctype == true, "It supposed to check this condition before actual call"); Debug.Assert(_output.DoctypeSystem != null || (_isHtmlOutput && _output.DoctypePublic != null), "We set outputDoctype == true only if"); Indent(0); Write(s_DocType); if (_isXmlOutput) { WriteName(mainNode.Prefix, mainNode.LocalName); } else { WriteName(string.Empty, "html"); } Write(s_Space); if (_output.DoctypePublic != null) { Write(s_Public); Write(s_Quote); Write(_output.DoctypePublic); Write(s_QuoteSpace); } else { Write(s_System); } if (_output.DoctypeSystem != null) { Write(s_Quote); Write(_output.DoctypeSystem); Write(s_Quote); } Write(s_GreaterThan); } private void WriteXmlDeclaration() { Debug.Assert(_outputXmlDecl == true, "It supposed to check this condition before actual call"); Debug.Assert(_isXmlOutput && !_output.OmitXmlDeclaration, "We set outputXmlDecl == true only if"); _outputXmlDecl = false; Indent(0); Write(s_LessThanQuestion); WriteName(string.Empty, "xml"); Write(s_VersionAll); if (this.encoding != null) { Write(s_EncodingStart); Write(this.encoding.WebName); Write(s_Quote); } if (_output.HasStandalone) { Write(s_Standalone); Write(_output.Standalone ? "yes" : "no"); Write(s_Quote); } Write(s_QuestionGreaterThan); } private void WriteProcessingInstruction(RecordBuilder record) { Indent(record); WriteProcessingInstruction(record.MainNode); } private void WriteProcessingInstruction(BuilderInfo node) { Write(s_LessThanQuestion); WriteName(node.Prefix, node.LocalName); Write(s_Space); Write(node.Value); if (_isHtmlOutput) { Write(s_GreaterThan); } else { Write(s_QuestionGreaterThan); } } private void WriteEndElement(RecordBuilder record) { BuilderInfo node = record.MainNode; HtmlElementProps htmlProps = record.Manager.CurrentElementScope.HtmlElementProps; if (htmlProps != null && htmlProps.Empty) { return; } Indent(record); Write(s_LessThanSlash); WriteName(record.MainNode.Prefix, record.MainNode.LocalName); Write(s_GreaterThan); } // // RecordOutput interface method implementation // public Processor.OutputResult RecordDone(RecordBuilder record) { if (_output.Method == XsltOutput.OutputMethod.Unknown) { if (!DecideDefaultOutput(record.MainNode)) { CacheRecord(record); } else { OutputCachedRecords(); OutputRecord(record); } } else { OutputRecord(record); } record.Reset(); return Processor.OutputResult.Continue; } public void TheEnd() { OutputCachedRecords(); Close(); } private bool DecideDefaultOutput(BuilderInfo node) { XsltOutput.OutputMethod method = XsltOutput.OutputMethod.Xml; switch (node.NodeType) { case XmlNodeType.Element: if (node.NamespaceURI.Length == 0 && string.Equals("html", node.LocalName, StringComparison.OrdinalIgnoreCase)) { method = XsltOutput.OutputMethod.Html; } break; case XmlNodeType.Text: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: if (_xmlCharType.IsOnlyWhitespace(node.Value)) { return false; } method = XsltOutput.OutputMethod.Xml; break; default: return false; } if (_processor.SetDefaultOutput(method)) { CacheOuptutProps(_processor.Output); } return true; } private void CacheRecord(RecordBuilder record) { if (_outputCache == null) { _outputCache = new ArrayList(); } _outputCache.Add(record.MainNode.Clone()); } private void OutputCachedRecords() { if (_outputCache == null) { return; } for (int record = 0; record < _outputCache.Count; record++) { Debug.Assert(_outputCache[record] is BuilderInfo); BuilderInfo info = (BuilderInfo)_outputCache[record]; OutputRecord(info); } _outputCache = null; } private void OutputRecord(RecordBuilder record) { BuilderInfo mainNode = record.MainNode; if (_outputXmlDecl) { WriteXmlDeclaration(); } switch (mainNode.NodeType) { case XmlNodeType.Element: WriteStartElement(record); break; case XmlNodeType.Text: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: WriteTextNode(record); break; case XmlNodeType.CDATA: Debug.Fail("Should never get here"); break; case XmlNodeType.EntityReference: Write(s_Ampersand); WriteName(mainNode.Prefix, mainNode.LocalName); Write(s_Semicolon); break; case XmlNodeType.ProcessingInstruction: WriteProcessingInstruction(record); break; case XmlNodeType.Comment: Indent(record); Write(s_CommentBegin); Write(mainNode.Value); Write(s_CommentEnd); break; case XmlNodeType.Document: break; case XmlNodeType.DocumentType: Write(mainNode.Value); break; case XmlNodeType.EndElement: WriteEndElement(record); break; default: break; } } private void OutputRecord(BuilderInfo node) { if (_outputXmlDecl) { WriteXmlDeclaration(); } Indent(0); // we can have only top level stuff here switch (node.NodeType) { case XmlNodeType.Element: Debug.Fail("Should never get here"); break; case XmlNodeType.Text: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: WriteTextNode(node); break; case XmlNodeType.CDATA: Debug.Fail("Should never get here"); break; case XmlNodeType.EntityReference: Write(s_Ampersand); WriteName(node.Prefix, node.LocalName); Write(s_Semicolon); break; case XmlNodeType.ProcessingInstruction: WriteProcessingInstruction(node); break; case XmlNodeType.Comment: Write(s_CommentBegin); Write(node.Value); Write(s_CommentEnd); break; case XmlNodeType.Document: break; case XmlNodeType.DocumentType: Write(node.Value); break; case XmlNodeType.EndElement: Debug.Fail("Should never get here"); break; default: break; } } // // Internal helpers // private void WriteName(string prefix, string name) { if (prefix != null && prefix.Length > 0) { Write(prefix); if (name != null && name.Length > 0) { Write(s_Colon); } else { return; } } Write(name); } private void WriteXmlAttributeValue(string value) { Debug.Assert(value != null); WriteWithReplace(value, s_XmlAttributeValueFind, s_XmlAttributeValueReplace); } private void WriteHtmlAttributeValue(string value) { Debug.Assert(value != null); int length = value.Length; int i = 0; while (i < length) { char ch = value[i]; i++; switch (ch) { case '&': if (i != length && value[i] == '{') { // &{ hasn't to be encoded in HTML output. Write(ch); } else { Write(s_EnAmpersand); } break; case '"': Write(s_EnQuote); break; default: Write(ch); break; } } } private void WriteHtmlUri(string value) { Debug.Assert(value != null); Debug.Assert(_isHtmlOutput); int length = value.Length; int i = 0; while (i < length) { char ch = value[i]; i++; switch (ch) { case '&': if (i != length && value[i] == '{') { // &{ hasn't to be encoded in HTML output. Write(ch); } else { Write(s_EnAmpersand); } break; case '"': Write(s_EnQuote); break; case '\n': Write(s_EnNewLine); break; case '\r': Write(s_EnReturn); break; default: if (127 < ch) { if (_utf8Encoding == null) { _utf8Encoding = Encoding.UTF8; _byteBuffer = new byte[_utf8Encoding.GetMaxByteCount(1)]; } int bytes = _utf8Encoding.GetBytes(value, i - 1, 1, _byteBuffer, 0); for (int j = 0; j < bytes; j++) { Write("%"); Write(((uint)_byteBuffer[j]).ToString("X2", CultureInfo.InvariantCulture)); } } else { Write(ch); } break; } } } private void WriteWithReplace(string value, char[] find, string[] replace) { Debug.Assert(value != null); Debug.Assert(find.Length == replace.Length); int length = value.Length; int pos = 0; while (pos < length) { int newPos = value.IndexOfAny(find, pos); if (newPos == -1) { break; // not found; } // output clean leading part of the string while (pos < newPos) { Write(value[pos]); pos++; } // output replacement char badChar = value[pos]; int i; for (i = find.Length - 1; 0 <= i; i--) { if (find[i] == badChar) { Write(replace[i]); break; } } Debug.Assert(0 <= i, "find char wasn't realy find"); pos++; } // output rest of the string if (pos == 0) { Write(value); } else { while (pos < length) { Write(value[pos]); pos++; } } } private void WriteCData(string value) { Debug.Assert(value != null); Write(value.Replace(s_CDataEnd, s_CDataSplit)); } private void WriteAttributes(ArrayList list, int count, HtmlElementProps htmlElementsProps) { Debug.Assert(count <= list.Count); for (int attrib = 0; attrib < count; attrib++) { Debug.Assert(list[attrib] is BuilderInfo); BuilderInfo attribute = (BuilderInfo)list[attrib]; string attrValue = attribute.Value; bool abr = false, uri = false; { if (htmlElementsProps != null && attribute.Prefix.Length == 0) { HtmlAttributeProps htmlAttrProps = attribute.htmlAttrProps; if (htmlAttrProps == null && attribute.search) { htmlAttrProps = HtmlAttributeProps.GetProps(attribute.LocalName); } if (htmlAttrProps != null) { abr = htmlElementsProps.AbrParent && htmlAttrProps.Abr; uri = htmlElementsProps.UriParent && (htmlAttrProps.Uri || htmlElementsProps.NameParent && htmlAttrProps.Name ); } } } Write(s_Space); WriteName(attribute.Prefix, attribute.LocalName); if (abr && string.Equals(attribute.LocalName, attrValue, StringComparison.OrdinalIgnoreCase)) { // Since the name of the attribute = the value of the attribute, // this is a boolean attribute whose value should be suppressed continue; } Write(s_EqualQuote); if (uri) { WriteHtmlUri(attrValue); } else if (_isHtmlOutput) { WriteHtmlAttributeValue(attrValue); } else { WriteXmlAttributeValue(attrValue); } Write(s_Quote); } } private void Indent(RecordBuilder record) { if (!record.Manager.CurrentElementScope.Mixed) { Indent(record.MainNode.Depth); } } private void Indent(int depth) { if (_firstLine) { if (_indentOutput) { _firstLine = false; } return; // preven leading CRLF } Write(s_EndOfLine); for (int i = 2 * depth; 0 < i; i--) { Write(" "); } } // // Abstract methods internal abstract void Write(char outputChar); internal abstract void Write(string outputText); internal abstract void Close(); } }
using System; using System.Linq; using System.Threading.Tasks; using Foundation; using MobileCoreServices; using UIKit; using Producer.Domain; using Producer.Shared; namespace Producer.iOS { public partial class ComposeVc : UIViewController { NSUrl filePath; bool isValidMediaItem; bool initializedVeiw; // TODO: Make this an object (string UTType, string UTSubtype, string Filename) utiData; AvContent avContent; public ComposeVc (IntPtr handle) : base (handle) { } public void SetData (NSUrl url) { initializedVeiw = false; filePath = url; utiData = filePath.GetAvUtiConformance (); } public void SetData (AvContent content) { initializedVeiw = false; avContent = content; //filePath = url; //utiData = filePath.GetAvUtiConformance (); } public override void ViewDidLoad () { base.ViewDidLoad (); createButton.Layer.CornerRadius = 4; fileTypeTextField.Enabled = false; } public override void ViewDidAppear (bool animated) { base.ViewDidAppear (animated); if (!initializedVeiw) { if (!string.IsNullOrEmpty (utiData.UTType)) { initializeViewForUtiData (); } else if (avContent != null) { initializeViewForEditingAvContent (); } } } public override void ViewDidDisappear (bool animated) { utiData = (null, null, null); filePath = null; avContent = null; initializedVeiw = false; isValidMediaItem = false; // TODO: make sure this isn't called whien displaying a dialog base.ViewDidDisappear (animated); } partial void cancelClicked (NSObject sender) { if (avContent != null) // editing existing item { DismissViewController (true, null); } else // creating new draft { Log.Debug ($"Deleting local asset at: {filePath.Path}"); NSFileManager.DefaultManager.Remove (filePath.Path, out NSError error); if (error != null) { Log.Debug ($"ERROR: {error}\n{error.Description}"); } NavigationController.PopViewController (true); } } partial void createButtonClicked (NSObject sender) { createButton.Enabled = false; fileNameTextField.Enabled = false; fileDisplayNameTextField.Enabled = false; descriptionTextField.Enabled = false; if (avContent != null) // editing existing item { if (updateAvContentItem ()) { //Settings.LastAvContentDescription = avContent.Description ?? string.Empty; Task.Run (async () => { await ContentClient.Shared.UpdateAvContent (avContent); BeginInvokeOnMainThread (() => DismissViewController (true, null)); }); } } else // creating new draft { avContent = new AvContent { Name = fileNameTextField.Text, DisplayName = fileDisplayNameTextField.Text, Description = descriptionTextField.Text, ProducerId = ProducerClient.Shared.User.Id, ContentType = utiData.UTType == UTType.Audio ? AvContentTypes.Audio : utiData.UTType == UTType.Movie ? AvContentTypes.Video : AvContentTypes.Unknown }; UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true; Task.Run (async () => { avContent = await ContentClient.Shared.CreateAvContent (avContent); var storageToken = await ProducerClient.Shared.GetStorageToken (avContent); if (storageToken != null) { // store the inbox path incase upload fails, is interrupted, app // crashes, etc. and we need to reinitialize the upload later avContent.LocalInboxPath = filePath.Path; var success = await AzureStorageClient.Shared.AddNewFileAsync (avContent, storageToken); BeginInvokeOnMainThread (() => { UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; if (success) { Settings.LastAvContentDescription = avContent.Description ?? string.Empty; NavigationController.PopViewController (true); } else { // TODO: show failed/retry alert } //UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; }); } else { BeginInvokeOnMainThread (() => { UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; }); } }); } } bool updateAvContentItem () { bool changed = false; if (!avContent.DisplayName.Equals (fileDisplayNameTextField.Text, StringComparison.OrdinalIgnoreCase)) { avContent.DisplayName = fileDisplayNameTextField.Text; changed = true; } if (!avContent.Description.Equals (descriptionTextField.Text, StringComparison.OrdinalIgnoreCase)) { avContent.Description = descriptionTextField.Text; changed = true; } return changed; } void initializeViewForEditingAvContent () { initializedVeiw = true; Title = avContent.DisplayName; fileNameTextField.Text = avContent.Name; fileDisplayNameTextField.Text = avContent.DisplayName; fileTypeTextField.Text = avContent.ContentType == AvContentTypes.Audio ? "Streaming audio" : avContent.ContentType == AvContentTypes.Video ? "Streaming video" : "unknown"; descriptionTextField.Text = avContent.Description; createButton.SetTitle ("Update Item", UIControlState.Normal); } void initializeViewForUtiData () { initializedVeiw = true; if (utiData.Item1 == UTType.Audio) { if (utiData.Item2 == UTType.Audio) { showUnsupportedAlert ("Unsupported audio file", "The folowing formats are currently supported:\nmp3, wav"); } else { setInitialFormData (utiData); } } else if (utiData.Item1 == UTType.Movie) { if (utiData.Item2 == UTType.Movie) { showUnsupportedAlert ("Unsupported movie file", "The folowing formats are currently supported:\nmp4, mov"); } else { setInitialFormData (utiData); } } else if (utiData.Item1 == UTType.PlainText) { showUnsupportedAlert ("File import failed", $"{utiData.Item2}\n\nThe folowing formats are currently supported:\nmp3, wav, mp4, mov"); } createButton.Enabled = isValidMediaItem; } void setInitialFormData ((string, string, string) data) { isValidMediaItem = true; var cleanName = data.Item3.SplitOnLast ('.').FirstOrDefault (); Title = cleanName; fileNameTextField.Text = data.Item3; fileDisplayNameTextField.Text = cleanName; fileTypeTextField.Text = data.Item2; descriptionTextField.Text = Settings.LastAvContentDescription; } void showUnsupportedAlert (string title, string message) { var alertController = UIAlertController.Create (title, message, UIAlertControllerStyle.Alert); alertController.AddAction (UIAlertAction.Create ("Okay", UIAlertActionStyle.Default, handleUnsupportedAlertAction)); PresentViewController (alertController, true, null); } void handleUnsupportedAlertAction (UIAlertAction obj) => DismissViewController (true, handleUnsupportedAlertActionDismissedViewController); void handleUnsupportedAlertActionDismissedViewController () => NavigationController.PopViewController (true); void showUploadFailedAlert (string title, string message) { var alertController = UIAlertController.Create (title, message, UIAlertControllerStyle.Alert); alertController.AddAction (UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, null)); alertController.AddAction (UIAlertAction.Create ("Retry", UIAlertActionStyle.Default, null)); PresentViewController (alertController, true, null); } } }
// MIT License // // Copyright (c) 2009-2017 Luca Piccioni // // 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. // // This file is automatically generated #pragma warning disable 649, 1572, 1573 // ReSharper disable RedundantUsingDirective using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Text; using Khronos; // ReSharper disable CheckNamespace // ReSharper disable InconsistentNaming // ReSharper disable JoinDeclarationAndInitializer namespace OpenGL { public partial class Wgl { /// <summary> /// [WGL] Value of WGL_BIND_TO_TEXTURE_RGB_ARB symbol. /// </summary> [RequiredByFeature("WGL_ARB_render_texture")] public const int BIND_TO_TEXTURE_RGB_ARB = 0x2070; /// <summary> /// [WGL] Value of WGL_BIND_TO_TEXTURE_RGBA_ARB symbol. /// </summary> [RequiredByFeature("WGL_ARB_render_texture")] public const int BIND_TO_TEXTURE_RGBA_ARB = 0x2071; /// <summary> /// [WGL] Value of WGL_TEXTURE_FORMAT_ARB symbol. /// </summary> [RequiredByFeature("WGL_ARB_render_texture")] public const int TEXTURE_FORMAT_ARB = 0x2072; /// <summary> /// [WGL] Value of WGL_TEXTURE_TARGET_ARB symbol. /// </summary> [RequiredByFeature("WGL_ARB_render_texture")] public const int TEXTURE_TARGET_ARB = 0x2073; /// <summary> /// [WGL] Value of WGL_MIPMAP_TEXTURE_ARB symbol. /// </summary> [RequiredByFeature("WGL_ARB_render_texture")] public const int MIPMAP_TEXTURE_ARB = 0x2074; /// <summary> /// [WGL] Value of WGL_TEXTURE_RGB_ARB symbol. /// </summary> [RequiredByFeature("WGL_ARB_render_texture")] public const int TEXTURE_RGB_ARB = 0x2075; /// <summary> /// [WGL] Value of WGL_TEXTURE_RGBA_ARB symbol. /// </summary> [RequiredByFeature("WGL_ARB_render_texture")] public const int TEXTURE_RGBA_ARB = 0x2076; /// <summary> /// [WGL] Value of WGL_NO_TEXTURE_ARB symbol. /// </summary> [RequiredByFeature("WGL_ARB_render_texture")] public const int NO_TEXTURE_ARB = 0x2077; /// <summary> /// [WGL] Value of WGL_TEXTURE_CUBE_MAP_ARB symbol. /// </summary> [RequiredByFeature("WGL_ARB_render_texture")] public const int TEXTURE_CUBE_MAP_ARB = 0x2078; /// <summary> /// [WGL] Value of WGL_TEXTURE_1D_ARB symbol. /// </summary> [RequiredByFeature("WGL_ARB_render_texture")] public const int TEXTURE_1D_ARB = 0x2079; /// <summary> /// [WGL] Value of WGL_TEXTURE_2D_ARB symbol. /// </summary> [RequiredByFeature("WGL_ARB_render_texture")] public const int TEXTURE_2D_ARB = 0x207A; /// <summary> /// [WGL] Value of WGL_MIPMAP_LEVEL_ARB symbol. /// </summary> [RequiredByFeature("WGL_ARB_render_texture")] public const int MIPMAP_LEVEL_ARB = 0x207B; /// <summary> /// [WGL] Value of WGL_CUBE_MAP_FACE_ARB symbol. /// </summary> [RequiredByFeature("WGL_ARB_render_texture")] public const int CUBE_MAP_FACE_ARB = 0x207C; /// <summary> /// [WGL] Value of WGL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB symbol. /// </summary> [RequiredByFeature("WGL_ARB_render_texture")] public const int TEXTURE_CUBE_MAP_POSITIVE_X_ARB = 0x207D; /// <summary> /// [WGL] Value of WGL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB symbol. /// </summary> [RequiredByFeature("WGL_ARB_render_texture")] public const int TEXTURE_CUBE_MAP_NEGATIVE_X_ARB = 0x207E; /// <summary> /// [WGL] Value of WGL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB symbol. /// </summary> [RequiredByFeature("WGL_ARB_render_texture")] public const int TEXTURE_CUBE_MAP_POSITIVE_Y_ARB = 0x207F; /// <summary> /// [WGL] Value of WGL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB symbol. /// </summary> [RequiredByFeature("WGL_ARB_render_texture")] public const int TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB = 0x2080; /// <summary> /// [WGL] Value of WGL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB symbol. /// </summary> [RequiredByFeature("WGL_ARB_render_texture")] public const int TEXTURE_CUBE_MAP_POSITIVE_Z_ARB = 0x2081; /// <summary> /// [WGL] Value of WGL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB symbol. /// </summary> [RequiredByFeature("WGL_ARB_render_texture")] public const int TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB = 0x2082; /// <summary> /// [WGL] Value of WGL_FRONT_LEFT_ARB symbol. /// </summary> [RequiredByFeature("WGL_ARB_render_texture")] public const int FRONT_LEFT_ARB = 0x2083; /// <summary> /// [WGL] Value of WGL_FRONT_RIGHT_ARB symbol. /// </summary> [RequiredByFeature("WGL_ARB_render_texture")] public const int FRONT_RIGHT_ARB = 0x2084; /// <summary> /// [WGL] Value of WGL_BACK_LEFT_ARB symbol. /// </summary> [RequiredByFeature("WGL_ARB_render_texture")] public const int BACK_LEFT_ARB = 0x2085; /// <summary> /// [WGL] Value of WGL_BACK_RIGHT_ARB symbol. /// </summary> [RequiredByFeature("WGL_ARB_render_texture")] public const int BACK_RIGHT_ARB = 0x2086; /// <summary> /// [WGL] Value of WGL_AUX0_ARB symbol. /// </summary> [RequiredByFeature("WGL_ARB_render_texture")] public const int AUX0_ARB = 0x2087; /// <summary> /// [WGL] Value of WGL_AUX1_ARB symbol. /// </summary> [RequiredByFeature("WGL_ARB_render_texture")] public const int AUX1_ARB = 0x2088; /// <summary> /// [WGL] Value of WGL_AUX2_ARB symbol. /// </summary> [RequiredByFeature("WGL_ARB_render_texture")] public const int AUX2_ARB = 0x2089; /// <summary> /// [WGL] Value of WGL_AUX3_ARB symbol. /// </summary> [RequiredByFeature("WGL_ARB_render_texture")] public const int AUX3_ARB = 0x208A; /// <summary> /// [WGL] Value of WGL_AUX4_ARB symbol. /// </summary> [RequiredByFeature("WGL_ARB_render_texture")] public const int AUX4_ARB = 0x208B; /// <summary> /// [WGL] Value of WGL_AUX5_ARB symbol. /// </summary> [RequiredByFeature("WGL_ARB_render_texture")] public const int AUX5_ARB = 0x208C; /// <summary> /// [WGL] Value of WGL_AUX6_ARB symbol. /// </summary> [RequiredByFeature("WGL_ARB_render_texture")] public const int AUX6_ARB = 0x208D; /// <summary> /// [WGL] Value of WGL_AUX7_ARB symbol. /// </summary> [RequiredByFeature("WGL_ARB_render_texture")] public const int AUX7_ARB = 0x208E; /// <summary> /// [WGL] Value of WGL_AUX8_ARB symbol. /// </summary> [RequiredByFeature("WGL_ARB_render_texture")] public const int AUX8_ARB = 0x208F; /// <summary> /// [WGL] Value of WGL_AUX9_ARB symbol. /// </summary> [RequiredByFeature("WGL_ARB_render_texture")] public const int AUX9_ARB = 0x2090; /// <summary> /// [WGL] wglBindTexImageARB: Binding for wglBindTexImageARB. /// </summary> /// <param name="hPbuffer"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="iBuffer"> /// A <see cref="T:int"/>. /// </param> [RequiredByFeature("WGL_ARB_render_texture")] public static bool BindTexImageARB(IntPtr hPbuffer, int iBuffer) { bool retValue; Debug.Assert(Delegates.pwglBindTexImageARB != null, "pwglBindTexImageARB not implemented"); retValue = Delegates.pwglBindTexImageARB(hPbuffer, iBuffer); LogCommand("wglBindTexImageARB", retValue, hPbuffer, iBuffer ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [WGL] wglReleaseTexImageARB: Binding for wglReleaseTexImageARB. /// </summary> /// <param name="hPbuffer"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="iBuffer"> /// A <see cref="T:int"/>. /// </param> [RequiredByFeature("WGL_ARB_render_texture")] public static bool ReleaseTexImageARB(IntPtr hPbuffer, int iBuffer) { bool retValue; Debug.Assert(Delegates.pwglReleaseTexImageARB != null, "pwglReleaseTexImageARB not implemented"); retValue = Delegates.pwglReleaseTexImageARB(hPbuffer, iBuffer); LogCommand("wglReleaseTexImageARB", retValue, hPbuffer, iBuffer ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [WGL] wglSetPbufferAttribARB: Binding for wglSetPbufferAttribARB. /// </summary> /// <param name="hPbuffer"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="piAttribList"> /// A <see cref="T:int[]"/>. /// </param> [RequiredByFeature("WGL_ARB_render_texture")] public static bool SetPbufferAttribARB(IntPtr hPbuffer, int[] piAttribList) { bool retValue; unsafe { fixed (int* p_piAttribList = piAttribList) { Debug.Assert(Delegates.pwglSetPbufferAttribARB != null, "pwglSetPbufferAttribARB not implemented"); retValue = Delegates.pwglSetPbufferAttribARB(hPbuffer, p_piAttribList); LogCommand("wglSetPbufferAttribARB", retValue, hPbuffer, piAttribList ); } } DebugCheckErrors(retValue); return (retValue); } internal static unsafe partial class Delegates { [RequiredByFeature("WGL_ARB_render_texture")] [SuppressUnmanagedCodeSecurity] internal delegate bool wglBindTexImageARB(IntPtr hPbuffer, int iBuffer); [RequiredByFeature("WGL_ARB_render_texture")] internal static wglBindTexImageARB pwglBindTexImageARB; [RequiredByFeature("WGL_ARB_render_texture")] [SuppressUnmanagedCodeSecurity] internal delegate bool wglReleaseTexImageARB(IntPtr hPbuffer, int iBuffer); [RequiredByFeature("WGL_ARB_render_texture")] internal static wglReleaseTexImageARB pwglReleaseTexImageARB; [RequiredByFeature("WGL_ARB_render_texture")] [SuppressUnmanagedCodeSecurity] internal delegate bool wglSetPbufferAttribARB(IntPtr hPbuffer, int* piAttribList); [RequiredByFeature("WGL_ARB_render_texture")] internal static wglSetPbufferAttribARB pwglSetPbufferAttribARB; } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using Avalonia.Input; using Avalonia.Metadata; namespace Avalonia.Controls.Primitives { public class Track : Control { public static readonly DirectProperty<Track, double> MinimumProperty = RangeBase.MinimumProperty.AddOwner<Track>(o => o.Minimum, (o, v) => o.Minimum = v); public static readonly DirectProperty<Track, double> MaximumProperty = RangeBase.MaximumProperty.AddOwner<Track>(o => o.Maximum, (o, v) => o.Maximum = v); public static readonly DirectProperty<Track, double> ValueProperty = RangeBase.ValueProperty.AddOwner<Track>(o => o.Value, (o, v) => o.Value = v); public static readonly StyledProperty<double> ViewportSizeProperty = ScrollBar.ViewportSizeProperty.AddOwner<Track>(); public static readonly StyledProperty<Orientation> OrientationProperty = ScrollBar.OrientationProperty.AddOwner<Track>(); public static readonly StyledProperty<Thumb> ThumbProperty = AvaloniaProperty.Register<Track, Thumb>(nameof(Thumb)); public static readonly StyledProperty<Button> IncreaseButtonProperty = AvaloniaProperty.Register<Track, Button>(nameof(IncreaseButton)); public static readonly StyledProperty<Button> DecreaseButtonProperty = AvaloniaProperty.Register<Track, Button>(nameof(DecreaseButton)); private double _minimum; private double _maximum = 100.0; private double _value; static Track() { ThumbProperty.Changed.AddClassHandler<Track>(x => x.ThumbChanged); IncreaseButtonProperty.Changed.AddClassHandler<Track>(x => x.ButtonChanged); DecreaseButtonProperty.Changed.AddClassHandler<Track>(x => x.ButtonChanged); AffectsArrange(MinimumProperty, MaximumProperty, ValueProperty, OrientationProperty); } public double Minimum { get { return _minimum; } set { SetAndRaise(MinimumProperty, ref _minimum, value); } } public double Maximum { get { return _maximum; } set { SetAndRaise(MaximumProperty, ref _maximum, value); } } public double Value { get { return _value; } set { SetAndRaise(ValueProperty, ref _value, value); } } public double ViewportSize { get { return GetValue(ViewportSizeProperty); } set { SetValue(ViewportSizeProperty, value); } } public Orientation Orientation { get { return GetValue(OrientationProperty); } set { SetValue(OrientationProperty, value); } } [Content] public Thumb Thumb { get { return GetValue(ThumbProperty); } set { SetValue(ThumbProperty, value); } } public Button IncreaseButton { get { return GetValue(IncreaseButtonProperty); } set { SetValue(IncreaseButtonProperty, value); } } public Button DecreaseButton { get { return GetValue(DecreaseButtonProperty); } set { SetValue(DecreaseButtonProperty, value); } } protected override Size MeasureOverride(Size availableSize) { var thumb = Thumb; if (thumb != null) { thumb.Measure(availableSize); if (Orientation == Orientation.Horizontal) { return new Size(0, thumb.DesiredSize.Height); } else { return new Size(thumb.DesiredSize.Width, 0); } } return base.MeasureOverride(availableSize); } protected override Size ArrangeOverride(Size finalSize) { var thumb = Thumb; var increaseButton = IncreaseButton; var decreaseButton = DecreaseButton; var range = Maximum - Minimum; var offset = Math.Min(Value - Minimum, range); var viewportSize = ViewportSize; var extent = range + viewportSize; if (Orientation == Orientation.Horizontal) { double thumbWidth = 0; if (double.IsNaN(viewportSize)) { thumbWidth = thumb?.DesiredSize.Width ?? 0; } else if (extent > 0) { thumbWidth = finalSize.Width * viewportSize / extent; } var remaining = finalSize.Width - thumbWidth; var firstWidth = range <= 0 ? 0 : remaining * offset / range; if (decreaseButton != null) { decreaseButton.Arrange(new Rect(0, 0, firstWidth, finalSize.Height)); } if (thumb != null) { thumb.Arrange(new Rect(firstWidth, 0, thumbWidth, finalSize.Height)); } if (increaseButton != null) { increaseButton.Arrange(new Rect( firstWidth + thumbWidth, 0, Math.Max(0, remaining - firstWidth), finalSize.Height)); } } else { double thumbHeight = 0; if (double.IsNaN(viewportSize)) { thumbHeight = thumb?.DesiredSize.Height ?? 0; } else if (extent > 0) { thumbHeight = finalSize.Height * viewportSize / extent; } var remaining = finalSize.Height - thumbHeight; var firstHeight = range <= 0 ? 0 : remaining * offset / range; if (decreaseButton != null) { decreaseButton.Arrange(new Rect(0, 0, finalSize.Width, firstHeight)); } if (thumb != null) { thumb.Arrange(new Rect(0, firstHeight, finalSize.Width, thumbHeight)); } if (increaseButton != null) { increaseButton.Arrange(new Rect( 0, firstHeight + thumbHeight, finalSize.Width, Math.Max(remaining - firstHeight, 0))); } } return finalSize; } private void ThumbChanged(AvaloniaPropertyChangedEventArgs e) { var oldThumb = (Thumb)e.OldValue; var newThumb = (Thumb)e.NewValue; if (oldThumb != null) { oldThumb.DragDelta -= ThumbDragged; LogicalChildren.Remove(oldThumb); VisualChildren.Remove(oldThumb); } if (newThumb != null) { newThumb.DragDelta += ThumbDragged; LogicalChildren.Add(newThumb); VisualChildren.Add(newThumb); } } private void ButtonChanged(AvaloniaPropertyChangedEventArgs e) { var oldButton = (Button)e.OldValue; var newButton = (Button)e.NewValue; if (oldButton != null) { LogicalChildren.Remove(oldButton); VisualChildren.Remove(oldButton); } if (newButton != null) { LogicalChildren.Add(newButton); VisualChildren.Add(newButton); } } private void ThumbDragged(object sender, VectorEventArgs e) { double range = Maximum - Minimum; double value = Value; double offset; if (Orientation == Orientation.Horizontal) { offset = e.Vector.X / ((Bounds.Size.Width - Thumb.Bounds.Size.Width) / range); } else { offset = e.Vector.Y * (range / (Bounds.Size.Height - Thumb.Bounds.Size.Height)); } if (!double.IsNaN(offset) && !double.IsInfinity(offset)) { value += offset; value = Math.Max(value, Minimum); value = Math.Min(value, Maximum); Value = value; } } } }
using System; using System.Runtime.InteropServices; using System.Collections; using System.Collections.Generic; using System.Security; using SFML.Window; namespace SFML { namespace Graphics { //////////////////////////////////////////////////////////// /// <summary> /// Target for off-screen 2D rendering into an texture /// </summary> //////////////////////////////////////////////////////////// public class RenderTexture : ObjectBase, RenderTarget { //////////////////////////////////////////////////////////// /// <summary> /// Create the render-texture with the given dimensions /// </summary> /// <param name="width">Width of the render-texture</param> /// <param name="height">Height of the render-texture</param> //////////////////////////////////////////////////////////// public RenderTexture(uint width, uint height) : this(width, height, false) { } //////////////////////////////////////////////////////////// /// <summary> /// Create the render-texture with the given dimensions and /// an optional depth-buffer attached /// </summary> /// <param name="width">Width of the render-texture</param> /// <param name="height">Height of the render-texture</param> /// <param name="depthBuffer">Do you want a depth-buffer attached?</param> //////////////////////////////////////////////////////////// public RenderTexture(uint width, uint height, bool depthBuffer) : base(sfRenderTexture_create(width, height, depthBuffer)) { myDefaultView = new View(sfRenderTexture_getDefaultView(CPointer)); myTexture = new Texture(sfRenderTexture_getTexture(CPointer)); GC.SuppressFinalize(myDefaultView); GC.SuppressFinalize(myTexture); } //////////////////////////////////////////////////////////// /// <summary> /// Activate of deactivate the render texture as the current target /// for rendering /// </summary> /// <param name="active">True to activate, false to deactivate (true by default)</param> /// <returns>True if operation was successful, false otherwise</returns> //////////////////////////////////////////////////////////// public bool SetActive(bool active) { return sfRenderTexture_setActive(CPointer, active); } //////////////////////////////////////////////////////////// /// <summary> /// Size of the rendering region of the render texture /// </summary> //////////////////////////////////////////////////////////// public Vector2u Size { get { return sfRenderTexture_getSize(CPointer); } } //////////////////////////////////////////////////////////// /// <summary> /// Default view of the render texture /// </summary> //////////////////////////////////////////////////////////// public View DefaultView { get {return myDefaultView;} } //////////////////////////////////////////////////////////// /// <summary> /// Return the current active view /// </summary> /// <returns>The current view</returns> //////////////////////////////////////////////////////////// public View GetView() { return new View(sfRenderTexture_getView(CPointer)); } //////////////////////////////////////////////////////////// /// <summary> /// Change the current active view /// </summary> /// <param name="view">New view</param> //////////////////////////////////////////////////////////// public void SetView(View view) { sfRenderTexture_setView(CPointer, view.CPointer); } //////////////////////////////////////////////////////////// /// <summary> /// Get the viewport of a view applied to this target /// </summary> /// <param name="view">Target view</param> /// <returns>Viewport rectangle, expressed in pixels in the current target</returns> //////////////////////////////////////////////////////////// public IntRect GetViewport(View view) { return sfRenderTexture_getViewport(CPointer, view.CPointer); } //////////////////////////////////////////////////////////// /// <summary> /// Convert a point from target coordinates to world /// coordinates, using the current view /// /// This function is an overload of the MapPixelToCoords /// function that implicitely uses the current view. /// It is equivalent to: /// target.MapPixelToCoords(point, target.GetView()); /// </summary> /// <param name="point">Pixel to convert</param> /// <returns>The converted point, in "world" coordinates</returns> //////////////////////////////////////////////////////////// public Vector2f MapPixelToCoords(Vector2i point) { return MapPixelToCoords(point, GetView()); } //////////////////////////////////////////////////////////// /// <summary> /// Convert a point from target coordinates to world coordinates /// /// This function finds the 2D position that matches the /// given pixel of the render-target. In other words, it does /// the inverse of what the graphics card does, to find the /// initial position of a rendered pixel. /// /// Initially, both coordinate systems (world units and target pixels) /// match perfectly. But if you define a custom view or resize your /// render-target, this assertion is not true anymore, ie. a point /// located at (10, 50) in your render-target may map to the point /// (150, 75) in your 2D world -- if the view is translated by (140, 25). /// /// For render-windows, this function is typically used to find /// which point (or object) is located below the mouse cursor. /// /// This version uses a custom view for calculations, see the other /// overload of the function if you want to use the current view of the /// render-target. /// </summary> /// <param name="point">Pixel to convert</param> /// <param name="view">The view to use for converting the point</param> /// <returns>The converted point, in "world" coordinates</returns> //////////////////////////////////////////////////////////// public Vector2f MapPixelToCoords(Vector2i point, View view) { return sfRenderTexture_mapPixelToCoords(CPointer, point, view != null ? view.CPointer : IntPtr.Zero); } //////////////////////////////////////////////////////////// /// <summary> /// Convert a point from world coordinates to target /// coordinates, using the current view /// /// This function is an overload of the mapCoordsToPixel /// function that implicitely uses the current view. /// It is equivalent to: /// target.MapCoordsToPixel(point, target.GetView()); /// </summary> /// <param name="point">Point to convert</param> /// <returns>The converted point, in target coordinates (pixels)</returns> //////////////////////////////////////////////////////////// public Vector2i MapCoordsToPixel(Vector2f point) { return MapCoordsToPixel(point, GetView()); } //////////////////////////////////////////////////////////// /// <summary> /// Convert a point from world coordinates to target coordinates /// /// This function finds the pixel of the render-target that matches /// the given 2D point. In other words, it goes through the same process /// as the graphics card, to compute the final position of a rendered point. /// /// Initially, both coordinate systems (world units and target pixels) /// match perfectly. But if you define a custom view or resize your /// render-target, this assertion is not true anymore, ie. a point /// located at (150, 75) in your 2D world may map to the pixel /// (10, 50) of your render-target -- if the view is translated by (140, 25). /// /// This version uses a custom view for calculations, see the other /// overload of the function if you want to use the current view of the /// render-target. /// </summary> /// <param name="point">Point to convert</param> /// <param name="view">The view to use for converting the point</param> /// <returns>The converted point, in target coordinates (pixels)</returns> //////////////////////////////////////////////////////////// public Vector2i MapCoordsToPixel(Vector2f point, View view) { return sfRenderTexture_mapCoordsToPixel(CPointer, point, view != null ? view.CPointer : IntPtr.Zero); } //////////////////////////////////////////////////////////// /// <summary> /// Clear the entire render texture with black color /// </summary> //////////////////////////////////////////////////////////// public void Clear() { sfRenderTexture_clear(CPointer, Color.Black); } //////////////////////////////////////////////////////////// /// <summary> /// Clear the entire render texture with a single color /// </summary> /// <param name="color">Color to use to clear the texture</param> //////////////////////////////////////////////////////////// public void Clear(Color color) { sfRenderTexture_clear(CPointer, color); } //////////////////////////////////////////////////////////// /// <summary> /// Update the contents of the target texture /// </summary> //////////////////////////////////////////////////////////// public void Display() { sfRenderTexture_display(CPointer); } //////////////////////////////////////////////////////////// /// <summary> /// Target texture of the render texture /// </summary> //////////////////////////////////////////////////////////// public Texture Texture { get { return myTexture; } } //////////////////////////////////////////////////////////// /// <summary> /// Control the smooth filter /// </summary> //////////////////////////////////////////////////////////// public bool Smooth { get { return sfRenderTexture_isSmooth(CPointer); } set { sfRenderTexture_setSmooth(CPointer, value); } } //////////////////////////////////////////////////////////// /// <summary> /// Draw a drawable object to the render-target, with default render states /// </summary> /// <param name="drawable">Object to draw</param> //////////////////////////////////////////////////////////// public void Draw(Drawable drawable) { Draw(drawable, RenderStates.Default); } //////////////////////////////////////////////////////////// /// <summary> /// Draw a drawable object to the render-target /// </summary> /// <param name="drawable">Object to draw</param> /// <param name="states">Render states to use for drawing</param> //////////////////////////////////////////////////////////// public void Draw(Drawable drawable, RenderStates states) { drawable.Draw(this, states); } //////////////////////////////////////////////////////////// /// <summary> /// Draw primitives defined by an array of vertices, with default render states /// </summary> /// <param name="vertices">Pointer to the vertices</param> /// <param name="type">Type of primitives to draw</param> //////////////////////////////////////////////////////////// public void Draw(Vertex[] vertices, PrimitiveType type) { Draw(vertices, type, RenderStates.Default); } //////////////////////////////////////////////////////////// /// <summary> /// Draw primitives defined by an array of vertices /// </summary> /// <param name="vertices">Pointer to the vertices</param> /// <param name="type">Type of primitives to draw</param> /// <param name="states">Render states to use for drawing</param> //////////////////////////////////////////////////////////// public void Draw(Vertex[] vertices, PrimitiveType type, RenderStates states) { Draw(vertices, 0, (uint)vertices.Length, type, states); } //////////////////////////////////////////////////////////// /// <summary> /// Draw primitives defined by a sub-array of vertices, with default render states /// </summary> /// <param name="vertices">Array of vertices to draw</param> /// <param name="start">Index of the first vertex to draw in the array</param> /// <param name="count">Number of vertices to draw</param> /// <param name="type">Type of primitives to draw</param> //////////////////////////////////////////////////////////// public void Draw(Vertex[] vertices, uint start, uint count, PrimitiveType type) { Draw(vertices, start, count, type, RenderStates.Default); } //////////////////////////////////////////////////////////// /// <summary> /// Draw primitives defined by a sub-array of vertices /// </summary> /// <param name="vertices">Pointer to the vertices</param> /// <param name="start">Index of the first vertex to use in the array</param> /// <param name="count">Number of vertices to draw</param> /// <param name="type">Type of primitives to draw</param> /// <param name="states">Render states to use for drawing</param> //////////////////////////////////////////////////////////// public void Draw(Vertex[] vertices, uint start, uint count, PrimitiveType type, RenderStates states) { RenderStates.MarshalData marshaledStates = states.Marshal(); unsafe { fixed (Vertex* vertexPtr = vertices) { sfRenderTexture_drawPrimitives(CPointer, vertexPtr + start, count, type, ref marshaledStates); } } } //////////////////////////////////////////////////////////// /// <summary> /// Save the current OpenGL render states and matrices. /// /// This function can be used when you mix SFML drawing /// and direct OpenGL rendering. Combined with PopGLStates, /// it ensures that: /// \li SFML's internal states are not messed up by your OpenGL code /// \li your OpenGL states are not modified by a call to a SFML function /// /// More specifically, it must be used around code that /// calls Draw functions. Example: /// /// // OpenGL code here... /// window.PushGLStates(); /// window.Draw(...); /// window.Draw(...); /// window.PopGLStates(); /// // OpenGL code here... /// /// Note that this function is quite expensive: it saves all the /// possible OpenGL states and matrices, even the ones you /// don't care about. Therefore it should be used wisely. /// It is provided for convenience, but the best results will /// be achieved if you handle OpenGL states yourself (because /// you know which states have really changed, and need to be /// saved and restored). Take a look at the ResetGLStates /// function if you do so. /// </summary> //////////////////////////////////////////////////////////// public void PushGLStates() { sfRenderTexture_pushGLStates(CPointer); } //////////////////////////////////////////////////////////// /// <summary> /// Restore the previously saved OpenGL render states and matrices. /// /// See the description of PushGLStates to get a detailed /// description of these functions. /// </summary> //////////////////////////////////////////////////////////// public void PopGLStates() { sfRenderTexture_popGLStates(CPointer); } //////////////////////////////////////////////////////////// /// <summary> /// Reset the internal OpenGL states so that the target is ready for drawing. /// /// This function can be used when you mix SFML drawing /// and direct OpenGL rendering, if you choose not to use /// PushGLStates/PopGLStates. It makes sure that all OpenGL /// states needed by SFML are set, so that subsequent Draw() /// calls will work as expected. /// /// Example: /// /// // OpenGL code here... /// glPushAttrib(...); /// window.ResetGLStates(); /// window.Draw(...); /// window.Draw(...); /// glPopAttrib(...); /// // OpenGL code here... /// </summary> //////////////////////////////////////////////////////////// public void ResetGLStates() { sfRenderTexture_resetGLStates(CPointer); } //////////////////////////////////////////////////////////// /// <summary> /// Provide a string describing the object /// </summary> /// <returns>String description of the object</returns> //////////////////////////////////////////////////////////// public override string ToString() { return "[RenderTexture]" + " Size(" + Size + ")" + " Texture(" + Texture + ")" + " DefaultView(" + DefaultView + ")" + " View(" + GetView() + ")"; } //////////////////////////////////////////////////////////// /// <summary> /// Handle the destruction of the object /// </summary> /// <param name="disposing">Is the GC disposing the object, or is it an explicit call ?</param> //////////////////////////////////////////////////////////// protected override void Destroy(bool disposing) { if (!disposing) Context.Global.SetActive(true); sfRenderTexture_destroy(CPointer); if (disposing) { myDefaultView.Dispose(); myTexture.Dispose(); } if (!disposing) Context.Global.SetActive(false); } private View myDefaultView = null; private Texture myTexture = null; #region Imports [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntPtr sfRenderTexture_create(uint Width, uint Height, bool DepthBuffer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfRenderTexture_destroy(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfRenderTexture_clear(IntPtr CPointer, Color ClearColor); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern Vector2u sfRenderTexture_getSize(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern bool sfRenderTexture_setActive(IntPtr CPointer, bool Active); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern bool sfRenderTexture_saveGLStates(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern bool sfRenderTexture_restoreGLStates(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern bool sfRenderTexture_display(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfRenderTexture_setView(IntPtr CPointer, IntPtr View); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntPtr sfRenderTexture_getView(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntPtr sfRenderTexture_getDefaultView(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntRect sfRenderTexture_getViewport(IntPtr CPointer, IntPtr TargetView); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern Vector2i sfRenderTexture_mapCoordsToPixel(IntPtr CPointer, Vector2f point, IntPtr View); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern Vector2f sfRenderTexture_mapPixelToCoords(IntPtr CPointer, Vector2i point, IntPtr View); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntPtr sfRenderTexture_getTexture(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfRenderTexture_setSmooth(IntPtr texture, bool smooth); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern bool sfRenderTexture_isSmooth(IntPtr texture); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] unsafe static extern void sfRenderTexture_drawPrimitives(IntPtr CPointer, Vertex* vertexPtr, uint vertexCount, PrimitiveType type, ref RenderStates.MarshalData renderStates); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfRenderTexture_pushGLStates(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfRenderTexture_popGLStates(IntPtr CPointer); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfRenderTexture_resetGLStates(IntPtr CPointer); #endregion } } }
#region copyright // Copyright (c) 2015 Wm. Barrett Simms wbsimms.com // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #endregion using System.Collections; using Gadgeteer.Modules; using Gadgeteer.Modules.GHIElectronics; using GadgeteerHelper; using Microsoft.SPOT; using Microsoft.SPOT.Presentation; using Microsoft.SPOT.Presentation.Controls; using TouchKeyboard; namespace GMorse { public class KeyboardHelper { private KeyStateContext _keyState; private Module.DisplayModule display; private Font font; private Text displayText; private IList keys = new ArrayList(); public delegate void TextChangedEventHander(object sender, TextChangedEventArgs args); public event TextChangedEventHander TextChanged; public delegate void EnterPressedEventHander(object sender, EnterPressedEventArgs args); public event EnterPressedEventHander EnterPressed; StackPanel spacer = new StackPanel(Orientation.Horizontal); StackPanel spacer1 = new StackPanel(Orientation.Horizontal); StackPanel keysRow1 = new StackPanel(Orientation.Horizontal); StackPanel keysRow2 = new StackPanel(Orientation.Horizontal); StackPanel keysRow3 = new StackPanel(Orientation.Horizontal); StackPanel keysRow4 = new StackPanel(Orientation.Horizontal); StackPanel keysRow5 = new StackPanel(Orientation.Horizontal); StackPanel keysRow6 = new StackPanel(Orientation.Horizontal); public KeyboardHelper(Module.DisplayModule display, Font font) { this.display = display; this.font = font; this.displayText = new Text(font,""); spacer.Height = 3; spacer1.Height = 3; Init(); } public void Init() { Window window = display.WPFWindow; Panel mainPanel = new Panel(); window.Child = mainPanel; StackPanel sp = new StackPanel(Orientation.Vertical); mainPanel.Children.Add(sp); sp.Children.Add(spacer); StackPanel dispalySP = new StackPanel(Orientation.Horizontal); sp.Children.Add(dispalySP); dispalySP.Children.Add(displayText); sp.Children.Add(spacer1); sp.Children.Add(keysRow1); sp.Children.Add(keysRow2); sp.Children.Add(keysRow3); sp.Children.Add(keysRow4); sp.Children.Add(keysRow5); sp.Children.Add(keysRow6); keysRow1.HorizontalAlignment = HorizontalAlignment.Center; keysRow2.HorizontalAlignment = HorizontalAlignment.Center; keysRow3.HorizontalAlignment = HorizontalAlignment.Center; keysRow4.HorizontalAlignment = HorizontalAlignment.Center; keysRow5.HorizontalAlignment = HorizontalAlignment.Center; keysRow6.HorizontalAlignment = HorizontalAlignment.Center; UnShiftKeys(false); Key shiftKey = new Key(font, "Shift"); shiftKey.keyPressedHandler += keyPressedHandler; Key spaceKey = new Key(font, "Space"); spaceKey.keyPressedHandler += keyPressedHandler; Key delKey = new Key(font, "Delete"); delKey.keyPressedHandler += keyPressedHandler; keysRow5.Children.Add(shiftKey.RenderKey()); keysRow5.Children.Add(spaceKey.RenderKey()); keysRow5.Children.Add(delKey.RenderKey()); Key enterKey = new Key(font, "Enter"); enterKey.keyPressedHandler += keyPressedHandler; keysRow6.Children.Add(enterKey.RenderKey()); _keyState = new KeyStateContext(this); } private Key GetKeyAndAddToList(string text) { Key k = new Key(font,text); k.keyPressedHandler += keyPressedHandler; keys.Add(k); return k; } void keyPressedHandler(object sender, KeyPressedEventArgs args) { if (args.KeyPressed == "Shift") { _keyState.SwitchState(); } else if (args.KeyPressed == "Space") { displayText.TextContent = displayText.TextContent + " "; OnTextChanged(sender); } else if (args.KeyPressed == "Enter") { OnTextChanged(sender); OnEnterPressed(sender); } else if (args.KeyPressed == "Delete") { if (displayText.TextContent.Length == 0) return; displayText.TextContent = displayText.TextContent.Substring(0,displayText.TextContent.Length-1); OnTextChanged(sender); } else { displayText.TextContent = displayText.TextContent + args.KeyPressed; OnTextChanged(sender); } } private void OnEnterPressed(object sender) { if (EnterPressed != null) { EnterPressed(sender, new EnterPressedEventArgs(displayText.TextContent)); } } private void OnTextChanged(object sender) { if (TextChanged != null) { TextChanged(sender, new TextChangedEventArgs(displayText.TextContent)); } } private void UnShiftKeys(bool needRemoval = true) { if (needRemoval) { RemoveKeys(); } AddKeys(keysRow1, "1234567890"); AddKeys(keysRow2, "qwertyuiop"); AddKeys(keysRow3, "asdfghjkl"); AddKeys(keysRow4, "zxcvbnm"); } protected void ShiftKeys() { RemoveKeys(); AddKeys(keysRow1, "!@#$%^&*()"); AddKeys(keysRow2, "QWERTYUIOP"); AddKeys(keysRow3, "ASDFGHJKL"); AddKeys(keysRow4, "ZXCVBNM"); } private void AddKeys(StackPanel keysRow, string keys) { foreach (var character in keys.ToCharArray()) { keysRow.Children.Add(GetKeyAndAddToList(character.ToString()).RenderKey()); } } private void RemoveKeys() { foreach (Key k in keys) { k.keyPressedHandler -= keyPressedHandler; k.Dispose(); } keysRow1.Children.Clear(); keysRow2.Children.Clear(); keysRow3.Children.Clear(); keysRow4.Children.Clear(); } private interface IKeyState { void CreateKeys(); } private class KeyStateShifted : IKeyState { private KeyboardHelper _parent; public KeyStateShifted(KeyboardHelper parent) { _parent = parent; } public void CreateKeys() { _parent.ShiftKeys(); } } private class KeyStateUnshifted : IKeyState { private KeyboardHelper _parent; public KeyStateUnshifted(KeyboardHelper parent) { _parent = parent; } public void CreateKeys() { _parent.UnShiftKeys(); } } private class KeyStateContext { private IKeyState[] _keyStates; private IKeyState _currentKeyState; public KeyStateContext(KeyboardHelper parent) { _keyStates = new IKeyState[] { new KeyStateUnshifted(parent), new KeyStateShifted(parent) }; _currentKeyState = _keyStates[0]; } public void SwitchState() { if (_currentKeyState is KeyStateUnshifted) { _currentKeyState = _keyStates[1]; } else { _currentKeyState = _keyStates[0]; } _currentKeyState.CreateKeys(); } } } }
#region License // Distributed under the MIT License // ============================================================ // Copyright (c) 2019 Hotcakes Commerce, LLC // Copyright (c) 2020 Upendo Ventures, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #endregion using System; using System.Web.UI.WebControls; using Hotcakes.Commerce; using Hotcakes.Commerce.Catalog; using Hotcakes.Modules.Core.Admin.AppCode; namespace Hotcakes.Modules.Core.Admin.Controls { partial class SimpleProductFilter : HccUserControl { public delegate void FilterChangedDelegate(object sender, EventArgs e); public delegate void GoPressedDelegate(object sender, EventArgs e); public event FilterChangedDelegate FilterChanged; public event GoPressedDelegate GoPressed; protected override void OnInit(EventArgs e) { base.OnInit(e); if (!Page.IsPostBack) { PopulateFilterFields(); } } public override void Focus() { txtFilterField.Focus(); } public ProductSearchCriteria LoadProductCriteria() { var c = new ProductSearchCriteria(); c.DisplayInactiveProducts = true; if (txtFilterField.Text.Trim().Length > 0) { c.Keyword = txtFilterField.Text.Trim(); } if (!string.IsNullOrEmpty(ddlManufacturerFilter.SelectedValue)) { c.ManufacturerId = ddlManufacturerFilter.SelectedValue; } if (!string.IsNullOrEmpty(ddlVendorFilter.SelectedValue)) { c.VendorId = ddlVendorFilter.SelectedValue; } if (!string.IsNullOrEmpty(ddlCategoryFilter.SelectedValue)) { c.CategoryId = ddlCategoryFilter.SelectedValue; } if (!string.IsNullOrEmpty(ddlStatusFilter.SelectedValue)) { c.Status = (ProductStatus) int.Parse(ddlStatusFilter.SelectedValue); } if (!string.IsNullOrEmpty(ddlInventoryStatusFilter.SelectedValue)) { c.InventoryStatus = (ProductInventoryStatus) int.Parse(ddlInventoryStatusFilter.SelectedValue); } if (!string.IsNullOrEmpty(ddlProductTypeFilter.SelectedValue)) { c.ProductTypeId = ddlProductTypeFilter.SelectedValue; } // Save Setting to Session SessionManager.AdminProductCriteriaKeyword = txtFilterField.Text.Trim(); SessionManager.AdminProductCriteriaCategory = ddlCategoryFilter.SelectedValue; SessionManager.AdminProductCriteriaManufacturer = ddlManufacturerFilter.SelectedValue; SessionManager.AdminProductCriteriaVendor = ddlVendorFilter.SelectedValue; SessionManager.AdminProductCriteriaStatus = ddlStatusFilter.SelectedValue; SessionManager.AdminProductCriteriaInventoryStatus = ddlInventoryStatusFilter.SelectedValue; SessionManager.AdminProductCriteriaProductType = ddlProductTypeFilter.SelectedValue; return c; } private void PopulateFilterFields() { PopulateCategories(); PopulateManufacturers(); PopulateVendors(); PopulateStatus(); PopulateInventoryStatus(); PopulateProductTypes(); txtFilterField.Text = SessionManager.AdminProductCriteriaKeyword.Trim(); SetListToValue(ddlCategoryFilter, SessionManager.AdminProductCriteriaCategory); SetListToValue(ddlManufacturerFilter, SessionManager.AdminProductCriteriaManufacturer); SetListToValue(ddlVendorFilter, SessionManager.AdminProductCriteriaVendor); SetListToValue(ddlStatusFilter, SessionManager.AdminProductCriteriaStatus); SetListToValue(ddlInventoryStatusFilter, SessionManager.AdminProductCriteriaInventoryStatus); SetListToValue(ddlProductTypeFilter, SessionManager.AdminProductCriteriaProductType); } private void SetListToValue(DropDownList l, string value) { if (l != null && l.Items.FindByValue(value) != null) { l.ClearSelection(); l.Items.FindByValue(value).Selected = true; } } private void PopulateCategories() { var tree = CategoriesHelper.ListFullTreeWithIndents(HccApp.CatalogServices.Categories); ddlCategoryFilter.Items.Clear(); foreach (var li in tree) { var item = new ListItem(li.Text, li.Value); ddlCategoryFilter.Items.Add(item); } ddlCategoryFilter.Items.Insert(0, new ListItem(Localization.GetString("AnyCategory"), string.Empty)); } private void PopulateManufacturers() { ddlManufacturerFilter.DataSource = HccApp.ContactServices.Manufacturers.FindAll(); ddlManufacturerFilter.DataTextField = "DisplayName"; ddlManufacturerFilter.DataValueField = "Bvin"; ddlManufacturerFilter.DataBind(); ddlManufacturerFilter.Items.Insert(0, new ListItem(Localization.GetString("AnyManufacturer"), string.Empty)); } private void PopulateVendors() { ddlVendorFilter.DataSource = HccApp.ContactServices.Vendors.FindAll(); ddlVendorFilter.DataTextField = "DisplayName"; ddlVendorFilter.DataValueField = "Bvin"; ddlVendorFilter.DataBind(); ddlVendorFilter.Items.Insert(0, new ListItem(Localization.GetString("AnyVendor"), string.Empty)); } private void PopulateStatus() { ddlStatusFilter.Items.Clear(); ddlStatusFilter.Items.Add(new ListItem(Localization.GetString("AnyStatus"), string.Empty)); ddlStatusFilter.Items.Add(new ListItem(Localization.GetString("Active"), "1")); ddlStatusFilter.Items.Add(new ListItem(Localization.GetString("Disabled"), "0")); } private void PopulateInventoryStatus() { ddlInventoryStatusFilter.Items.Clear(); ddlInventoryStatusFilter.Items.Add(new ListItem(Localization.GetString("AnyInventoryStatus"), string.Empty)); ddlInventoryStatusFilter.Items.Add(new ListItem(Localization.GetString("NotAvailable"), "0")); ddlInventoryStatusFilter.Items.Add(new ListItem(Localization.GetString("Available"), "1")); ddlInventoryStatusFilter.Items.Add(new ListItem(Localization.GetString("LowInventory"), "2")); } private void PopulateProductTypes() { ddlProductTypeFilter.Items.Clear(); ddlProductTypeFilter.DataSource = HccApp.CatalogServices.ProductTypes.FindAll(); ddlProductTypeFilter.DataTextField = "ProductTypeName"; ddlProductTypeFilter.DataValueField = "bvin"; ddlProductTypeFilter.DataBind(); ddlProductTypeFilter.Items.Insert(0, new ListItem(Localization.GetString("AnyType"), string.Empty)); } protected void btnGo_Click(object sender, EventArgs e) { GoPressed(LoadProductCriteria(), new EventArgs()); txtFilterField.Focus(); } protected void ddlProductTypeFilter_SelectedIndexChanged(object sender, EventArgs e) { FilterChanged(LoadProductCriteria(), new EventArgs()); } protected void ddlCategoryFilter_SelectedIndexChanged(object sender, EventArgs e) { FilterChanged(LoadProductCriteria(), new EventArgs()); } protected void ddlManufacturerFilter_SelectedIndexChanged(object sender, EventArgs e) { FilterChanged(LoadProductCriteria(), new EventArgs()); } protected void ddlVendorFilter_SelectedIndexChanged(object sender, EventArgs e) { FilterChanged(LoadProductCriteria(), new EventArgs()); } protected void ddlStatusFilter_SelectedIndexChanged(object sender, EventArgs e) { FilterChanged(LoadProductCriteria(), new EventArgs()); } protected void ddlInventoryStatusFilter_SelectedIndexChanged(object sender, EventArgs e) { FilterChanged(LoadProductCriteria(), new EventArgs()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ShiftLeftLogicalInt161() { var test = new ImmUnaryOpTest__ShiftLeftLogicalInt161(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmUnaryOpTest__ShiftLeftLogicalInt161 { private struct TestStruct { public Vector256<Int16> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftLeftLogicalInt161 testClass) { var result = Avx2.ShiftLeftLogical(_fld, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static Int16[] _data = new Int16[Op1ElementCount]; private static Vector256<Int16> _clsVar; private Vector256<Int16> _fld; private SimpleUnaryOpTest__DataTable<Int16, Int16> _dataTable; static ImmUnaryOpTest__ShiftLeftLogicalInt161() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); } public ImmUnaryOpTest__ShiftLeftLogicalInt161() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new SimpleUnaryOpTest__DataTable<Int16, Int16>(_data, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.ShiftLeftLogical( Unsafe.Read<Vector256<Int16>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.ShiftLeftLogical( Avx.LoadVector256((Int16*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.ShiftLeftLogical( Avx.LoadAlignedVector256((Int16*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical), new Type[] { typeof(Vector256<Int16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int16>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical), new Type[] { typeof(Vector256<Int16>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((Int16*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical), new Type[] { typeof(Vector256<Int16>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int16*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.ShiftLeftLogical( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector256<Int16>>(_dataTable.inArrayPtr); var result = Avx2.ShiftLeftLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Avx.LoadVector256((Int16*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftLeftLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftLeftLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftLeftLogicalInt161(); var result = Avx2.ShiftLeftLogical(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.ShiftLeftLogical(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.ShiftLeftLogical(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Int16> firstOp, void* result, [CallerMemberName] string method = "") { Int16[] inArray = new Int16[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int16[] inArray = new Int16[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int16[] firstOp, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((short)(firstOp[0] << 1) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((short)(firstOp[i] << 1) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ShiftLeftLogical)}<Int16>(Vector256<Int16><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Text; using SharpDX.Collections; namespace SharpDX.Diagnostics { /// <summary> /// Event args for <see cref="ComObject"/> used by <see cref="ObjectTracker"/>. /// </summary> public class ComObjectEventArgs : EventArgs { /// <summary> /// The object being tracked/untracked. /// </summary> public ComObject Object; /// <summary> /// Initializes a new instance of the <see cref="ComObjectEventArgs"/> class. /// </summary> /// <param name="o">The o.</param> public ComObjectEventArgs(ComObject o) { Object = o; } } /// <summary> /// Track all allocated objects. /// </summary> public static class ObjectTracker { private static Dictionary<IntPtr, List<ObjectReference>> processGlobalObjectReferences; [ThreadStatic] private static Dictionary<IntPtr, List<ObjectReference>> threadStaticObjectReferences; /// <summary> /// Occurs when a ComObject is tracked. /// </summary> public static event EventHandler<ComObjectEventArgs> Tracked; /// <summary> /// Occurs when a ComObject is untracked. /// </summary> public static event EventHandler<ComObjectEventArgs> UnTracked; private static Dictionary<IntPtr, List<ObjectReference>> ObjectReferences { get { Dictionary<IntPtr, List<ObjectReference>> objectReferences; if (Configuration.UseThreadStaticObjectTracking) { if (threadStaticObjectReferences == null) threadStaticObjectReferences = new Dictionary<IntPtr, List<ObjectReference>>(EqualityComparer.DefaultIntPtr); objectReferences = threadStaticObjectReferences; } else { if (processGlobalObjectReferences == null) processGlobalObjectReferences = new Dictionary<IntPtr, List<ObjectReference>>(EqualityComparer.DefaultIntPtr); objectReferences = processGlobalObjectReferences; } return objectReferences; } } /// <summary> /// Tracks the specified COM object. /// </summary> /// <param name="comObject">The COM object.</param> public static void Track(ComObject comObject) { if (comObject == null || comObject.NativePointer == IntPtr.Zero) return; lock (ObjectReferences) { List<ObjectReference> referenceList; // Object is already tracked if (!ObjectReferences.TryGetValue(comObject.NativePointer, out referenceList)) { referenceList = new List<ObjectReference>(); ObjectReferences.Add(comObject.NativePointer, referenceList); } #if STORE_APP var stacktrace = "Stacktrace is not available on this platform"; // This code is a workaround to be able to get a full stacktrace on Windows Store App. // This is an unsafe code, that should not run on production. Only at dev time! // Make sure we are on a 32bit process if(IntPtr.Size == 4) { // Get an access to a restricted method try { var stackTraceGetMethod = typeof(Environment).GetRuntimeProperty("StackTrace").GetMethod; try { // First try to get the stacktrace stacktrace = (string)stackTraceGetMethod.Invoke(null, null); } catch(Exception ex) { // If we have an exception, it means that the access to the method is not possible // so we are going to patch the field RuntimeMethodInfo.m_invocationFlags that should contain // 0x41 (initialized + security), and replace it by 0x1 (initialized) // and then callback again the method unsafe { // unsafe code, the RuntimeMethodInfo could be relocated (is it a real managed GC object?), // but we don't have much choice var addr = *(int**)Interop.Fixed(ref stackTraceGetMethod); // offset to RuntimeMethodInfo.m_invocationFlags addr += 13; // Check if we have the expecting value if(*addr == 0x41) { // if yes, change it to 0x1 *addr = 0x1; try { // And try to callit again a second time // if it succeeds, first Invoke() should run on next call stacktrace = (string)stackTraceGetMethod.Invoke(null, null); } catch(Exception ex2) { // if it is still failing, we can't do anything } } } } } catch(Exception ex) { // can't do anything } } referenceList.Add(new ObjectReference(DateTime.Now, comObject, stacktrace)); #else // Another WTF: To get a stacktrace, we don't have other ways than throwing an exception on PCL. try { throw new GetStackTraceException(); } catch (GetStackTraceException ex) { referenceList.Add(new ObjectReference(DateTime.Now, comObject, ex.StackTrace)); } #endif // Fire Tracked event. OnTracked(comObject); } } /// <summary> /// Finds a list of object reference from a specified COM object pointer. /// </summary> /// <param name="comObjectPtr">The COM object pointer.</param> /// <returns>A list of object reference</returns> public static List<ObjectReference> Find(IntPtr comObjectPtr) { lock (ObjectReferences) { List<ObjectReference> referenceList; // Object is already tracked if (ObjectReferences.TryGetValue(comObjectPtr, out referenceList)) return new List<ObjectReference>(referenceList); } return new List<ObjectReference>(); } /// <summary> /// Finds the object reference for a specific COM object. /// </summary> /// <param name="comObject">The COM object.</param> /// <returns>An object reference</returns> public static ObjectReference Find(ComObject comObject) { lock (ObjectReferences) { List<ObjectReference> referenceList; // Object is already tracked if (ObjectReferences.TryGetValue(comObject.NativePointer, out referenceList)) { foreach (var objectReference in referenceList) { if (ReferenceEquals(objectReference.Object.Target, comObject)) return objectReference; } } } return null; } /// <summary> /// Untracks the specified COM object. /// </summary> /// <param name="comObject">The COM object.</param> public static void UnTrack(ComObject comObject) { if (comObject == null || comObject.NativePointer == IntPtr.Zero) return; lock (ObjectReferences) { List<ObjectReference> referenceList; // Object is already tracked if (ObjectReferences.TryGetValue(comObject.NativePointer, out referenceList)) { for (int i = referenceList.Count-1; i >=0; i--) { var objectReference = referenceList[i]; if (ReferenceEquals(objectReference.Object.Target, comObject)) referenceList.RemoveAt(i); else if (!objectReference.IsAlive) referenceList.RemoveAt(i); } // Remove empty list if (referenceList.Count == 0) ObjectReferences.Remove(comObject.NativePointer); // Fire UnTracked event OnUnTracked(comObject); } } } /// <summary> /// Reports all COM object that are active and not yet disposed. /// </summary> public static List<ObjectReference> FindActiveObjects() { var activeObjects = new List<ObjectReference>(); lock (ObjectReferences) { foreach (var referenceList in ObjectReferences.Values) { foreach (var objectReference in referenceList) { if (objectReference.IsAlive) activeObjects.Add(objectReference); } } } return activeObjects; } /// <summary> /// Reports all COM object that are active and not yet disposed. /// </summary> public static string ReportActiveObjects() { var text = new StringBuilder(); int count = 0; var countPerType = new Dictionary<string, int>(); foreach (var findActiveObject in FindActiveObjects()) { var findActiveObjectStr = findActiveObject.ToString(); if (!string.IsNullOrEmpty(findActiveObjectStr)) { text.AppendFormat("[{0}]: {1}", count, findActiveObjectStr); var target = findActiveObject.Object.Target; if (target != null) { int typeCount; var targetType = target.GetType().Name; if (!countPerType.TryGetValue(targetType, out typeCount)) { countPerType[targetType] = 0; } countPerType[targetType] = typeCount + 1; } } count++; } var keys = new List<string>(countPerType.Keys); keys.Sort(); text.AppendLine(); text.AppendLine("Count per Type:"); foreach (var key in keys) { text.AppendFormat("{0} : {1}", key, countPerType[key]); text.AppendLine(); } return text.ToString(); } private static void OnTracked(ComObject obj) { var handler = Tracked; if (handler != null) { handler(null, new ComObjectEventArgs(obj)); } } private static void OnUnTracked(ComObject obj) { var handler = UnTracked; if (handler != null) { handler(null, new ComObjectEventArgs(obj)); } } private class GetStackTraceException : Exception { } } }
// 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.Data.Common; using System.Data.SqlTypes; using System.Diagnostics; namespace System.Data { internal sealed class FunctionNode : ExpressionNode { internal readonly string _name; internal readonly int _info = -1; internal int _argumentCount = 0; internal const int initialCapacity = 1; internal ExpressionNode[] _arguments; private static readonly Function[] s_funcs = new Function[] { new Function("Abs", FunctionId.Abs, typeof(object), true, false, 1, typeof(object), null, null), new Function("IIf", FunctionId.Iif, typeof(object), false, false, 3, typeof(object), typeof(object), typeof(object)), new Function("In", FunctionId.In, typeof(bool), false, true, 1, null, null, null), new Function("IsNull", FunctionId.IsNull, typeof(object), false, false, 2, typeof(object), typeof(object), null), new Function("Len", FunctionId.Len, typeof(int), true, false, 1, typeof(string), null, null), new Function("Substring", FunctionId.Substring, typeof(string), true, false, 3, typeof(string), typeof(int), typeof(int)), new Function("Trim", FunctionId.Trim, typeof(string), true, false, 1, typeof(string), null, null), // convert new Function("Convert", FunctionId.Convert, typeof(object), false, true, 1, typeof(object), null, null), new Function("DateTimeOffset", FunctionId.DateTimeOffset, typeof(DateTimeOffset), false, true, 3, typeof(DateTime), typeof(int), typeof(int)), // store aggregates here new Function("Max", FunctionId.Max, typeof(object), false, false, 1, null, null, null), new Function("Min", FunctionId.Min, typeof(object), false, false, 1, null, null, null), new Function("Sum", FunctionId.Sum, typeof(object), false, false, 1, null, null, null), new Function("Count", FunctionId.Count, typeof(object), false, false, 1, null, null, null), new Function("Var", FunctionId.Var, typeof(object), false, false, 1, null, null, null), new Function("StDev", FunctionId.StDev, typeof(object), false, false, 1, null, null, null), new Function("Avg", FunctionId.Avg, typeof(object), false, false, 1, null, null, null), }; internal FunctionNode(DataTable table, string name) : base(table) { _name = name; for (int i = 0; i < s_funcs.Length; i++) { if (string.Equals(s_funcs[i]._name, name, StringComparison.OrdinalIgnoreCase)) { // we found the reserved word.. _info = i; break; } } if (_info < 0) { throw ExprException.UndefinedFunction(_name); } } internal void AddArgument(ExpressionNode argument) { if (!s_funcs[_info]._isVariantArgumentList && _argumentCount >= s_funcs[_info]._argumentCount) throw ExprException.FunctionArgumentCount(_name); if (_arguments == null) { _arguments = new ExpressionNode[initialCapacity]; } else if (_argumentCount == _arguments.Length) { ExpressionNode[] bigger = new ExpressionNode[_argumentCount * 2]; Array.Copy(_arguments, 0, bigger, 0, _argumentCount); _arguments = bigger; } _arguments[_argumentCount++] = argument; } internal override void Bind(DataTable table, List<DataColumn> list) { BindTable(table); Check(); // special case for the Convert function bind only the first argument: // the second argument should be a Type stored as a name node, replace it with constant. if (s_funcs[_info]._id == FunctionId.Convert) { if (_argumentCount != 2) throw ExprException.FunctionArgumentCount(_name); _arguments[0].Bind(table, list); if (_arguments[1].GetType() == typeof(NameNode)) { NameNode type = (NameNode)_arguments[1]; _arguments[1] = new ConstNode(table, ValueType.Str, type._name); } _arguments[1].Bind(table, list); } else { for (int i = 0; i < _argumentCount; i++) { _arguments[i].Bind(table, list); } } } internal override object Eval() { return Eval(null, DataRowVersion.Default); } internal override object Eval(DataRow row, DataRowVersion version) { Debug.Assert(_info < s_funcs.Length && _info >= 0, "Invalid function info."); object[] argumentValues = new object[_argumentCount]; Debug.Assert(_argumentCount == s_funcs[_info]._argumentCount || s_funcs[_info]._isVariantArgumentList, "Invalid argument argumentCount."); // special case of the Convert function if (s_funcs[_info]._id == FunctionId.Convert) { if (_argumentCount != 2) throw ExprException.FunctionArgumentCount(_name); argumentValues[0] = _arguments[0].Eval(row, version); argumentValues[1] = GetDataType(_arguments[1]); } else if (s_funcs[_info]._id != FunctionId.Iif) { // We do not want to evaluate arguments of IIF, we will already do it in EvalFunction/ second point: we may go to div by 0 for (int i = 0; i < _argumentCount; i++) { argumentValues[i] = _arguments[i].Eval(row, version); if (s_funcs[_info]._isValidateArguments) { if ((argumentValues[i] == DBNull.Value) || (typeof(object) == s_funcs[_info]._parameters[i])) { // currently all supported functions with IsValidateArguments set to true // NOTE: for IIF and ISNULL IsValidateArguments set to false return DBNull.Value; } if (argumentValues[i].GetType() != s_funcs[_info]._parameters[i]) { // We are allowing conversions in one very specific case: int, int64,...'nice' numeric to numeric.. if (s_funcs[_info]._parameters[i] == typeof(int) && ExpressionNode.IsInteger(DataStorage.GetStorageType(argumentValues[i].GetType()))) { argumentValues[i] = Convert.ToInt32(argumentValues[i], FormatProvider); } else if ((s_funcs[_info]._id == FunctionId.Trim) || (s_funcs[_info]._id == FunctionId.Substring) || (s_funcs[_info]._id == FunctionId.Len)) { if ((typeof(string) != (argumentValues[i].GetType())) && (typeof(SqlString) != (argumentValues[i].GetType()))) { throw ExprException.ArgumentType(s_funcs[_info]._name, i + 1, s_funcs[_info]._parameters[i]); } } else { throw ExprException.ArgumentType(s_funcs[_info]._name, i + 1, s_funcs[_info]._parameters[i]); } } } } } return EvalFunction(s_funcs[_info]._id, argumentValues, row, version); } internal override object Eval(int[] recordNos) { throw ExprException.ComputeNotAggregate(ToString()); } internal override bool IsConstant() { // Currently all function calls with const arguments return constant. // That could change in the future (if we implement Rand()...) // CONSIDER: We could be smarter for Iif. bool constant = true; for (int i = 0; i < _argumentCount; i++) { constant = constant && _arguments[i].IsConstant(); } Debug.Assert(_info > -1, "All function nodes should be bound at this point."); // default info is -1, it means if not bounded, it should be -1, not 0!! return (constant); } internal override bool IsTableConstant() { for (int i = 0; i < _argumentCount; i++) { if (!_arguments[i].IsTableConstant()) { return false; } } return true; } internal override bool HasLocalAggregate() { for (int i = 0; i < _argumentCount; i++) { if (_arguments[i].HasLocalAggregate()) { return true; } } return false; } internal override bool HasRemoteAggregate() { for (int i = 0; i < _argumentCount; i++) { if (_arguments[i].HasRemoteAggregate()) { return true; } } return false; } internal override bool DependsOn(DataColumn column) { for (int i = 0; i < _argumentCount; i++) { if (_arguments[i].DependsOn(column)) return true; } return false; } internal override ExpressionNode Optimize() { for (int i = 0; i < _argumentCount; i++) { _arguments[i] = _arguments[i].Optimize(); } Debug.Assert(_info > -1, "Optimizing unbound function "); // default info is -1, it means if not bounded, it should be -1, not 0!! if (s_funcs[_info]._id == FunctionId.In) { // we can not optimize the in node, just check that it has all constant arguments if (!IsConstant()) { throw ExprException.NonConstantArgument(); } } else { if (IsConstant()) { return new ConstNode(table, ValueType.Object, Eval(), false); } } return this; } private Type GetDataType(ExpressionNode node) { Type nodeType = node.GetType(); string typeName = null; if (nodeType == typeof(NameNode)) { typeName = ((NameNode)node)._name; } if (nodeType == typeof(ConstNode)) { typeName = ((ConstNode)node)._val.ToString(); } if (typeName == null) { throw ExprException.ArgumentType(s_funcs[_info]._name, 2, typeof(Type)); } Type dataType = Type.GetType(typeName); if (dataType == null) { throw ExprException.InvalidType(typeName); } return dataType; } private object EvalFunction(FunctionId id, object[] argumentValues, DataRow row, DataRowVersion version) { StorageType storageType; switch (id) { case FunctionId.Abs: Debug.Assert(_argumentCount == 1, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider)); storageType = DataStorage.GetStorageType(argumentValues[0].GetType()); if (ExpressionNode.IsInteger(storageType)) return (Math.Abs((long)argumentValues[0])); if (ExpressionNode.IsNumeric(storageType)) return (Math.Abs((double)argumentValues[0])); throw ExprException.ArgumentTypeInteger(s_funcs[_info]._name, 1); case FunctionId.cBool: Debug.Assert(_argumentCount == 1, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider)); storageType = DataStorage.GetStorageType(argumentValues[0].GetType()); return storageType switch { StorageType.Boolean => (bool)argumentValues[0], StorageType.Int32 => ((int)argumentValues[0] != 0), StorageType.Double => ((double)argumentValues[0] != 0.0), StorageType.String => bool.Parse((string)argumentValues[0]), _ => throw ExprException.DatatypeConvertion(argumentValues[0].GetType(), typeof(bool)), }; case FunctionId.cInt: Debug.Assert(_argumentCount == 1, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider)); return Convert.ToInt32(argumentValues[0], FormatProvider); case FunctionId.cDate: Debug.Assert(_argumentCount == 1, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider)); return Convert.ToDateTime(argumentValues[0], FormatProvider); case FunctionId.cDbl: Debug.Assert(_argumentCount == 1, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider)); return Convert.ToDouble(argumentValues[0], FormatProvider); case FunctionId.cStr: Debug.Assert(_argumentCount == 1, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider)); return Convert.ToString(argumentValues[0], FormatProvider); case FunctionId.Charindex: Debug.Assert(_argumentCount == 2, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider)); Debug.Assert(argumentValues[0] is string, "Invalid argument type for " + s_funcs[_info]._name); Debug.Assert(argumentValues[1] is string, "Invalid argument type for " + s_funcs[_info]._name); if (DataStorage.IsObjectNull(argumentValues[0]) || DataStorage.IsObjectNull(argumentValues[1])) return DBNull.Value; if (argumentValues[0] is SqlString) argumentValues[0] = ((SqlString)argumentValues[0]).Value; if (argumentValues[1] is SqlString) argumentValues[1] = ((SqlString)argumentValues[1]).Value; return ((string)argumentValues[1]).IndexOf((string)argumentValues[0], StringComparison.Ordinal); case FunctionId.Iif: Debug.Assert(_argumentCount == 3, "Invalid argument argumentCount: " + _argumentCount.ToString(FormatProvider)); object first = _arguments[0].Eval(row, version); if (DataExpression.ToBoolean(first) != false) { return _arguments[1].Eval(row, version); } else { return _arguments[2].Eval(row, version); } case FunctionId.In: // we never evaluate IN directly: IN as a binary operator, so evaluation of this should be in // BinaryNode class throw ExprException.NYI(s_funcs[_info]._name); case FunctionId.IsNull: Debug.Assert(_argumentCount == 2, "Invalid argument argumentCount: "); if (DataStorage.IsObjectNull(argumentValues[0])) return argumentValues[1]; else return argumentValues[0]; case FunctionId.Len: Debug.Assert(_argumentCount == 1, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider)); Debug.Assert((argumentValues[0] is string) || (argumentValues[0] is SqlString), "Invalid argument type for " + s_funcs[_info]._name); if (argumentValues[0] is SqlString) { if (((SqlString)argumentValues[0]).IsNull) { return DBNull.Value; } else { argumentValues[0] = ((SqlString)argumentValues[0]).Value; } } return ((string)argumentValues[0]).Length; case FunctionId.Substring: Debug.Assert(_argumentCount == 3, "Invalid argument argumentCount: " + _argumentCount.ToString(FormatProvider)); Debug.Assert((argumentValues[0] is string) || (argumentValues[0] is SqlString), "Invalid first argument " + argumentValues[0].GetType().FullName + " in " + s_funcs[_info]._name); Debug.Assert(argumentValues[1] is int, "Invalid second argument " + argumentValues[1].GetType().FullName + " in " + s_funcs[_info]._name); Debug.Assert(argumentValues[2] is int, "Invalid third argument " + argumentValues[2].GetType().FullName + " in " + s_funcs[_info]._name); // work around the differences in .NET and VBA implementation of the Substring function // 1. The <index> Argument is 0-based in .NET, and 1-based in VBA // 2. If the <Length> argument is longer then the string length .NET throws an ArgumentException // but our users still want to get a result. int start = (int)argumentValues[1] - 1; int length = (int)argumentValues[2]; if (start < 0) throw ExprException.FunctionArgumentOutOfRange("index", "Substring"); if (length < 0) throw ExprException.FunctionArgumentOutOfRange("length", "Substring"); if (length == 0) return string.Empty; if (argumentValues[0] is SqlString) argumentValues[0] = ((SqlString)argumentValues[0]).Value; int src_length = ((string)argumentValues[0]).Length; if (start > src_length) { return DBNull.Value; } if (start + length > src_length) { length = src_length - start; } return ((string)argumentValues[0]).Substring(start, length); case FunctionId.Trim: { Debug.Assert(_argumentCount == 1, "Invalid argument argumentCount for " + s_funcs[_info]._name + " : " + _argumentCount.ToString(FormatProvider)); Debug.Assert((argumentValues[0] is string) || (argumentValues[0] is SqlString), "Invalid argument type for " + s_funcs[_info]._name); if (DataStorage.IsObjectNull(argumentValues[0])) return DBNull.Value; if (argumentValues[0] is SqlString) argumentValues[0] = ((SqlString)argumentValues[0]).Value; return (((string)argumentValues[0]).Trim()); } case FunctionId.Convert: if (_argumentCount != 2) throw ExprException.FunctionArgumentCount(_name); if (argumentValues[0] == DBNull.Value) { return DBNull.Value; } Type type = (Type)argumentValues[1]; StorageType mytype = DataStorage.GetStorageType(type); storageType = DataStorage.GetStorageType(argumentValues[0].GetType()); if (mytype == StorageType.DateTimeOffset) { if (storageType == StorageType.String) { return SqlConvert.ConvertStringToDateTimeOffset((string)argumentValues[0], FormatProvider); } } if (StorageType.Object != mytype) { if ((mytype == StorageType.Guid) && (storageType == StorageType.String)) return new Guid((string)argumentValues[0]); if (ExpressionNode.IsFloatSql(storageType) && ExpressionNode.IsIntegerSql(mytype)) { if (StorageType.Single == storageType) { return SqlConvert.ChangeType2((float)SqlConvert.ChangeType2(argumentValues[0], StorageType.Single, typeof(float), FormatProvider), mytype, type, FormatProvider); } else if (StorageType.Double == storageType) { return SqlConvert.ChangeType2((double)SqlConvert.ChangeType2(argumentValues[0], StorageType.Double, typeof(double), FormatProvider), mytype, type, FormatProvider); } else if (StorageType.Decimal == storageType) { return SqlConvert.ChangeType2((decimal)SqlConvert.ChangeType2(argumentValues[0], StorageType.Decimal, typeof(decimal), FormatProvider), mytype, type, FormatProvider); } return SqlConvert.ChangeType2(argumentValues[0], mytype, type, FormatProvider); } return SqlConvert.ChangeType2(argumentValues[0], mytype, type, FormatProvider); } return argumentValues[0]; case FunctionId.DateTimeOffset: if (argumentValues[0] == DBNull.Value || argumentValues[1] == DBNull.Value || argumentValues[2] == DBNull.Value) return DBNull.Value; switch (((DateTime)argumentValues[0]).Kind) { case DateTimeKind.Utc: if ((int)argumentValues[1] != 0 && (int)argumentValues[2] != 0) { throw ExprException.MismatchKindandTimeSpan(); } break; case DateTimeKind.Local: if (DateTimeOffset.Now.Offset.Hours != (int)argumentValues[1] && DateTimeOffset.Now.Offset.Minutes != (int)argumentValues[2]) { throw ExprException.MismatchKindandTimeSpan(); } break; case DateTimeKind.Unspecified: break; } if ((int)argumentValues[1] < -14 || (int)argumentValues[1] > 14) throw ExprException.InvalidHoursArgument(); if ((int)argumentValues[2] < -59 || (int)argumentValues[2] > 59) throw ExprException.InvalidMinutesArgument(); // range should be within -14 hours and +14 hours if ((int)argumentValues[1] == 14 && (int)argumentValues[2] > 0) throw ExprException.InvalidTimeZoneRange(); if ((int)argumentValues[1] == -14 && (int)argumentValues[2] < 0) throw ExprException.InvalidTimeZoneRange(); return new DateTimeOffset((DateTime)argumentValues[0], new TimeSpan((int)argumentValues[1], (int)argumentValues[2], 0)); default: throw ExprException.UndefinedFunction(s_funcs[_info]._name); } } internal FunctionId Aggregate { get { if (IsAggregate) { return s_funcs[_info]._id; } return FunctionId.none; } } internal bool IsAggregate { get { bool aggregate = (s_funcs[_info]._id == FunctionId.Sum) || (s_funcs[_info]._id == FunctionId.Avg) || (s_funcs[_info]._id == FunctionId.Min) || (s_funcs[_info]._id == FunctionId.Max) || (s_funcs[_info]._id == FunctionId.Count) || (s_funcs[_info]._id == FunctionId.StDev) || (s_funcs[_info]._id == FunctionId.Var); return aggregate; } } internal void Check() { if (_info < 0) throw ExprException.UndefinedFunction(_name); if (s_funcs[_info]._isVariantArgumentList) { // for finctions with variabls argument list argumentCount is a minimal number of arguments if (_argumentCount < s_funcs[_info]._argumentCount) { // Special case for the IN operator if (s_funcs[_info]._id == FunctionId.In) throw ExprException.InWithoutList(); throw ExprException.FunctionArgumentCount(_name); } } else { if (_argumentCount != s_funcs[_info]._argumentCount) throw ExprException.FunctionArgumentCount(_name); } } } internal enum FunctionId { none = -1, Ascii = 0, Char = 1, Charindex = 2, Difference = 3, Len = 4, Lower = 5, LTrim = 6, Patindex = 7, Replicate = 8, Reverse = 9, Right = 10, RTrim = 11, Soundex = 12, Space = 13, Str = 14, Stuff = 15, Substring = 16, Upper = 17, IsNull = 18, Iif = 19, Convert = 20, cInt = 21, cBool = 22, cDate = 23, cDbl = 24, cStr = 25, Abs = 26, Acos = 27, In = 28, Trim = 29, Sum = 30, Avg = 31, Min = 32, Max = 33, Count = 34, StDev = 35, // Statistical standard deviation Var = 37, // Statistical variance DateTimeOffset = 38, } internal sealed class Function { internal readonly string _name; internal readonly FunctionId _id; internal readonly Type _result; internal readonly bool _isValidateArguments; internal readonly bool _isVariantArgumentList; internal readonly int _argumentCount; internal readonly Type[] _parameters = new Type[] { null, null, null }; internal Function() { _name = null; _id = FunctionId.none; _result = null; _isValidateArguments = false; _argumentCount = 0; } internal Function(string name, FunctionId id, Type result, bool IsValidateArguments, bool IsVariantArgumentList, int argumentCount, Type a1, Type a2, Type a3) { _name = name; _id = id; _result = result; _isValidateArguments = IsValidateArguments; _isVariantArgumentList = IsVariantArgumentList; _argumentCount = argumentCount; if (a1 != null) _parameters[0] = a1; if (a2 != null) _parameters[1] = a2; if (a3 != null) _parameters[2] = a3; } internal static string[] s_functionName = new string[] { "Unknown", "Ascii", "Char", "CharIndex", "Difference", "Len", "Lower", "LTrim", "Patindex", "Replicate", "Reverse", "Right", "RTrim", "Soundex", "Space", "Str", "Stuff", "Substring", "Upper", "IsNull", "Iif", "Convert", "cInt", "cBool", "cDate", "cDbl", "cStr", "Abs", "Acos", "In", "Trim", "Sum", "Avg", "Min", "Max", "Count", "StDev", "Var", "DateTimeOffset", }; } }
// // ContextBackendHandler.cs // // Author: // Lluis Sanchez <[email protected]> // Hywel Thomas <[email protected]> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Xwt.Backends; using Xwt.Drawing; using Xwt.GtkBackend; using System.Collections.Generic; namespace Xwt.CairoBackend { class CairoContextBackend : IDisposable { public double GlobalAlpha = 1; public Cairo.Context Context; public Cairo.Surface TempSurface; public double ScaleFactor = 1; public double PatternAlpha = 1; internal Point Origin = Point.Zero; Stack<Data> dataStack = new Stack<Data> (); struct Data { public double PatternAlpha; public double GlobalAlpha; } public CairoContextBackend (double scaleFactor) { ScaleFactor = scaleFactor; } public virtual void Dispose () { IDisposable d = Context; if (d != null) { d.Dispose (); } d = TempSurface; if (d != null) { d.Dispose (); } } public void Save () { Context.Save (); dataStack.Push (new Data () { PatternAlpha = PatternAlpha, GlobalAlpha = GlobalAlpha }); } public void Restore () { Context.Restore (); var d = dataStack.Pop (); PatternAlpha = d.PatternAlpha; GlobalAlpha = d.GlobalAlpha; } } public class CairoContextBackendHandler: ContextBackendHandler { public override bool DisposeHandleOnUiThread { get { return true; } } #region IContextBackendHandler implementation public override double GetScaleFactor (object backend) { CairoContextBackend gc = (CairoContextBackend)backend; return gc.ScaleFactor; } public override void Save (object backend) { CairoContextBackend gc = (CairoContextBackend)backend; gc.Save (); } public override void Restore (object backend) { CairoContextBackend gc = (CairoContextBackend)backend; gc.Restore (); } public override void SetGlobalAlpha (object backend, double alpha) { CairoContextBackend gc = (CairoContextBackend) backend; gc.GlobalAlpha = alpha; } const double degrees = System.Math.PI / 180d; public override void Arc (object backend, double xc, double yc, double radius, double angle1, double angle2) { CairoContextBackend gc = (CairoContextBackend)backend; gc.Context.Arc (xc, yc, radius, angle1 * degrees, angle2 * degrees); } public override void ArcNegative (object backend, double xc, double yc, double radius, double angle1, double angle2) { CairoContextBackend gc = (CairoContextBackend)backend; gc.Context.ArcNegative (xc, yc, radius, angle1 * degrees, angle2 * degrees); } public override void Clip (object backend) { Cairo.Context ctx = ((CairoContextBackend) backend).Context; ctx.Clip (); } public override void ClipPreserve (object backend) { Cairo.Context ctx = ((CairoContextBackend) backend).Context; ctx.ClipPreserve (); } public override void ClosePath (object backend) { Cairo.Context ctx = ((CairoContextBackend) backend).Context; ctx.ClosePath (); } public override void CurveTo (object backend, double x1, double y1, double x2, double y2, double x3, double y3) { CairoContextBackend gc = (CairoContextBackend) backend; gc.Context.CurveTo (x1, y1, x2, y2, x3, y3); } public override void Fill (object backend) { var gtkc = (CairoContextBackend) backend; Cairo.Context ctx = gtkc.Context; var alpha = gtkc.GlobalAlpha * gtkc.PatternAlpha; if (alpha == 1) ctx.Fill (); else { ctx.Save (); ctx.Clip (); ctx.PaintWithAlpha (alpha); ctx.Restore (); } } public override void FillPreserve (object backend) { var gtkc = (CairoContextBackend) backend; Cairo.Context ctx = gtkc.Context; var alpha = gtkc.GlobalAlpha * gtkc.PatternAlpha; if (alpha == 1) ctx.FillPreserve (); else { ctx.Save (); ctx.ClipPreserve (); ctx.PaintWithAlpha (alpha); ctx.Restore (); } } public override void LineTo (object backend, double x, double y) { CairoContextBackend gc = (CairoContextBackend) backend; gc.Context.LineTo (x, y); } public override void MoveTo (object backend, double x, double y) { CairoContextBackend gc = (CairoContextBackend) backend; gc.Context.MoveTo (x, y); } public override void NewPath (object backend) { Cairo.Context ctx = ((CairoContextBackend) backend).Context; ctx.NewPath (); } public override void Rectangle (object backend, double x, double y, double width, double height) { CairoContextBackend gc = (CairoContextBackend) backend; gc.Context.Rectangle (x, y, width, height); } public override void RelCurveTo (object backend, double dx1, double dy1, double dx2, double dy2, double dx3, double dy3) { Cairo.Context ctx = ((CairoContextBackend) backend).Context; ctx.RelCurveTo (dx1, dy1, dx2, dy2, dx3, dy3); } public override void RelLineTo (object backend, double dx, double dy) { Cairo.Context ctx = ((CairoContextBackend) backend).Context; ctx.RelLineTo (dx, dy); } public override void RelMoveTo (object backend, double dx, double dy) { Cairo.Context ctx = ((CairoContextBackend) backend).Context; ctx.RelMoveTo (dx, dy); } public override void Stroke (object backend) { Cairo.Context ctx = ((CairoContextBackend) backend).Context; ctx.Stroke (); } public override void StrokePreserve (object backend) { Cairo.Context ctx = ((CairoContextBackend) backend).Context; ctx.StrokePreserve (); } public override void SetColor (object backend, Xwt.Drawing.Color color) { var gtkContext = (CairoContextBackend) backend; gtkContext.Context.SetSourceRGBA (color.Red, color.Green, color.Blue, color.Alpha * gtkContext.GlobalAlpha); gtkContext.PatternAlpha = 1; } public override void SetLineWidth (object backend, double width) { Cairo.Context ctx = ((CairoContextBackend) backend).Context; ctx.LineWidth = width; } public override void SetLineDash (object backend, double offset, params double[] pattern) { Cairo.Context ctx = ((CairoContextBackend) backend).Context; ctx.SetDash (pattern, offset); } public override void SetPattern (object backend, object p) { var cb = (CairoContextBackend)backend; var toolkit = ApplicationContext.Toolkit; Cairo.Context ctx = cb.Context; p = toolkit.GetSafeBackend (p); if (p is ImagePatternBackend) { cb.PatternAlpha = ((ImagePatternBackend)p).Image.Alpha; p = ((ImagePatternBackend)p).GetPattern (ApplicationContext, ((CairoContextBackend)backend).ScaleFactor); } else cb.PatternAlpha = 1; if (p != null) ctx.SetSource ((Cairo.Pattern) p); else ctx.SetSource ((Cairo.Pattern) null); } public override void DrawTextLayout (object backend, TextLayout layout, double x, double y) { var be = (GtkTextLayoutBackendHandler.PangoBackend)ApplicationContext.Toolkit.GetSafeBackend (layout); var pl = be.Layout; CairoContextBackend ctx = (CairoContextBackend)backend; ctx.Context.MoveTo (x, y); if (layout.Height <= 0) { Pango.CairoHelper.ShowLayout (ctx.Context, pl); } else { var lc = pl.LineCount; var scale = Pango.Scale.PangoScale; double h = 0; var fe = ctx.Context.FontExtents; var baseline = fe.Ascent / (fe.Ascent + fe.Descent); for (int i=0; i<lc; i++) { var line = pl.Lines [i]; var ext = new Pango.Rectangle (); var extl = new Pango.Rectangle (); line.GetExtents (ref ext, ref extl); h += h == 0 ? (extl.Height / scale * baseline) : (extl.Height / scale); if (h > layout.Height) break; ctx.Context.MoveTo (x, y + h); Pango.CairoHelper.ShowLayoutLine (ctx.Context, line); } } } public override void DrawImage (object backend, ImageDescription img, double x, double y) { CairoContextBackend ctx = (CairoContextBackend)backend; img.Alpha *= ctx.GlobalAlpha; var pix = (Xwt.GtkBackend.GtkImage) img.Backend; pix.Draw (ApplicationContext, ctx.Context, ctx.ScaleFactor, x, y, img); } public override void DrawImage (object backend, ImageDescription img, Rectangle srcRect, Rectangle destRect) { CairoContextBackend ctx = (CairoContextBackend)backend; ctx.Context.Save (); ctx.Context.NewPath(); ctx.Context.Rectangle (destRect.X, destRect.Y, destRect.Width, destRect.Height); ctx.Context.Clip (); double sx = destRect.Width / srcRect.Width; double sy = destRect.Height / srcRect.Height; ctx.Context.Translate (destRect.X-srcRect.X*sx, destRect.Y-srcRect.Y*sy); ctx.Context.Scale (sx, sy); img.Alpha *= ctx.GlobalAlpha; var pix = (Xwt.GtkBackend.GtkImage) img.Backend; pix.Draw (ApplicationContext, ctx.Context, ctx.ScaleFactor, 0, 0, img); ctx.Context.Restore (); } protected virtual Size GetImageSize (object img) { return new Size (0,0); } public override void Rotate (object backend, double angle) { CairoContextBackend gc = (CairoContextBackend)backend; gc.Context.Rotate ((angle * System.Math.PI) / 180); } public override void Scale (object backend, double scaleX, double scaleY) { CairoContextBackend gc = (CairoContextBackend)backend; gc.Context.Scale (scaleX, scaleY); } public override void Translate (object backend, double tx, double ty) { CairoContextBackend gc = (CairoContextBackend)backend; gc.Context.Translate (tx, ty); } public override void ModifyCTM (object backend, Matrix m) { CairoContextBackend gc = (CairoContextBackend)backend; Cairo.Matrix t = new Cairo.Matrix (m.M11, m.M12, m.M21, m.M22, m.OffsetX, m.OffsetY); gc.Context.Transform (t); } public override Matrix GetCTM (object backend) { var cb = (CairoContextBackend)backend; Cairo.Matrix t = cb.Context.Matrix; // Adjust CTM X0,Y0 for ContextBackend Origin (ensures that new CTM is Identity Matrix) Matrix ctm = new Matrix (t.Xx, t.Yx, t.Xy, t.Yy, t.X0-cb.Origin.X, t.Y0-cb.Origin.Y); return ctm; } public override object CreatePath () { Cairo.Surface sf = new Cairo.ImageSurface (null, Cairo.Format.A1, 0, 0, 0); return new CairoContextBackend (1) { // scale doesn't matter here, we are going to use it only for creating a path TempSurface = sf, Context = new Cairo.Context (sf) }; } public override object CopyPath (object backend) { var newPath = CreatePath (); AppendPath (newPath, backend); return newPath; } public override void AppendPath (object backend, object otherBackend) { Cairo.Context dest = ((CairoContextBackend)backend).Context; Cairo.Context src = ((CairoContextBackend)otherBackend).Context; using (var path = src.CopyPath ()) dest.AppendPath (path); } public override bool IsPointInFill (object backend, double x, double y) { return ((CairoContextBackend)backend).Context.InFill (x, y); } public override bool IsPointInStroke (object backend, double x, double y) { return ((CairoContextBackend)backend).Context.InStroke (x, y); } public override void Dispose (object backend) { var ctx = (CairoContextBackend) backend; ctx.Dispose (); } #endregion } }
#region BSD License /* Copyright (c) 2004-2005 Matthew Holmes ([email protected]), Dan Moorehead ([email protected]) 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. * The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #endregion #region CVS Information /* * $Source$ * $Author: sontek $ * $Date: 2008-05-06 00:03:34 +0000 (Tue, 06 May 2008) $ * $Revision: 269 $ */ #endregion using System; using System.IO; using System.Xml; using Prebuild.Core.Attributes; using Prebuild.Core.Interfaces; using Prebuild.Core.Utilities; using Prebuild.Core.Targets; namespace Prebuild.Core.Nodes { /// <summary> /// /// </summary> public enum BuildAction { /// <summary> /// /// </summary> None, /// <summary> /// /// </summary> Compile, /// <summary> /// /// </summary> Content, /// <summary> /// /// </summary> EmbeddedResource } /// <summary> /// /// </summary> public enum SubType { /// <summary> /// /// </summary> Code, /// <summary> /// /// </summary> Component, /// <summary> /// /// </summary> Designer, /// <summary> /// /// </summary> Form, /// <summary> /// /// </summary> Settings, /// <summary> /// /// </summary> UserControl, /// <summary> /// /// </summary> CodeBehind, } public enum CopyToOutput { Never, Always, PreserveNewest } /// <summary> /// /// </summary> [DataNode("File")] public class FileNode : DataNode { #region Fields private string m_Path; private string m_ResourceName = ""; private BuildAction? m_BuildAction; private bool m_Valid; private SubType? m_SubType; private CopyToOutput m_CopyToOutput = CopyToOutput.Never; private bool m_Link = false; private string m_LinkPath = string.Empty; private bool m_PreservePath = false; #endregion #region Properties /// <summary> /// /// </summary> public string Path { get { return m_Path; } } /// <summary> /// /// </summary> public string ResourceName { get { return m_ResourceName; } } /// <summary> /// /// </summary> public BuildAction BuildAction { get { if (m_BuildAction != null) return m_BuildAction.Value; else return GetBuildActionByFileName(this.Path); } } public CopyToOutput CopyToOutput { get { return this.m_CopyToOutput; } } public bool IsLink { get { return this.m_Link; } } public string LinkPath { get { return this.m_LinkPath; } } /// <summary> /// /// </summary> public SubType SubType { get { if (m_SubType != null) return m_SubType.Value; else return GetSubTypeByFileName(this.Path); } } /// <summary> /// /// </summary> public bool IsValid { get { return m_Valid; } } /// <summary> /// /// </summary> /// <param name="file"></param> /// <returns></returns> public bool PreservePath { get { return m_PreservePath; } } #endregion #region Public Methods /// <summary> /// /// </summary> /// <param name="node"></param> public override void Parse(XmlNode node) { string buildAction = Helper.AttributeValue(node, "buildAction", String.Empty); if (buildAction != string.Empty) m_BuildAction = (BuildAction)Enum.Parse(typeof(BuildAction), buildAction); string subType = Helper.AttributeValue(node, "subType", string.Empty); if (subType != String.Empty) m_SubType = (SubType)Enum.Parse(typeof(SubType), subType); m_ResourceName = Helper.AttributeValue(node, "resourceName", m_ResourceName.ToString()); this.m_Link = bool.Parse(Helper.AttributeValue(node, "link", bool.FalseString)); if ( this.m_Link == true ) { this.m_LinkPath = Helper.AttributeValue( node, "linkPath", string.Empty ); } this.m_CopyToOutput = (CopyToOutput) Enum.Parse(typeof(CopyToOutput), Helper.AttributeValue(node, "copyToOutput", this.m_CopyToOutput.ToString())); this.m_PreservePath = bool.Parse( Helper.AttributeValue( node, "preservePath", bool.FalseString ) ); if( node == null ) { throw new ArgumentNullException("node"); } m_Path = Helper.InterpolateForEnvironmentVariables(node.InnerText); if(m_Path == null) { m_Path = ""; } m_Path = m_Path.Trim(); m_Valid = true; if(!File.Exists(m_Path)) { m_Valid = false; Kernel.Instance.Log.Write(LogType.Warning, "File does not exist: {0}", m_Path); } } #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.Collections.Generic; //StackTrace using System.Diagnostics; namespace OLEDB.Test.ModuleCore { //////////////////////////////////////////////////////////////// // CTestCases // //////////////////////////////////////////////////////////////// public class CTestCase : CTestBase//, ITestCases { public delegate int dlgtTestVariation(); //Data private CVariation _curvariation; //Constructor public CTestCase() : this(null) { //Delegate } public CTestCase(string desc) : this(null, desc) { //Delegate } public CTestCase(CTestModule parent, string desc) : base(desc) { Parent = parent; } public virtual void DOTEST() { if (this.Attribute != null) { Console.WriteLine("TestCase:{0} - {1}", this.Attribute.Name, this.Attribute.Desc); } } public override tagVARIATION_STATUS Execute() { List<object> children = Children; if (children != null && children.Count > 0) { // this is not a leaf node, just invoke all the children's execute foreach (object child in children) { CTestCase childTc = child as CTestCase; if (childTc != null) //nested test test case class will be child of a test case { childTc.Init(); childTc.Execute(); continue; } CVariation var = child as CVariation; if (var != null && CModInfo.IsVariationSelected(var.Desc)) { const string indent = "\t"; try { CurVariation = var; tagVARIATION_STATUS ret = var.Execute(); if (tagVARIATION_STATUS.eVariationStatusPassed == ret) { TestModule.PassCount++; } else if (tagVARIATION_STATUS.eVariationStatusFailed == ret) { System.Console.WriteLine(indent + var.Desc); System.Console.WriteLine(indent + " FAILED"); TestModule.FailCount++; } else { TestModule.SkipCount++; } } catch (CTestSkippedException) { TestModule.SkipCount++; } catch (Exception e) { System.Console.WriteLine(indent + var.Desc); System.Console.WriteLine("unexpected exception happend:{0}", e.Message); System.Console.WriteLine(e.StackTrace); System.Console.WriteLine(indent + " FAILED"); TestModule.FailCount++; } } } } return tagVARIATION_STATUS.eVariationStatusPassed; } public void RunVariation(dlgtTestVariation testmethod, Variation curVar) { if (!CModInfo.IsVariationSelected(curVar.Desc)) return; const string indent = "\t"; try { CurVariation.Attribute = curVar; int ret = testmethod(); if (TEST_PASS == ret) { TestModule.PassCount++; } else if (TEST_FAIL == ret) { System.Console.WriteLine(indent + curVar.Desc); System.Console.WriteLine(indent + " FAILED"); TestModule.FailCount++; } else { System.Console.WriteLine(indent + curVar.Desc); System.Console.WriteLine(indent + " SKIPPED"); TestModule.SkipCount++; } } catch (CTestSkippedException tse) { System.Console.WriteLine(indent + curVar.Desc); System.Console.WriteLine(indent + " SKIPPED" + ", Msg:" + tse.Message); TestModule.SkipCount++; } catch (Exception e) { System.Console.WriteLine(indent + curVar.Desc); System.Console.WriteLine("unexpected exception happend:{0}", e.Message); System.Console.WriteLine(e.StackTrace); System.Console.WriteLine(indent + " FAILED"); TestModule.FailCount++; } } //Accessor public CTestModule TestModule { get { if (Parent is CTestModule) return (CTestModule)Parent; else return ((CTestCase)Parent).TestModule; } set { Parent = value; } } //Accessors protected override CAttrBase CreateAttribute() { return new TestCase(); } public new virtual TestCase Attribute { get { return (TestCase)base.Attribute; } set { base.Attribute = value; } } //Helpers public void AddVariation(CVariation variation) { //Delegate this.AddChild(variation); } public CVariation CurVariation { //Return the current variation: //Note: We do this so that within the variation the user can have access to all the //atrributes of that particular method. Unlike the TestModule/TestCase which are objects //and have properties to reference, the variations are function and don't. Each variation //could also have multiple atrributes (repeats), so we can't simply use the StackFrame //to determine this info... get { return _curvariation; } set { _curvariation = value; } } public int GetVariationCount() { return Children.Count; } public virtual int ExecuteVariation(int index, object param) { //Execute the Variation return (int)_curvariation.Execute(); } public virtual tagVARIATION_STATUS ExecuteVariation(int index) { //Track the testcase were in CTestModule testmodule = this.TestModule; if (testmodule != null) testmodule.CurTestCase = this; //Track which variation were executing _curvariation = (CVariation)Children[index]; int result = TEST_FAIL; if (_curvariation.Skipped || !_curvariation.Implemented) { //Skipped result = TEST_SKIPPED; } else { //Execute result = ExecuteVariation(index, _curvariation.Param); } //Before exiting make sure we reset our CurVariation to null, to prevent //incorrect uses of CurVariation wihtin the TestCase, but not actually a running //variation. This will only be valid within a fucntion with a //[Variation] attribute... _curvariation = null; return (tagVARIATION_STATUS)result; } public int GetVariationID(int index) { CVariation variation = (CVariation)Children[index]; return variation.id; } public string GetVariationDesc(int index) { CVariation variation = (CVariation)Children[index]; return variation.GetDescription(); } protected override void DetermineChildren() { AddChildren(); DetermineVariations(); } public virtual void DetermineVariations() { //Default - no sort bool bSort = false; //Normally the reflection Type.GetMethods() api returns the methods in order //of how thery appear in the code. But it will change that order depending //upon if there are virtual functions, which are returned first before other //non-virtual functions. Then there are also inherited classes where the //derived classes methods are returned before the inherted class. So we have //added the support of specifing an id=x, as an attribute so you can have //then sorted and displayed however your see fit. if (bSort) Children.Sort(/*Default sort is based upon IComparable of each item*/); } } }
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.IO; using SharpDX.DXGI; using SharpDX.Direct3D11; using SharpDX.IO; using DeviceChild = SharpDX.Direct3D11.DeviceChild; namespace SharpDX.Toolkit.Graphics { /// <summary> /// Base class for texture resources. /// </summary> public abstract class Texture : GraphicsResource, IComparable<Texture> { private long textureId; /// <summary> /// Common description for this texture. /// </summary> public readonly TextureDescription Description; /// <summary> /// Gets the selector for a <see cref="ShaderResourceView"/> /// </summary> public readonly ShaderResourceViewSelector ShaderResourceView; /// <summary> /// Gets the selector for a <see cref="RenderTargetView"/> /// </summary> public readonly RenderTargetViewSelector RenderTargetView; /// <summary> /// Gets the selector for a <see cref="UnorderedAccessView"/> /// </summary> public readonly UnorderedAccessViewSelector UnorderedAccessView; /// <summary> /// Gets a boolean indicating whether this <see cref="Texture"/> is a using a block compress format (BC1, BC2, BC3, BC4, BC5, BC6H, BC7). /// </summary> public readonly bool IsBlockCompressed; /// <summary> /// The width stride in bytes (number of bytes per row). /// </summary> internal readonly int RowStride; /// <summary> /// The depth stride in bytes (number of bytes per depth slice). /// </summary> internal readonly int DepthStride; internal TextureView defaultShaderResourceView; internal Dictionary<TextureViewKey, TextureView> shaderResourceViews; internal TextureView[] renderTargetViews; internal UnorderedAccessView[] unorderedAccessViews; private MipMapDescription[] mipmapDescriptions; /// <summary> /// /// </summary> /// <param name="device"></param> /// <param name="description"></param> protected Texture(Direct3D11.Device device, TextureDescription description) : base(device) { Description = description; IsBlockCompressed = FormatHelper.IsCompressed(description.Format); RowStride = this.Description.Width * ((PixelFormat)this.Description.Format).SizeInBytes; DepthStride = RowStride * this.Description.Height; ShaderResourceView = new ShaderResourceViewSelector(this); RenderTargetView = new RenderTargetViewSelector(this); UnorderedAccessView = new UnorderedAccessViewSelector(this); mipmapDescriptions = Image.CalculateMipMapDescription(description); } /// <summary> /// <dd> <p>Texture width (in texels). The range is from 1 to <see cref="SharpDX.Direct3D11.Resource.MaximumTexture1DSize"/> (16384). However, the range is actually constrained by the feature level at which you create the rendering device. For more information about restrictions, see Remarks.</p> </dd> /// </summary> /// <remarks> /// This field is valid for all textures: <see cref="Texture1D"/>, <see cref="Texture2D"/>, <see cref="Texture3D"/> and <see cref="TextureCube"/>. /// </remarks> public int Width { get { return Description.Width; } } /// <summary> /// <dd> <p>Texture height (in texels). The range is from 1 to <see cref="SharpDX.Direct3D11.Resource.MaximumTexture3DSize"/> (2048). However, the range is actually constrained by the feature level at which you create the rendering device. For more information about restrictions, see Remarks.</p> </dd> /// </summary> /// <remarks> /// This field is only valid for <see cref="Texture2D"/>, <see cref="Texture3D"/> and <see cref="TextureCube"/>. /// </remarks> public int Height { get { return Description.Height; } } /// <summary> /// <dd> <p>Texture depth (in texels). The range is from 1 to <see cref="SharpDX.Direct3D11.Resource.MaximumTexture3DSize"/> (2048). However, the range is actually constrained by the feature level at which you create the rendering device. For more information about restrictions, see Remarks.</p> </dd> /// </summary> /// <remarks> /// This field is only valid for <see cref="Texture3D"/>. /// </remarks> public int Depth { get { return Description.Depth; } } /// <summary> /// Gets the texture format. /// </summary> /// <value>The texture format.</value> public PixelFormat Format { get { return Description.Format; } } /// <summary> /// /// </summary> /// <param name="resource"></param> protected override void Initialize(DeviceChild resource) { // Be sure that we are storing only the main device (which contains the immediate context). base.Initialize(resource); InitializeViews(); // Gets a Texture ID textureId = resource.NativePointer.ToInt64(); } /// <summary> /// Initializes the views provided by this texture. /// </summary> protected abstract void InitializeViews(); /// <summary> /// Gets the mipmap description of this instance for the specified mipmap level. /// </summary> /// <param name="mipmap">The mipmap.</param> /// <returns>A description of a particular mipmap for this texture.</returns> public MipMapDescription GetMipMapDescription(int mipmap) { return mipmapDescriptions[mipmap]; } /// <summary> /// Calculates the number of miplevels for a Texture 1D. /// </summary> /// <param name="width">The width of the texture.</param> /// <param name="mipLevels">A <see cref="MipMapCount"/>, set to true to calculates all mipmaps, to false to calculate only 1 miplevel, or > 1 to calculate a specific amount of levels.</param> /// <returns>The number of miplevels.</returns> public static int CalculateMipLevels(int width, MipMapCount mipLevels) { if (mipLevels > 1) { int maxMips = CountMips(width); if (mipLevels > maxMips) throw new InvalidOperationException(String.Format("MipLevels must be <= {0}", maxMips)); } else if (mipLevels == 0) { mipLevels = CountMips(width); } else { mipLevels = 1; } return mipLevels; } /// <summary> /// Calculates the number of miplevels for a Texture 2D. /// </summary> /// <param name="width">The width of the texture.</param> /// <param name="height">The height of the texture.</param> /// <param name="mipLevels">A <see cref="MipMapCount"/>, set to true to calculates all mipmaps, to false to calculate only 1 miplevel, or > 1 to calculate a specific amount of levels.</param> /// <returns>The number of miplevels.</returns> public static int CalculateMipLevels(int width, int height, MipMapCount mipLevels) { if (mipLevels > 1) { int maxMips = CountMips(width, height); if (mipLevels > maxMips) throw new InvalidOperationException(String.Format("MipLevels must be <= {0}", maxMips)); } else if (mipLevels == 0) { mipLevels = CountMips(width, height); } else { mipLevels = 1; } return mipLevels; } /// <summary> /// Calculates the number of miplevels for a Texture 2D. /// </summary> /// <param name="width">The width of the texture.</param> /// <param name="height">The height of the texture.</param> /// <param name="depth">The depth of the texture.</param> /// <param name="mipLevels">A <see cref="MipMapCount"/>, set to true to calculates all mipmaps, to false to calculate only 1 miplevel, or > 1 to calculate a specific amount of levels.</param> /// <returns>The number of miplevels.</returns> public static int CalculateMipLevels(int width, int height, int depth, MipMapCount mipLevels) { if (mipLevels > 1) { if (!IsPow2(width) || !IsPow2(height) || !IsPow2(depth)) throw new InvalidOperationException("Width/Height/Depth must be power of 2"); int maxMips = CountMips(width, height, depth); if (mipLevels > maxMips) throw new InvalidOperationException(String.Format("MipLevels must be <= {0}", maxMips)); } else if (mipLevels == 0) { if (!IsPow2(width) || !IsPow2(height) || !IsPow2(depth)) throw new InvalidOperationException("Width/Height/Depth must be power of 2"); mipLevels = CountMips(width, height, depth); } else { mipLevels = 1; } return mipLevels; } /// <summary> /// /// </summary> /// <param name="width"></param> /// <param name="mipLevel"></param> /// <returns></returns> public static int CalculateMipSize(int width, int mipLevel) { mipLevel = Math.Min(mipLevel, CountMips(width)); width = width >> mipLevel; return width > 0 ? width : 1; } /// <summary> /// Gets the absolute sub-resource index from the array and mip slice. /// </summary> /// <param name="arraySlice">The array slice index.</param> /// <param name="mipSlice">The mip slice index.</param> /// <returns>A value equals to arraySlice * Description.MipLevels + mipSlice.</returns> public int GetSubResourceIndex(int arraySlice, int mipSlice) { return arraySlice * Description.MipLevels + mipSlice; } /// <summary> /// Calculates the expected width of a texture using a specified type. /// </summary> /// <typeparam name="TData">The type of the T pixel data.</typeparam> /// <returns>The expected width</returns> /// <exception cref="System.ArgumentException">If the size is invalid</exception> public int CalculateWidth<TData>(int mipLevel = 0) where TData : struct { var widthOnMip = CalculateMipSize((int)Description.Width, mipLevel); var rowStride = widthOnMip * ((PixelFormat) Description.Format).SizeInBytes; var dataStrideInBytes = Utilities.SizeOf<TData>() * widthOnMip; var width = ((double)rowStride / dataStrideInBytes) * widthOnMip; if (Math.Abs(width - (int)width) > Double.Epsilon) throw new ArgumentException("sizeof(TData) / sizeof(Format) * Width is not an integer"); return (int)width; } /// <summary> /// Calculates the number of pixel data this texture is requiring for a particular mip level. /// </summary> /// <typeparam name="TData">The type of the T pixel data.</typeparam> /// <param name="mipLevel">The mip level.</param> /// <returns>The number of pixel data.</returns> /// <remarks>This method is used to allocated a texture data buffer to hold pixel data: var textureData = new T[ texture.CalculatePixelCount&lt;T&gt;() ] ;.</remarks> public int CalculatePixelDataCount<TData>(int mipLevel = 0) where TData : struct { return CalculateWidth<TData>(mipLevel) * CalculateMipSize(Description.Height, mipLevel) * CalculateMipSize(Description.Depth, mipLevel); } /// <summary> /// Makes a copy of this texture. /// </summary> /// <remarks> /// This method doesn't copy the content of the texture. /// </remarks> /// <returns> /// A copy of this texture. /// </returns> public abstract Texture Clone(); /// <summary> /// Makes a copy of this texture with type casting. /// </summary> /// <remarks> /// This method doesn't copy the content of the texture. /// </remarks> /// <returns> /// A copy of this texture. /// </returns> public T Clone<T>() where T : Texture { return (T)this.Clone(); } /// <summary> /// Creates a new texture with the specified generic texture description. /// </summary> /// <param name="graphicsDevice">The graphics device.</param> /// <param name="description">The description.</param> /// <returns>A Texture instance, either a RenderTarget or DepthStencilBuffer or Texture, depending on Binding flags.</returns> public static Texture New(Direct3D11.Device graphicsDevice, TextureDescription description) { if (graphicsDevice == null) { throw new ArgumentNullException("graphicsDevice"); } if ((description.BindFlags & BindFlags.RenderTarget) != 0) { switch (description.Dimension) { case TextureDimension.Texture1D: return RenderTarget1D.New(graphicsDevice, description); case TextureDimension.Texture2D: return RenderTarget2D.New(graphicsDevice, description); case TextureDimension.Texture3D: return RenderTarget3D.New(graphicsDevice, description); case TextureDimension.TextureCube: return RenderTargetCube.New(graphicsDevice, description); } } else if ((description.BindFlags & BindFlags.DepthStencil) != 0) { return DepthStencilBuffer.New(graphicsDevice, description); } else { switch (description.Dimension) { case TextureDimension.Texture1D: return Texture1D.New(graphicsDevice, description); case TextureDimension.Texture2D: return Texture2D.New(graphicsDevice, description); case TextureDimension.Texture3D: return Texture3D.New(graphicsDevice, description); case TextureDimension.TextureCube: return TextureCube.New(graphicsDevice, description); } } return null; } /// <summary> /// Return an equivalent staging texture CPU read-writable from this instance. /// </summary> /// <returns></returns> public abstract Texture ToStaging(); /// <summary> /// Gets a specific <see cref="ShaderResourceView" /> from this texture. /// </summary> /// <param name="viewFormat"></param> /// <param name="viewType">Type of the view slice.</param> /// <param name="arrayOrDepthSlice">The texture array slice index.</param> /// <param name="mipIndex">The mip map slice index.</param> /// <returns>An <see cref="ShaderResourceView" /></returns> internal abstract TextureView GetShaderResourceView(Format viewFormat, ViewType viewType, int arrayOrDepthSlice, int mipIndex); /// <summary> /// Gets a specific <see cref="RenderTargetView" /> from this texture. /// </summary> /// <param name="viewType">Type of the view slice.</param> /// <param name="arrayOrDepthSlice">The texture array slice index.</param> /// <param name="mipMapSlice">The mip map slice index.</param> /// <returns>An <see cref="RenderTargetView" /></returns> internal abstract TextureView GetRenderTargetView(ViewType viewType, int arrayOrDepthSlice, int mipMapSlice); /// <summary> /// Gets a specific <see cref="UnorderedAccessView"/> from this texture. /// </summary> /// <param name="arrayOrDepthSlice">The texture array slice index.</param> /// <param name="mipMapSlice">The mip map slice index.</param> /// <returns>An <see cref="UnorderedAccessView"/></returns> internal abstract UnorderedAccessView GetUnorderedAccessView(int arrayOrDepthSlice, int mipMapSlice); /// <summary> /// ShaderResourceView casting operator. /// </summary> /// <param name="from">Source for the.</param> public static implicit operator ShaderResourceView(Texture from) { return @from == null ? null : from.defaultShaderResourceView; } /// <summary> /// UnorderedAccessView casting operator. /// </summary> /// <param name="from">Source for the.</param> public static implicit operator UnorderedAccessView(Texture from) { return @from == null ? null : @from.unorderedAccessViews != null ? @from.unorderedAccessViews[0] : null; } /// <summary> /// Loads a texture from a stream. /// </summary> /// <param name="device">The <see cref="Direct3D11.Device"/>.</param> /// <param name="stream">The stream to load the texture from.</param> /// <param name="flags">Sets the texture flags (for unordered access...etc.)</param> /// <param name="usage">Usage of the resource. Default is <see cref="ResourceUsage.Immutable"/> </param> /// <returns>A texture</returns> public static Texture Load(Direct3D11.Device device, Stream stream, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable) { var image = Image.Load(stream); if (image == null) { return null; } try { switch (image.Description.Dimension) { case TextureDimension.Texture1D: return Texture1D.New(device, image, flags, usage); case TextureDimension.Texture2D: return Texture2D.New(device, image, flags, usage); case TextureDimension.Texture3D: return Texture3D.New(device, image, flags, usage); case TextureDimension.TextureCube: return TextureCube.New(device, image, flags, usage); } } finally { image.Dispose(); } throw new InvalidOperationException("Dimension not supported"); } /// <summary> /// Loads a texture from a file. /// </summary> /// <param name="device">Specify the device used to load and create a texture from a file.</param> /// <param name="filePath">The file to load the texture from.</param> /// <param name="flags">Sets the texture flags (for unordered access...etc.)</param> /// <param name="usage">Usage of the resource. Default is <see cref="ResourceUsage.Immutable"/> </param> /// <returns>A texture</returns> public static Texture Load(Direct3D11.Device device, string filePath, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable) { using (var stream = new NativeFileStream(filePath, NativeFileMode.Open, NativeFileAccess.Read)) return Load(device, stream, flags, usage); } /// <summary> /// Calculates the mip map count from a requested level. /// </summary> /// <param name="requestedLevel">The requested level.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="depth">The depth.</param> /// <returns>The resulting mipmap count (clamp to [1, maxMipMapCount] for this texture)</returns> internal static int CalculateMipMapCount(MipMapCount requestedLevel, int width, int height = 0, int depth = 0) { int size = Math.Max(Math.Max(width, height), depth); int maxMipMap = 1 + (int)Math.Log(size, 2); return requestedLevel == 0 ? maxMipMap : Math.Min(requestedLevel, maxMipMap); } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="format"></param> /// <param name="width"></param> /// <param name="height"></param> /// <param name="depth"></param> /// <param name="textureData"></param> /// <param name="fixedPointer"></param> /// <returns></returns> protected static DataBox GetDataBox<T>(Format format, int width, int height, int depth, T[] textureData, IntPtr fixedPointer) where T : struct { // Check that the textureData size is correct if (textureData == null) throw new ArgumentNullException("textureData"); int rowPitch; int slicePitch; int widthCount; int heightCount; Image.ComputePitch(format, width, height, out rowPitch, out slicePitch, out widthCount, out heightCount); if (Utilities.SizeOf(textureData) != (slicePitch * depth)) throw new ArgumentException("Invalid size for TextureData"); return new DataBox(fixedPointer, rowPitch, slicePitch); } internal static TextureDescription CreateTextureDescriptionFromImage(Image image, TextureFlags flags, ResourceUsage usage) { var desc = (TextureDescription)image.Description; desc.BindFlags = BindFlags.ShaderResource; desc.Usage = usage; if ((flags & TextureFlags.UnorderedAccess) != 0) desc.Usage = ResourceUsage.Default; desc.BindFlags = GetBindFlagsFromTextureFlags(flags); desc.CpuAccessFlags = GetCpuAccessFlagsFromUsage(usage); return desc; } internal void GetViewSliceBounds(ViewType viewType, ref int arrayOrDepthIndex, ref int mipIndex, out int arrayOrDepthCount, out int mipCount) { int arrayOrDepthSize = this.Description.Depth > 1 ? this.Description.Depth : this.Description.ArraySize; switch (viewType) { case ViewType.Full: arrayOrDepthIndex = 0; mipIndex = 0; arrayOrDepthCount = arrayOrDepthSize; mipCount = this.Description.MipLevels; break; case ViewType.Single: arrayOrDepthCount = 1; mipCount = 1; break; case ViewType.MipBand: arrayOrDepthCount = arrayOrDepthSize - arrayOrDepthIndex; mipCount = 1; break; case ViewType.ArrayBand: arrayOrDepthCount = 1; mipCount = Description.MipLevels - mipIndex; break; default: arrayOrDepthCount = 0; mipCount = 0; break; } } internal int GetViewCount() { int arrayOrDepthSize = this.Description.Depth > 1 ? this.Description.Depth : this.Description.ArraySize; return GetViewIndex((ViewType)4, arrayOrDepthSize, this.Description.MipLevels); } internal int GetViewIndex(ViewType viewType, int arrayOrDepthIndex, int mipIndex) { int arrayOrDepthSize = this.Description.Depth > 1 ? this.Description.Depth : this.Description.ArraySize; return (((int)viewType) * arrayOrDepthSize + arrayOrDepthIndex) * this.Description.MipLevels + mipIndex; } /// <summary> /// Called when name changed for this component. /// </summary> protected override void OnPropertyChanged(string propertyName) { base.OnPropertyChanged(propertyName); if (propertyName == "Name") { if ((((Direct3D11.Device)GraphicsDevice).CreationFlags & DeviceCreationFlags.Debug) != 0) { if (this.shaderResourceViews != null) { int i = 0; foreach(var shaderResourceViewItem in shaderResourceViews) { var shaderResourceView = shaderResourceViewItem.Value; if (shaderResourceView != null) shaderResourceView.View.DebugName = Name == null ? null : String.Format("{0} SRV[{1}]", i, Name); i++; } } if (this.renderTargetViews != null) { for (int i = 0; i < this.renderTargetViews.Length; i++) { var renderTargetView = this.renderTargetViews[i]; if (renderTargetView != null) renderTargetView.View.DebugName = Name == null ? null : String.Format("{0} RTV[{1}]", i, Name); } } if (this.unorderedAccessViews != null) { for (int i = 0; i < this.unorderedAccessViews.Length; i++) { var unorderedAccessView = this.unorderedAccessViews[i]; if (unorderedAccessView != null) unorderedAccessView.DebugName = Name == null ? null : String.Format("{0} UAV[{1}]", i, Name); } } } } } private static bool IsPow2( int x ) { return ((x != 0) && (x & (x - 1)) == 0); } private static int CountMips(int width) { int mipLevels = 1; while (width > 1) { ++mipLevels; if (width > 1) width >>= 1; } return mipLevels; } private static int CountMips(int width, int height) { int mipLevels = 1; while (height > 1 || width > 1) { ++mipLevels; if (height > 1) height >>= 1; if (width > 1) width >>= 1; } return mipLevels; } private static int CountMips(int width, int height, int depth) { int mipLevels = 1; while (height > 1 || width > 1 || depth > 1) { ++mipLevels; if (height > 1) height >>= 1; if (width > 1) width >>= 1; if (depth > 1) depth >>= 1; } return mipLevels; } /// <summary> /// /// </summary> /// <param name="obj"></param> /// <returns></returns> public int CompareTo(Texture obj) { return textureId.CompareTo(obj.textureId); } internal static BindFlags GetBindFlagsFromTextureFlags(TextureFlags flags) { var bindFlags = BindFlags.None; if ((flags & TextureFlags.ShaderResource) != 0) bindFlags |= BindFlags.ShaderResource; if ((flags & TextureFlags.UnorderedAccess) != 0) bindFlags |= BindFlags.UnorderedAccess; if ((flags & TextureFlags.RenderTarget) != 0) bindFlags |= BindFlags.RenderTarget; return bindFlags; } internal struct TextureViewKey : IEquatable<TextureViewKey> { public TextureViewKey(Format viewFormat, ViewType viewType, int arrayOrDepthSlice, int mipIndex) { ViewFormat = viewFormat; ViewType = viewType; ArrayOrDepthSlice = arrayOrDepthSlice; MipIndex = mipIndex; } public readonly DXGI.Format ViewFormat; public readonly ViewType ViewType; public readonly int ArrayOrDepthSlice; public readonly int MipIndex; public bool Equals(TextureViewKey other) { return ViewFormat == other.ViewFormat && ViewType == other.ViewType && ArrayOrDepthSlice == other.ArrayOrDepthSlice && MipIndex == other.MipIndex; } public override bool Equals(object obj) { if(ReferenceEquals(null, obj)) return false; return obj is TextureViewKey && Equals((TextureViewKey)obj); } public override int GetHashCode() { unchecked { var hashCode = (int)ViewFormat; hashCode = (hashCode * 397) ^ (int)ViewType; hashCode = (hashCode * 397) ^ ArrayOrDepthSlice; hashCode = (hashCode * 397) ^ MipIndex; return hashCode; } } public static bool operator ==(TextureViewKey left, TextureViewKey right) { return left.Equals(right); } public static bool operator !=(TextureViewKey left, TextureViewKey right) { return !left.Equals(right); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Globalization; //test case for delegate RemoveImpl(System.Delegate) method. namespace DelegateTest { delegate bool booldelegate(); public class DelegateRemoveImpl { booldelegate starkWork; public static int Main() { DelegateRemoveImpl delegateRemoveImpl = new DelegateRemoveImpl(); TestLibrary.TestFramework.BeginTestCase("DelegateRemoveImpl"); if (delegateRemoveImpl.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal;//static method return retVal; } // Returns true if the expected result is right // Returns false if the expected result is wrong public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Remove a function from the delegate which contains only 1 callback function"); try { DelegateRemoveImpl delctor = new DelegateRemoveImpl(); TestClass tcInstance = new TestClass(); delctor.starkWork = new booldelegate(tcInstance.StartWork_Bool); delctor.starkWork -= new booldelegate(tcInstance.StartWork_Bool); if (null != delctor.starkWork) { TestLibrary.TestFramework.LogError("001", "remove failure " ); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } // Returns true if the expected result is right // Returns false if the expected result is wrong public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Remove a function which is in the InvocationList"); try { DelegateRemoveImpl delctor = new DelegateRemoveImpl(); TestClass tcInstance = new TestClass(); booldelegate bStartWork_Bool = new booldelegate(tcInstance.StartWork_Bool); booldelegate bWorking_Bool = new booldelegate(tcInstance.Working_Bool); booldelegate bCompleted_Bool = new booldelegate(tcInstance.Completed_Bool); delctor.starkWork += bStartWork_Bool; delctor.starkWork += bWorking_Bool; delctor.starkWork += bCompleted_Bool; delctor.starkWork -= bWorking_Bool; Delegate[] invocationList = delctor.starkWork.GetInvocationList(); if (invocationList.Length != 2) { TestLibrary.TestFramework.LogError("003", "remove failure or remove method is not in the InvocationList"); retVal = false; } if (!delctor.starkWork.GetInvocationList()[0].Equals(bStartWork_Bool) || !delctor.starkWork.GetInvocationList()[1].Equals(bCompleted_Bool)) { TestLibrary.TestFramework.LogError("004", " remove failure "); retVal = false; } delctor.starkWork(); } catch (Exception e) { TestLibrary.TestFramework.LogError("005", "Unexpected exception: " + e); retVal = false; } return retVal; } // Returns true if the expected result is right // Returns false if the expected result is wrong public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Remove a function which is not in the InvocationList"); try { DelegateRemoveImpl delctor = new DelegateRemoveImpl(); booldelegate bStartWork_Bool = new booldelegate(new TestClass().StartWork_Bool); booldelegate bWorking_Bool = new booldelegate(new TestClass().Working_Bool); booldelegate bCompleted_Bool = new booldelegate(new TestClass().Completed_Bool); booldelegate bOther_bool = new booldelegate(TestClass1.Other_Bool); delctor.starkWork += bStartWork_Bool; delctor.starkWork += bWorking_Bool; delctor.starkWork += bCompleted_Bool; Delegate[] beforeList = delctor.starkWork.GetInvocationList(); delctor.starkWork -= bOther_bool; Delegate[] afterList = delctor.starkWork.GetInvocationList(); if (beforeList.Length != afterList.Length) { TestLibrary.TestFramework.LogError("006", String.Format("Remove changed invocation list length from {0} to {1}", beforeList.Length, afterList.Length)); retVal = false; } else { for (int i=0; i<beforeList.Length; i++) if (!beforeList[i].Equals(afterList[i])) { TestLibrary.TestFramework.LogError("006a", String.Format( "Invocation lists differ at element {0}", i)); retVal=false; } } delctor.starkWork(); } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } // Returns true if the expected result is right // Returns false if the expected result is wrong public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Remove a function which is in the InvocationList and not only one method"); try { DelegateRemoveImpl delctor = new DelegateRemoveImpl(); TestClass tcInstance = new TestClass(); booldelegate bStartWork_Bool = new booldelegate(tcInstance.StartWork_Bool); booldelegate bWorking_Bool = new booldelegate(tcInstance.Working_Bool); booldelegate bCompleted_Bool = new booldelegate(tcInstance.Completed_Bool); delctor.starkWork += bStartWork_Bool; delctor.starkWork += bStartWork_Bool; delctor.starkWork += bWorking_Bool; delctor.starkWork += bCompleted_Bool; delctor.starkWork -= bStartWork_Bool; Delegate[] invocationList = delctor.starkWork.GetInvocationList(); if (invocationList.Length !=3) { TestLibrary.TestFramework.LogError("009", "remove failure: " + invocationList.Length); retVal = false; } if (!delctor.starkWork.GetInvocationList()[0].Equals(bStartWork_Bool) || !delctor.starkWork.GetInvocationList()[1].Equals(bWorking_Bool) || !delctor.starkWork.GetInvocationList()[2].Equals(bCompleted_Bool)) { TestLibrary.TestFramework.LogError("010", " remove failure "); retVal = false; } delctor.starkWork(); } catch (Exception e) { TestLibrary.TestFramework.LogError("011", "Unexpected exception: " + e); retVal = false; } return retVal; } // Returns true if the expected result is right // Returns false if the expected result is wrong public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Remove a function which is in the InvocationList and not only one method ,method is static method"); try { DelegateRemoveImpl delctor = new DelegateRemoveImpl(); booldelegate bStartWork_Bool = new booldelegate(TestClass1.StartWork_Bool); booldelegate bWorking_Bool = new booldelegate(TestClass1.Working_Bool); booldelegate bCompleted_Bool = new booldelegate(TestClass1.Completed_Bool); delctor.starkWork += bStartWork_Bool; delctor.starkWork += bStartWork_Bool; delctor.starkWork += bWorking_Bool; delctor.starkWork += bCompleted_Bool; delctor.starkWork -= bStartWork_Bool; Delegate[] invocationList = delctor.starkWork.GetInvocationList(); if (invocationList.Length != 3) { TestLibrary.TestFramework.LogError("012", "remove failure: " + invocationList.Length); retVal = false; } if (!delctor.starkWork.GetInvocationList()[0].Equals(bStartWork_Bool) || !delctor.starkWork.GetInvocationList()[1].Equals(bWorking_Bool) || !delctor.starkWork.GetInvocationList()[2].Equals(bCompleted_Bool)) { TestLibrary.TestFramework.LogError("013", " remove failure "); retVal = false; } delctor.starkWork(); } catch (Exception e) { TestLibrary.TestFramework.LogError("014", "Unexpected exception: " + e); retVal = false; } return retVal; } } //create testclass for provding test method and test target. class TestClass { public bool StartWork_Bool() { TestLibrary.TestFramework.LogInformation("StartWork_Bool method is running ."); return true; } public bool Working_Bool() { TestLibrary.TestFramework.LogInformation("Working_Bool method is running ."); return true; } public bool Completed_Bool() { TestLibrary.TestFramework.LogInformation("Completed_Bool method is running ."); return true; } } class TestClass1 { public static bool StartWork_Bool() { TestLibrary.TestFramework.LogInformation("StartWork_Bool method is running ."); return true; } public static bool Working_Bool() { TestLibrary.TestFramework.LogInformation("Working_Bool method is running ."); return true; } public static bool Completed_Bool() { TestLibrary.TestFramework.LogInformation("Completed_Bool method is running ."); return true; } public static bool Other_Bool() { TestLibrary.TestFramework.LogInformation("Other_Bool method is running ."); return true; } } }
using System; using System.ComponentModel; using System.Globalization; using System.Linq.Expressions; using System.Reflection; using System.Text.RegularExpressions; namespace Signum.Utilities { public static class DateTimeExtensions { /// <summary> /// Checks if the date is inside a C interval defined by the two given dates /// </summary> [MethodExpander(typeof(IsInIntervalExpander))] public static bool IsInInterval(this DateTime date, DateTime minDate, DateTime maxDate) { return minDate <= date && date < maxDate; } /// <summary> /// Checks if the date is inside a C interval defined by the two given dates /// </summary> [MethodExpander(typeof(IsInIntervalExpanderNull))] public static bool IsInInterval(this DateTime date, DateTime minDate, DateTime? maxDate) { return minDate <= date && (maxDate == null || date < maxDate); } /// <summary> /// Checks if the date is inside a C interval defined by the two given dates /// </summary> [MethodExpander(typeof(IsInIntervalExpanderNullNull))] public static bool IsInInterval(this DateTime date, DateTime? minDate, DateTime? maxDate) { return (minDate == null || minDate <= date) && (maxDate == null || date < maxDate); } static void AssertDateOnly(DateTime? date) { if (date == null) return; DateTime d = date.Value; if (d.Hour != 0 || d.Minute != 0 || d.Second != 0 || d.Millisecond != 0) throw new InvalidOperationException("The date has some hours, minutes, seconds or milliseconds"); } /// <summary> /// Checks if the date is inside a date-only interval (compared by entires days) defined by the two given dates /// </summary> [MethodExpander(typeof(IsInIntervalExpander))] public static bool IsInDateInterval(this DateTime date, DateTime minDate, DateTime maxDate) { AssertDateOnly(date); AssertDateOnly(minDate); AssertDateOnly(maxDate); return minDate <= date && date <= maxDate; } /// <summary> /// Checks if the date is inside a date-only interval (compared by entires days) defined by the two given dates /// </summary> [MethodExpander(typeof(IsInIntervalExpanderNull))] public static bool IsInDateInterval(this DateTime date, DateTime minDate, DateTime? maxDate) { AssertDateOnly(date); AssertDateOnly(minDate); AssertDateOnly(maxDate); return (minDate == null || minDate <= date) && (maxDate == null || date < maxDate); } /// <summary> /// Checks if the date is inside a date-only interval (compared by entires days) defined by the two given dates /// </summary> [MethodExpander(typeof(IsInIntervalExpanderNullNull))] public static bool IsInDateInterval(this DateTime date, DateTime? minDate, DateTime? maxDate) { AssertDateOnly(date); AssertDateOnly(minDate); AssertDateOnly(maxDate); return (minDate == null || minDate <= date) && (maxDate == null || date < maxDate); } class IsInIntervalExpander : IMethodExpander { static readonly Expression<Func<DateTime, DateTime, DateTime, bool>> func = (date, minDate, maxDate) => minDate <= date && date < maxDate; public Expression Expand(Expression instance, Expression[] arguments, MethodInfo mi) { return Expression.Invoke(func, arguments[0], arguments[1], arguments[2]); } } class IsInIntervalExpanderNull : IMethodExpander { Expression<Func<DateTime, DateTime, DateTime?, bool>> func = (date, minDate, maxDate) => minDate <= date && (maxDate == null || date < maxDate); public Expression Expand(Expression instance, Expression[] arguments, MethodInfo mi) { return Expression.Invoke(func, arguments[0], arguments[1], arguments[2]); } } class IsInIntervalExpanderNullNull : IMethodExpander { Expression<Func<DateTime, DateTime?, DateTime?, bool>> func = (date, minDate, maxDate) => (minDate == null || minDate <= date) && (maxDate == null || date < maxDate); public Expression Expand(Expression instance, Expression[] arguments, MethodInfo mi) { return Expression.Invoke(func, arguments[0], arguments[1], arguments[2]); } } public static int YearsTo(this DateTime start, DateTime end) { int result = end.Year - start.Year; if (end < start.AddYears(result)) result--; return result; } public static int YearsTo(this Date start, Date end) { int result = end.Year - start.Year; if (end < start.AddYears(result)) result--; return result; } public static int MonthsTo(this DateTime start, DateTime end) { int result = end.Month - start.Month + (end.Year - start.Year) * 12; if (end < start.AddMonths(result)) result--; return result; } public static int MonthsTo(this Date start, Date end) { int result = end.Month - start.Month + (end.Year - start.Year) * 12; if (end < start.AddMonths(result)) result--; return result; } public static double TotalMonths(this DateTime start, DateTime end) { int wholeMonths = start.MonthsTo(end); double result = wholeMonths; DateTime limit = start.AddMonths(wholeMonths); DateTime limitMonthStart = limit.MonthStart(); DateTime nextMonthStart = limitMonthStart.AddMonths(1); if (nextMonthStart < end) { result += ((nextMonthStart - limit).TotalDays / NumberOfDaysAfterOneMonth(limitMonthStart)); result += ((end - nextMonthStart).TotalDays / NumberOfDaysAfterOneMonth(nextMonthStart)); } else { result += ((end - limit).TotalDays / NumberOfDaysAfterOneMonth(limitMonthStart)); } return result; } static double NumberOfDaysAfterOneMonth(DateTime monthStart) { return (monthStart.AddMonths(1) - monthStart).TotalDays; } public static DateSpan DateSpanTo(this DateTime min, DateTime max) { return DateSpan.FromToDates(min, max); } public static DateTime Add(this DateTime date, DateSpan dateSpan) { return dateSpan.AddTo(date); } public static DateTime Min(this DateTime a, DateTime b) { return a < b ? a : b; } public static DateTime Max(this DateTime a, DateTime b) { return a > b ? a : b; } public static DateTime Min(this DateTime a, DateTime? b) { if (b == null) return a; return a < b.Value ? a : b.Value; } public static DateTime Max(this DateTime a, DateTime? b) { if (b == null) return a; return a > b.Value ? a : b.Value; } public static DateTime? Min(this DateTime? a, DateTime? b) { if (a == null) return b; if (b == null) return a; return a.Value < b.Value ? a.Value : b.Value; } public static DateTime? Max(this DateTime? a, DateTime? b) { if (a == null) return b; if (b == null) return a; return a.Value > b.Value ? a.Value : b.Value; } /// <param name="precision">Using Milliseconds does nothing, using Days use DateTime.Date</param> public static DateTime TrimTo(this DateTime dateTime, DateTimePrecision precision) { switch (precision) { case DateTimePrecision.Days: return dateTime.Date; case DateTimePrecision.Hours: return TrimToHours(dateTime); case DateTimePrecision.Minutes: return TrimToMinutes(dateTime); case DateTimePrecision.Seconds: return TrimToSeconds(dateTime); case DateTimePrecision.Milliseconds: return dateTime; } throw new ArgumentException("precision"); } public static DateTime TrimToSeconds(this DateTime dateTime) { return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Kind); } public static DateTime TrimToMinutes(this DateTime dateTime) { return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, 0, dateTime.Kind); } public static DateTime TrimToHours(this DateTime dateTime) { return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, 0, 0, dateTime.Kind); } public static DateTimePrecision GetPrecision(this DateTime dateTime) { if (dateTime.Millisecond != 0) return DateTimePrecision.Milliseconds; if (dateTime.Second != 0) return DateTimePrecision.Seconds; if (dateTime.Minute != 0) return DateTimePrecision.Minutes; if (dateTime.Hour != 0) return DateTimePrecision.Hours; return DateTimePrecision.Days; } static char[] allStandardFormats = new char[] { 'd', 'D', 'f', 'F', 'g', 'G', 'm', 'M', 'o', 'O', 'r', 'R', 's', 't', 'T', 'u', 'U', 'y', 'Y' }; public static string? ToCustomFormatString(string? f, CultureInfo culture) { if (f != null && f.Length == 1 && allStandardFormats.IndexOf(f[0]) != -1) return culture.DateTimeFormat.GetAllDateTimePatterns(f[0]).FirstEx(); return f; } public static string SmartShortDatePattern(this DateTime date) { DateTime currentdate = DateTime.Today; return SmartShortDatePattern(date, currentdate); } public static string SmartShortDatePattern(this DateTime date, DateTime currentdate) { int datediff = (date.Date - currentdate).Days; if (-7 <= datediff && datediff <= -2) return DateTimeMessage.Last0.NiceToString(CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedDayName(date.DayOfWeek).FirstUpper()); if (datediff == -1) return DateTimeMessage.Yesterday.NiceToString(); if (datediff == 0) return DateTimeMessage.Today.NiceToString(); if (datediff == 1) return DateTimeMessage.Tomorrow.NiceToString(); if (2 <= datediff && datediff <= 7) return DateTimeMessage.This0.NiceToString(CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedDayName(date.DayOfWeek).FirstUpper()); if (date.Year == currentdate.Year) return date.ToString("d MMM"); return date.ToString("d MMMM yyyy"); } public static string SmartDatePattern(this DateTime date) { DateTime currentdate = DateTime.Today; return SmartDatePattern(date, currentdate); } public static string SmartDatePattern(this DateTime date, DateTime currentdate) { int datediff = (date.Date - currentdate).Days; if (-7 <= datediff && datediff <= -2) return DateTimeMessage.Last0.NiceToString(CultureInfo.CurrentCulture.DateTimeFormat.GetDayName(date.DayOfWeek).FirstUpper()); if (datediff == -1) return DateTimeMessage.Yesterday.NiceToString(); if (datediff == 0) return DateTimeMessage.Today.NiceToString(); if (datediff == 1) return DateTimeMessage.Tomorrow.NiceToString(); if (2 <= datediff && datediff <= 7) return DateTimeMessage.This0.NiceToString(CultureInfo.CurrentCulture.DateTimeFormat.GetDayName(date.DayOfWeek).FirstUpper()); if (date.Year == currentdate.Year) { string pattern = CultureInfo.CurrentCulture.DateTimeFormat.LongDatePattern; pattern = Regex.Replace(pattern, "('[^']*')?yyy?y?('[^']*')?", ""); string dateString = date.ToString(pattern); return dateString.Trim().FirstUpper(); } return date.ToLongDateString(); } public static string ToAgoString(this DateTime dateTime) { return ToAgoString(dateTime, dateTime.Kind == DateTimeKind.Utc ? DateTime.UtcNow : DateTime.Now); } public static string ToAgoString(this DateTime dateTime, DateTime now) { TimeSpan ts = now.Subtract(dateTime); string? resource = null; if (ts.TotalMilliseconds < 0) resource = DateTimeMessage.In0.NiceToString(); else resource = DateTimeMessage._0Ago.NiceToString(); int months = Math.Abs(ts.Days) / 30; if (months > 0) return resource.FormatWith((months == 1 ? DateTimeMessage._0Month.NiceToString() : DateTimeMessage._0Months.NiceToString()).FormatWith(Math.Abs(months))).ToLower(); if (Math.Abs(ts.Days) > 0) return resource.FormatWith((ts.Days == 1 ? DateTimeMessage._0Day.NiceToString() : DateTimeMessage._0Days.NiceToString()).FormatWith(Math.Abs(ts.Days))).ToLower(); if (Math.Abs(ts.Hours) > 0) return resource.FormatWith((ts.Hours == 1 ? DateTimeMessage._0Hour.NiceToString() : DateTimeMessage._0Hours.NiceToString()).FormatWith(Math.Abs(ts.Hours))).ToLower(); if (Math.Abs(ts.Minutes) > 0) return resource.FormatWith((ts.Minutes == 1 ? DateTimeMessage._0Minute.NiceToString() : DateTimeMessage._0Minutes.NiceToString()).FormatWith(Math.Abs(ts.Minutes))).ToLower(); return resource.FormatWith((ts.Seconds == 1 ? DateTimeMessage._0Second.NiceToString() : DateTimeMessage._0Seconds.NiceToString()).FormatWith(Math.Abs(ts.Seconds))).ToLower(); } public static long JavascriptMilliseconds(this DateTime dateTime) { if (dateTime.Kind != DateTimeKind.Utc) throw new InvalidOperationException("dateTime should be UTC"); return (long)new TimeSpan(dateTime.Ticks - new DateTime(1970, 1, 1).Ticks).TotalMilliseconds; } public static DateTime YearStart(this DateTime dateTime) { return new DateTime(dateTime.Year, 1, 1, 0, 0, 0, dateTime.Kind); } public static Date YearStart(this Date date) { return new Date(date.Year, 1, 1); } public static DateTime QuarterStart(this DateTime dateTime) { var quarterMonthStart = (((dateTime.Month - 1) / 4) * 4) + 1; return new DateTime(dateTime.Year, quarterMonthStart, 1, 0, 0, 0, dateTime.Kind); } public static Date QuarterStart(this Date date) { var quarterMonthStart = (((date.Month - 1) / 4) * 4) + 1; return new Date(date.Year, quarterMonthStart, 1); } public static int Quarter(this DateTime dateTime) { return ((dateTime.Month - 1) / 4) + 1; } public static int Quarter(this Date date) { return ((date.Month - 1) / 4) + 1; } public static DateTime MonthStart(this DateTime dateTime) { return new DateTime(dateTime.Year, dateTime.Month, 1, 0, 0, 0, dateTime.Kind); } public static Date MonthStart(this Date date) { return new Date(date.Year, date.Month, 1); } public static DateTime WeekStart(this DateTime dateTime) { return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 0, 0, 0, dateTime.Kind).AddDays(-(int)dateTime.DayOfWeek); } public static Date WeekStart(this Date date) { return new Date(date.Year, date.Month, date.Day).AddDays(-(int)date.DayOfWeek); } public static DateTime HourStart(this DateTime dateTime) { return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, 0, 0, dateTime.Kind); } public static DateTime MinuteStart(this DateTime dateTime) { return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, 0, dateTime.Kind); } public static DateTime SecondStart(this DateTime dateTime) { return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Kind); } public static string ToMonthName(this DateTime dateTime) { return CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(dateTime.Month); } public static string ToShortMonthName(this DateTime dateTime) { return CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(dateTime.Month); } public static int WeekNumber(this DateTime dateTime) { var cc = CultureInfo.CurrentCulture; return cc.Calendar.GetWeekOfYear(dateTime, cc.DateTimeFormat.CalendarWeekRule, cc.DateTimeFormat.FirstDayOfWeek); } public static int WeekNumber(this Date date) { var cc = CultureInfo.CurrentCulture; return cc.Calendar.GetWeekOfYear(date, cc.DateTimeFormat.CalendarWeekRule, cc.DateTimeFormat.FirstDayOfWeek); } /// <summary> /// Returns the unix time (also known as POSIX time or epoch time) for the give date time. /// </summary> /// The unix time is defined as the number of seconds, that have elapsed since Thursday, 1 January 1970 00:00:00 (UTC). /// <param name="dateTime"></param> public static long ToUnixTimeSeconds(this DateTime dateTime) { return new DateTimeOffset(dateTime).ToUnixTimeSeconds(); } /// <summary> /// Returns the unix time (also known as POSIX time or epoch time) for the give date time in milliseconds. /// </summary> /// The unix time is defined as the number of milliseconds, that have elapsed since Thursday, 1 January 1970 00:00:00 (UTC). /// <param name="dateTime"></param> public static long ToUnixTimeMilliseconds(this DateTime dateTime) { return new DateTimeOffset(dateTime).ToUnixTimeMilliseconds(); } } [DescriptionOptions(DescriptionOptions.Members)] public enum DateTimePrecision { Days, Hours, Minutes, Seconds, Milliseconds, } public struct DateSpan { public static readonly DateSpan Zero = new DateSpan(0, 0, 0); public readonly int Years; public readonly int Months; public readonly int Days; public DateSpan(int years, int months, int days) { int sign = Math.Sign(years).DefaultToNull() ?? Math.Sign(months).DefaultToNull() ?? Math.Sign(days); if (0 < sign && (months < 0 || days < 0) || sign < 0 && (0 < months || 0 < days)) throw new ArgumentException("All arguments should have the same sign"); this.Years = years; this.Months = months; this.Days = days; } public static DateSpan FromToDates(DateTime min, DateTime max) { if (min > max) return FromToDates(max, min).Invert(); int years = max.Year - min.Year; int months = max.Month - min.Month; if (max.Day < min.Day) months -= 1; if (months < 0) { years -= 1; months += 12; } int days = max.Subtract(min.AddYears(years).AddMonths(months)).Days; return new DateSpan(years, months, days); } public DateTime AddTo(DateTime date) { return date.AddDays(Days).AddMonths(Months).AddYears(Years); } public DateSpan Invert() { return new DateSpan(-Years, -Months, -Days); } public override string ToString() { string result = ", ".Combine( Years == 0 ? null : Years == 1 ? DateTimeMessage._0Year.NiceToString().FormatWith(Years) : DateTimeMessage._0Years.NiceToString().FormatWith(Years), Months == 0 ? null : Months == 1 ? DateTimeMessage._0Month.NiceToString().FormatWith(Months) : DateTimeMessage._0Months.NiceToString().FormatWith(Months), Days == 0 ? null : Days == 1 ? DateTimeMessage._0Day.NiceToString().FormatWith(Days) : DateTimeMessage._0Days.NiceToString().FormatWith(Days)); if (string.IsNullOrEmpty(result)) result = DateTimeMessage._0Day.NiceToString().FormatWith(0); return result; } } public enum DateTimeMessage { [Description("{0} Day")] _0Day, [Description("{0} Days")] _0Days, [Description("{0} Hour")] _0Hour, [Description("{0} Hours")] _0Hours, [Description("{0} Minute")] _0Minute, [Description("{0} Minutes")] _0Minutes, [Description("{0} Week")] _0Week, [Description("{0} Weeks")] _0Weeks, [Description("{0} Month")] _0Month, [Description("{0} Months")] _0Months, [Description("{0} Second")] _0Second, [Description("{0} Seconds")] _0Seconds, [Description("{0} Year")] _0Year, [Description("{0} Years")] _0Years, [Description("{0} ago")] _0Ago, [Description("Last {0}")] Last0, [Description("This {0}")] This0, [Description("In {0}")] In0, Today, Tomorrow, Yesterday } }
using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using Avalonia.Collections; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Controls.Selection; using Avalonia.Controls.Templates; using Avalonia.Data; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Data; using Avalonia.Styling; using Avalonia.UnitTests; using Moq; using Xunit; namespace Avalonia.Controls.UnitTests.Primitives { public partial class SelectingItemsControlTests { private MouseTestHelper _helper = new MouseTestHelper(); [Fact] public void SelectedIndex_Should_Initially_Be_Minus_1() { var items = new[] { new Item(), new Item(), }; var target = new SelectingItemsControl { Items = items, Template = Template(), }; Assert.Equal(-1, target.SelectedIndex); } [Fact] public void Item_IsSelected_Should_Initially_Be_False() { var items = new[] { new Item(), new Item(), }; var target = new SelectingItemsControl { Items = items, Template = Template(), }; Prepare(target); Assert.False(items[0].IsSelected); Assert.False(items[1].IsSelected); } [Fact] public void Setting_SelectedItem_Should_Set_Item_IsSelected_True() { var items = new[] { new Item(), new Item(), }; var target = new SelectingItemsControl { Items = items, Template = Template(), }; Prepare(target); target.SelectedItem = items[1]; Assert.False(items[0].IsSelected); Assert.True(items[1].IsSelected); } [Fact] public void Setting_SelectedItem_Before_ApplyTemplate_Should_Set_Item_IsSelected_True() { var items = new[] { new Item(), new Item(), }; var target = new SelectingItemsControl { Items = items, Template = Template(), }; target.SelectedItem = items[1]; Prepare(target); Assert.False(items[0].IsSelected); Assert.True(items[1].IsSelected); } [Fact] public void SelectedIndex_Should_Be_Minus_1_After_Initialize() { var items = new[] { new Item(), new Item(), }; var target = new ListBox(); target.BeginInit(); target.Items = items; target.Template = Template(); target.EndInit(); Assert.Equal(-1, target.SelectedIndex); } [Fact] public void SelectedIndex_Should_Be_Minus_1_Without_Initialize() { var items = new[] { new Item(), new Item(), }; var target = new ListBox(); target.Items = items; target.Template = Template(); target.DataContext = new object(); Assert.Equal(-1, target.SelectedIndex); } [Fact] public void SelectedIndex_Should_Be_0_After_Initialize_With_AlwaysSelected() { var items = new[] { new Item(), new Item(), }; var target = new ListBox(); target.BeginInit(); target.SelectionMode = SelectionMode.Single | SelectionMode.AlwaysSelected; target.Items = items; target.Template = Template(); target.EndInit(); Prepare(target); Assert.Equal(0, target.SelectedIndex); } [Fact] public void Setting_SelectedIndex_During_Initialize_Should_Select_Item_When_AlwaysSelected_Is_Used() { var listBox = new ListBox { SelectionMode = SelectionMode.Single | SelectionMode.AlwaysSelected }; listBox.BeginInit(); listBox.SelectedIndex = 1; var items = new AvaloniaList<string>(); listBox.Items = items; items.Add("A"); items.Add("B"); items.Add("C"); listBox.EndInit(); Prepare(listBox); Assert.Equal("B", listBox.SelectedItem); } [Fact] public void Setting_SelectedIndex_Before_Initialize_Should_Retain_Selection() { var listBox = new ListBox { SelectionMode = SelectionMode.Single, Items = new[] { "foo", "bar", "baz" }, SelectedIndex = 1 }; listBox.BeginInit(); listBox.EndInit(); Assert.Equal(1, listBox.SelectedIndex); Assert.Equal("bar", listBox.SelectedItem); } [Fact] public void Setting_SelectedIndex_During_Initialize_Should_Take_Priority_Over_Previous_Value() { var listBox = new ListBox { SelectionMode = SelectionMode.Single, Items = new[] { "foo", "bar", "baz" }, SelectedIndex = 2 }; listBox.BeginInit(); listBox.SelectedIndex = 1; listBox.EndInit(); Assert.Equal(1, listBox.SelectedIndex); Assert.Equal("bar", listBox.SelectedItem); } [Fact] public void Setting_SelectedItem_Before_Initialize_Should_Retain_Selection() { var listBox = new ListBox { SelectionMode = SelectionMode.Single, Items = new[] { "foo", "bar", "baz" }, SelectedItem = "bar" }; listBox.BeginInit(); listBox.EndInit(); Assert.Equal(1, listBox.SelectedIndex); Assert.Equal("bar", listBox.SelectedItem); } [Fact] public void Setting_SelectedItems_Before_Initialize_Should_Retain_Selection() { var listBox = new ListBox { SelectionMode = SelectionMode.Multiple, Items = new[] { "foo", "bar", "baz" }, }; var selected = new[] { "foo", "bar" }; foreach (var v in selected) { listBox.SelectedItems.Add(v); } listBox.BeginInit(); listBox.EndInit(); Assert.Equal(selected, listBox.SelectedItems); } [Fact] public void Setting_SelectedItems_During_Initialize_Should_Take_Priority_Over_Previous_Value() { var listBox = new ListBox { SelectionMode = SelectionMode.Multiple, Items = new[] { "foo", "bar", "baz" }, }; var selected = new[] { "foo", "bar" }; foreach (var v in new[] { "bar", "baz" }) { listBox.SelectedItems.Add(v); } listBox.BeginInit(); listBox.SelectedItems = new AvaloniaList<object>(selected); listBox.EndInit(); Assert.Equal(selected, listBox.SelectedItems); } [Fact] public void Setting_SelectedIndex_Before_Initialize_With_AlwaysSelected_Should_Retain_Selection() { var listBox = new ListBox { SelectionMode = SelectionMode.Single | SelectionMode.AlwaysSelected, Items = new[] { "foo", "bar", "baz" }, SelectedIndex = 1 }; listBox.BeginInit(); listBox.EndInit(); Assert.Equal(1, listBox.SelectedIndex); Assert.Equal("bar", listBox.SelectedItem); } [Fact] public void Setting_SelectedIndex_Before_ApplyTemplate_Should_Set_Item_IsSelected_True() { var items = new[] { new Item(), new Item(), }; var target = new SelectingItemsControl { Items = items, Template = Template(), }; target.SelectedIndex = 1; Prepare(target); Assert.False(items[0].IsSelected); Assert.True(items[1].IsSelected); } [Fact] public void Setting_SelectedItem_Should_Set_SelectedIndex() { var items = new[] { new Item(), new Item(), }; var target = new SelectingItemsControl { Items = items, Template = Template(), }; target.ApplyTemplate(); target.SelectedItem = items[1]; Assert.Equal(items[1], target.SelectedItem); Assert.Equal(1, target.SelectedIndex); } [Fact] public void SelectedIndex_Item_Is_Updated_As_Items_Removed_When_Last_Item_Is_Selected() { var items = new ObservableCollection<string> { "Foo", "Bar", "FooBar" }; var target = new SelectingItemsControl { Items = items, Template = Template(), }; target.ApplyTemplate(); target.SelectedItem = items[2]; Assert.Equal(items[2], target.SelectedItem); Assert.Equal(2, target.SelectedIndex); items.RemoveAt(0); Assert.Equal(items[1], target.SelectedItem); Assert.Equal(1, target.SelectedIndex); } [Fact] public void Setting_SelectedItem_To_Not_Present_Item_Should_Clear_Selection() { var items = new[] { new Item(), new Item(), }; var target = new SelectingItemsControl { Items = items, Template = Template(), }; target.ApplyTemplate(); target.SelectedItem = items[1]; Assert.Equal(items[1], target.SelectedItem); Assert.Equal(1, target.SelectedIndex); target.SelectedItem = new Item(); Assert.Null(target.SelectedItem); Assert.Equal(-1, target.SelectedIndex); } [Fact] public void Setting_SelectedIndex_Should_Set_SelectedItem() { var items = new[] { new Item(), new Item(), }; var target = new SelectingItemsControl { Items = items, Template = Template(), }; target.ApplyTemplate(); target.SelectedIndex = 1; Assert.Equal(items[1], target.SelectedItem); } [Fact] public void Setting_SelectedIndex_Out_Of_Bounds_Should_Clear_Selection() { var items = new[] { new Item(), new Item(), }; var target = new SelectingItemsControl { Items = items, Template = Template(), }; target.ApplyTemplate(); target.SelectedIndex = 2; Assert.Equal(-1, target.SelectedIndex); } [Fact] public void Setting_SelectedItem_To_Non_Existent_Item_Should_Clear_Selection() { var target = new SelectingItemsControl { Template = Template(), }; target.ApplyTemplate(); target.SelectedItem = new Item(); Assert.Equal(-1, target.SelectedIndex); Assert.Null(target.SelectedItem); } [Fact] public void Adding_Selected_Item_Should_Update_Selection() { var items = new AvaloniaList<Item>(new[] { new Item(), new Item(), }); var target = new SelectingItemsControl { Items = items, Template = Template(), }; Prepare(target); items.Add(new Item { IsSelected = true }); Assert.Equal(2, target.SelectedIndex); Assert.Equal(items[2], target.SelectedItem); } [Fact] public void Setting_Items_To_Null_Should_Clear_Selection() { var items = new AvaloniaList<Item> { new Item(), new Item(), }; var target = new SelectingItemsControl { Items = items, Template = Template(), }; target.ApplyTemplate(); target.SelectedIndex = 1; Assert.Equal(items[1], target.SelectedItem); Assert.Equal(1, target.SelectedIndex); target.Items = null; Assert.Null(target.SelectedItem); Assert.Equal(-1, target.SelectedIndex); } [Fact] public void Removing_Selected_Item_Should_Clear_Selection() { var items = new AvaloniaList<Item> { new Item(), new Item(), }; var target = new SelectingItemsControl { Items = items, Template = Template(), }; Prepare(target); target.SelectedIndex = 1; Assert.Equal(items[1], target.SelectedItem); Assert.Equal(1, target.SelectedIndex); SelectionChangedEventArgs receivedArgs = null; target.SelectionChanged += (_, args) => receivedArgs = args; var removed = items[1]; items.RemoveAt(1); Assert.Null(target.SelectedItem); Assert.Equal(-1, target.SelectedIndex); Assert.NotNull(receivedArgs); Assert.Empty(receivedArgs.AddedItems); Assert.Equal(new[] { removed }, receivedArgs.RemovedItems); Assert.False(items.Single().IsSelected); } [Fact] public void Removing_Selected_Item_Should_Update_Selection_With_AlwaysSelected() { var item0 = new Item(); var item1 = new Item(); var items = new AvaloniaList<Item> { item0, item1, }; var target = new TestSelector { Items = items, Template = Template(), SelectionMode = SelectionMode.AlwaysSelected, }; Prepare(target); target.SelectedIndex = 1; Assert.Equal(items[1], target.SelectedItem); Assert.Equal(1, target.SelectedIndex); SelectionChangedEventArgs receivedArgs = null; target.SelectionChanged += (_, args) => receivedArgs = args; items.RemoveAt(1); Assert.Same(item0, target.SelectedItem); Assert.Equal(0, target.SelectedIndex); Assert.NotNull(receivedArgs); Assert.Equal(new[] { item0 }, receivedArgs.AddedItems); Assert.Equal(new[] { item1 }, receivedArgs.RemovedItems); Assert.True(items.Single().IsSelected); } [Fact] public void Removing_Selected_Item_Should_Clear_Selection_With_BeginInit() { var items = new AvaloniaList<Item> { new Item(), new Item(), }; var target = new SelectingItemsControl(); target.BeginInit(); target.Items = items; target.Template = Template(); target.EndInit(); Prepare(target); target.SelectedIndex = 0; Assert.Equal(items[0], target.SelectedItem); Assert.Equal(0, target.SelectedIndex); SelectionChangedEventArgs receivedArgs = null; target.SelectionChanged += (_, args) => receivedArgs = args; var removed = items[0]; items.RemoveAt(0); Assert.Null(target.SelectedItem); Assert.Equal(-1, target.SelectedIndex); Assert.NotNull(receivedArgs); Assert.Empty(receivedArgs.AddedItems); Assert.Equal(new[] { removed }, receivedArgs.RemovedItems); Assert.False(items.Single().IsSelected); } [Fact] public void Resetting_Items_Collection_Should_Clear_Selection() { // Need to use ObservableCollection here as AvaloniaList signals a Clear as an // add + remove. var items = new ObservableCollection<Item> { new Item(), new Item(), }; var target = new SelectingItemsControl { Items = items, Template = Template(), }; target.ApplyTemplate(); target.SelectedIndex = 1; Assert.Equal(items[1], target.SelectedItem); Assert.Equal(1, target.SelectedIndex); items.Clear(); Assert.Null(target.SelectedItem); Assert.Equal(-1, target.SelectedIndex); } [Fact] public void Raising_IsSelectedChanged_On_Item_Should_Update_Selection() { var items = new[] { new Item(), new Item(), }; var target = new SelectingItemsControl { Items = items, Template = Template(), }; Prepare(target); target.SelectedItem = items[1]; Assert.False(items[0].IsSelected); Assert.True(items[1].IsSelected); items[0].IsSelected = true; items[0].RaiseEvent(new RoutedEventArgs(SelectingItemsControl.IsSelectedChangedEvent)); Assert.Equal(0, target.SelectedIndex); Assert.Equal(items[0], target.SelectedItem); Assert.True(items[0].IsSelected); Assert.False(items[1].IsSelected); } [Fact] public void Clearing_IsSelected_And_Raising_IsSelectedChanged_On_Item_Should_Update_Selection() { var items = new[] { new Item(), new Item(), }; var target = new SelectingItemsControl { Items = items, Template = Template(), }; Prepare(target); target.SelectedItem = items[1]; Assert.False(items[0].IsSelected); Assert.True(items[1].IsSelected); items[1].IsSelected = false; items[1].RaiseEvent(new RoutedEventArgs(SelectingItemsControl.IsSelectedChangedEvent)); Assert.Equal(-1, target.SelectedIndex); Assert.Null(target.SelectedItem); } [Fact] public void Raising_IsSelectedChanged_On_Someone_Elses_Item_Should_Not_Update_Selection() { var items = new[] { new Item(), new Item(), }; var target = new SelectingItemsControl { Items = items, Template = Template(), }; target.ApplyTemplate(); target.SelectedItem = items[1]; var notChild = new Item { IsSelected = true, }; target.RaiseEvent(new RoutedEventArgs { RoutedEvent = SelectingItemsControl.IsSelectedChangedEvent, Source = notChild, }); Assert.Equal(target.SelectedItem, items[1]); } [Fact] public void Setting_SelectedIndex_Should_Raise_SelectionChanged_Event() { var items = new[] { new Item(), new Item(), }; var target = new SelectingItemsControl { Items = items, Template = Template(), }; var called = false; target.SelectionChanged += (s, e) => { Assert.Same(items[1], e.AddedItems.Cast<object>().Single()); Assert.Empty(e.RemovedItems); called = true; }; target.SelectedIndex = 1; Assert.True(called); } [Fact] public void Clearing_SelectedIndex_Should_Raise_SelectionChanged_Event() { var items = new[] { new Item(), new Item(), }; var target = new SelectingItemsControl { Items = items, Template = Template(), SelectedIndex = 1, }; Prepare(target); var called = false; target.SelectionChanged += (s, e) => { Assert.Same(items[1], e.RemovedItems.Cast<object>().Single()); Assert.Empty(e.AddedItems); called = true; }; target.SelectedIndex = -1; Assert.True(called); } [Fact] public void Setting_SelectedIndex_Should_Raise_PropertyChanged_Events() { var items = new ObservableCollection<string> { "foo", "bar", "baz" }; var target = new TestSelector { Items = items, Template = Template(), }; var selectedIndexRaised = 0; var selectedItemRaised = 0; target.PropertyChanged += (s, e) => { if (e.Property == SelectingItemsControl.SelectedIndexProperty) { Assert.Equal(-1, e.OldValue); Assert.Equal(1, e.NewValue); ++selectedIndexRaised; } else if (e.Property == SelectingItemsControl.SelectedItemProperty) { Assert.Null(e.OldValue); Assert.Equal("bar", e.NewValue); ++selectedItemRaised; } }; target.SelectedIndex = 1; Assert.Equal(1, selectedIndexRaised); Assert.Equal(1, selectedItemRaised); } [Fact] public void Removing_Selected_Item_Should_Raise_PropertyChanged_Events() { var items = new ObservableCollection<string> { "foo", "bar", "baz" }; var target = new TestSelector { Items = items, Template = Template(), }; var selectedIndexRaised = 0; var selectedItemRaised = 0; target.SelectedIndex = 1; target.PropertyChanged += (s, e) => { if (e.Property == SelectingItemsControl.SelectedIndexProperty) { Assert.Equal(1, e.OldValue); Assert.Equal(-1, e.NewValue); ++selectedIndexRaised; } else if (e.Property == SelectingItemsControl.SelectedItemProperty) { Assert.Equal("bar", e.OldValue); Assert.Null(e.NewValue); } }; items.RemoveAt(1); Assert.Equal(1, selectedIndexRaised); Assert.Equal(0, selectedItemRaised); } [Fact] public void Removing_Selected_Item0_Should_Raise_PropertyChanged_Events_With_AlwaysSelected() { var items = new ObservableCollection<string> { "foo", "bar", "baz" }; var target = new TestSelector { Items = items, Template = Template(), SelectionMode = SelectionMode.AlwaysSelected, }; var selectedIndexRaised = 0; var selectedItemRaised = 0; target.SelectedIndex = 0; target.PropertyChanged += (s, e) => { if (e.Property == SelectingItemsControl.SelectedIndexProperty) { ++selectedIndexRaised; } else if (e.Property == SelectingItemsControl.SelectedItemProperty) { Assert.Equal("foo", e.OldValue); Assert.Equal("bar", e.NewValue); ++selectedItemRaised; } }; items.RemoveAt(0); Assert.Equal(0, selectedIndexRaised); Assert.Equal(1, selectedItemRaised); } [Fact] public void Removing_Selected_Item1_Should_Raise_PropertyChanged_Events_With_AlwaysSelected() { var items = new ObservableCollection<string> { "foo", "bar", "baz" }; var target = new TestSelector { Items = items, Template = Template(), SelectionMode = SelectionMode.AlwaysSelected, }; var selectedIndexRaised = 0; var selectedItemRaised = 0; target.SelectedIndex = 1; target.PropertyChanged += (s, e) => { if (e.Property == SelectingItemsControl.SelectedIndexProperty) { Assert.Equal(1, e.OldValue); Assert.Equal(0, e.NewValue); ++selectedIndexRaised; } else if (e.Property == SelectingItemsControl.SelectedItemProperty) { Assert.Equal("bar", e.OldValue); Assert.Equal("foo", e.NewValue); } }; items.RemoveAt(1); Assert.Equal(1, selectedIndexRaised); Assert.Equal(0, selectedItemRaised); } [Fact] public void Removing_Item_Before_Selection_Should_Raise_PropertyChanged_Events() { var items = new ObservableCollection<string> { "foo", "bar", "baz" }; var target = new SelectingItemsControl { Items = items, Template = Template(), }; var selectedIndexRaised = 0; var selectedItemRaised = 0; target.SelectedIndex = 1; target.PropertyChanged += (s, e) => { if (e.Property == SelectingItemsControl.SelectedIndexProperty) { Assert.Equal(1, e.OldValue); Assert.Equal(0, e.NewValue); ++selectedIndexRaised; } else if (e.Property == SelectingItemsControl.SelectedItemProperty) { ++selectedItemRaised; } }; items.RemoveAt(0); Assert.Equal(1, selectedIndexRaised); Assert.Equal(0, selectedItemRaised); } [Fact] public void Order_Of_Setting_Items_And_SelectedIndex_During_Initialization_Should_Not_Matter() { var items = new[] { "Foo", "Bar" }; var target = new SelectingItemsControl(); ((ISupportInitialize)target).BeginInit(); target.SelectedIndex = 1; target.Items = items; ((ISupportInitialize)target).EndInit(); Prepare(target); Assert.Equal(1, target.SelectedIndex); Assert.Equal("Bar", target.SelectedItem); } [Fact] public void Order_Of_Setting_Items_And_SelectedItem_During_Initialization_Should_Not_Matter() { var items = new[] { "Foo", "Bar" }; var target = new SelectingItemsControl(); ((ISupportInitialize)target).BeginInit(); target.SelectedItem = "Bar"; target.Items = items; ((ISupportInitialize)target).EndInit(); Prepare(target); Assert.Equal(1, target.SelectedIndex); Assert.Equal("Bar", target.SelectedItem); } [Fact] public void Changing_DataContext_Should_Not_Clear_Nested_ViewModel_SelectedItem() { var items = new[] { new Item(), new Item(), }; var vm = new MasterViewModel { Child = new ChildViewModel { Items = items, SelectedItem = items[1], } }; var target = new SelectingItemsControl { DataContext = vm }; var itemsBinding = new Binding("Child.Items"); var selectedBinding = new Binding("Child.SelectedItem"); target.Bind(SelectingItemsControl.ItemsProperty, itemsBinding); target.Bind(SelectingItemsControl.SelectedItemProperty, selectedBinding); Assert.Equal(1, target.SelectedIndex); Assert.Same(vm.Child.SelectedItem, target.SelectedItem); items = new[] { new Item { Value = "Item1" }, new Item { Value = "Item2" }, new Item { Value = "Item3" }, }; vm = new MasterViewModel { Child = new ChildViewModel { Items = items, SelectedItem = items[2], } }; target.DataContext = vm; Assert.Equal(2, target.SelectedIndex); Assert.Same(vm.Child.SelectedItem, target.SelectedItem); } [Fact] public void Nested_ListBox_Does_Not_Change_Parent_SelectedIndex() { SelectingItemsControl nested; var root = new SelectingItemsControl { Template = Template(), Items = new IControl[] { new Border(), nested = new ListBox { Template = Template(), Items = new[] { "foo", "bar" }, SelectedIndex = 1, } }, SelectedIndex = 0, }; root.ApplyTemplate(); root.Presenter.ApplyTemplate(); nested.ApplyTemplate(); nested.Presenter.ApplyTemplate(); Assert.Equal(0, root.SelectedIndex); Assert.Equal(1, nested.SelectedIndex); nested.SelectedIndex = 0; Assert.Equal(0, root.SelectedIndex); } [Fact] public void Setting_SelectedItem_With_Pointer_Should_Set_TabOnceActiveElement() { var target = new ListBox { Template = Template(), Items = new[] { "Foo", "Bar", "Baz " }, }; Prepare(target); _helper.Down((Interactive)target.Presenter.Panel.Children[1]); var panel = target.Presenter.Panel; Assert.Equal( KeyboardNavigation.GetTabOnceActiveElement((InputElement)panel), panel.Children[1]); } [Fact] public void Removing_SelectedItem_Should_Clear_TabOnceActiveElement() { var items = new ObservableCollection<string>(new[] { "Foo", "Bar", "Baz " }); var target = new ListBox { Template = Template(), Items = items, }; Prepare(target); _helper.Down(target.Presenter.Panel.Children[1]); items.RemoveAt(1); var panel = target.Presenter.Panel; Assert.Null(KeyboardNavigation.GetTabOnceActiveElement((InputElement)panel)); } [Fact] public void Resetting_Items_Collection_Should_Retain_Selection() { var itemsMock = new Mock<List<string>>(); var itemsMockAsINCC = itemsMock.As<INotifyCollectionChanged>(); itemsMock.Object.AddRange(new[] { "Foo", "Bar", "Baz" }); var target = new SelectingItemsControl { Items = itemsMock.Object }; target.SelectedIndex = 1; itemsMockAsINCC.Raise(e => e.CollectionChanged += null, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); Assert.True(target.SelectedIndex == 1); } [Fact] public void Binding_With_DelayedBinding_And_Initialization_Where_DataContext_Is_Root_Works() { // Test for #1932. var root = new RootWithItems(); root.BeginInit(); root.DataContext = root; var target = new ListBox(); target.BeginInit(); root.Child = target; DelayedBinding.Add(target, ItemsControl.ItemsProperty, new Binding(nameof(RootWithItems.Items))); DelayedBinding.Add(target, ListBox.SelectedItemProperty, new Binding(nameof(RootWithItems.Selected))); target.EndInit(); root.EndInit(); Assert.Equal("b", target.SelectedItem); } [Fact] public void Mode_For_SelectedIndex_Is_TwoWay_By_Default() { var items = new[] { new Item(), new Item(), new Item(), }; var vm = new MasterViewModel { Child = new ChildViewModel { Items = items, SelectedIndex = 1, } }; var target = new SelectingItemsControl { DataContext = vm }; var itemsBinding = new Binding("Child.Items"); var selectedIndBinding = new Binding("Child.SelectedIndex"); target.Bind(SelectingItemsControl.ItemsProperty, itemsBinding); target.Bind(SelectingItemsControl.SelectedIndexProperty, selectedIndBinding); Assert.Equal(1, target.SelectedIndex); target.SelectedIndex = 2; Assert.Equal(2, target.SelectedIndex); Assert.Equal(2, vm.Child.SelectedIndex); } [Fact] public void Should_Select_Correct_Item_When_Duplicate_Items_Are_Present() { var target = new ListBox { Template = Template(), Items = new[] { "Foo", "Bar", "Baz", "Foo", "Bar", "Baz" }, }; Prepare(target); _helper.Down((Interactive)target.Presenter.Panel.Children[3]); Assert.Equal(3, target.SelectedIndex); } [Fact] public void Should_Apply_Selected_Pseudoclass_To_Correct_Item_When_Duplicate_Items_Are_Present() { var target = new ListBox { Template = Template(), Items = new[] { "Foo", "Bar", "Baz", "Foo", "Bar", "Baz" }, }; Prepare(target); _helper.Down((Interactive)target.Presenter.Panel.Children[3]); Assert.Equal(new[] { ":pressed", ":selected" }, target.Presenter.Panel.Children[3].Classes); } [Fact] public void Adding_Item_Before_SelectedItem_Should_Update_SelectedIndex() { var items = new ObservableCollection<string> { "Foo", "Bar", "Baz" }; var target = new ListBox { Template = Template(), Items = items, SelectedIndex = 1, }; Prepare(target); items.Insert(0, "Qux"); Assert.Equal(2, target.SelectedIndex); Assert.Equal("Bar", target.SelectedItem); } [Fact] public void Removing_Item_Before_SelectedItem_Should_Update_SelectedIndex() { var items = new ObservableCollection<string> { "Foo", "Bar", "Baz" }; var target = new ListBox { Template = Template(), Items = items, SelectedIndex = 1, }; Prepare(target); items.RemoveAt(0); Assert.Equal(0, target.SelectedIndex); Assert.Equal("Bar", target.SelectedItem); } [Fact] public void Binding_SelectedIndex_Selects_Correct_Item() { // Issue #4496 (part 2) var items = new ObservableCollection<string>(); var other = new ListBox { Template = Template(), Items = items, SelectionMode = SelectionMode.AlwaysSelected, }; var target = new ListBox { Template = Template(), Items = items, [!ListBox.SelectedIndexProperty] = other[!ListBox.SelectedIndexProperty], }; Prepare(other); Prepare(target); items.Add("Foo"); Assert.Equal(0, other.SelectedIndex); Assert.Equal(0, target.SelectedIndex); } [Fact] public void Binding_SelectedItem_Selects_Correct_Item() { // Issue #4496 (part 2) var items = new ObservableCollection<string>(); var other = new ListBox { Template = Template(), Items = items, SelectionMode = SelectionMode.AlwaysSelected, }; var target = new ListBox { Template = Template(), Items = items, [!ListBox.SelectedItemProperty] = other[!ListBox.SelectedItemProperty], }; Prepare(target); other.ApplyTemplate(); other.Presenter.ApplyTemplate(); items.Add("Foo"); Assert.Equal(0, other.SelectedIndex); Assert.Equal(0, target.SelectedIndex); } [Fact] public void Replacing_Selected_Item_Should_Update_SelectedItem() { var items = new ObservableCollection<string> { "Foo", "Bar", "Baz" }; var target = new ListBox { Template = Template(), Items = items, SelectedIndex = 1, }; Prepare(target); items[1] = "Qux"; Assert.Equal(-1, target.SelectedIndex); Assert.Null(target.SelectedItem); } [Fact] public void AutoScrollToSelectedItem_Causes_Scroll_To_SelectedItem() { var items = new ObservableCollection<string> { "Foo", "Bar", "Baz" }; var target = new ListBox { Template = Template(), Items = items, }; var raised = false; Prepare(target); target.AddHandler(Control.RequestBringIntoViewEvent, (s, e) => raised = true); target.SelectedIndex = 2; Assert.True(raised); } [Fact] public void AutoScrollToSelectedItem_Causes_Scroll_To_Initial_SelectedItem() { var items = new ObservableCollection<string> { "Foo", "Bar", "Baz" }; var target = new ListBox { Template = Template(), Items = items, }; var raised = false; target.AddHandler(Control.RequestBringIntoViewEvent, (s, e) => raised = true); target.SelectedIndex = 2; Prepare(target); Assert.True(raised); } [Fact] public void AutoScrollToSelectedItem_On_Reset_Works() { // Issue #3148 using (UnitTestApplication.Start(TestServices.StyledWindow)) { var items = new ResettingCollection(100); var target = new ListBox { Items = items, ItemTemplate = new FuncDataTemplate<string>((x, _) => new TextBlock { Text = x, Width = 100, Height = 10 }), AutoScrollToSelectedItem = true, VirtualizationMode = ItemVirtualizationMode.Simple, }; var root = new TestRoot(true, target); root.Measure(new Size(100, 100)); root.Arrange(new Rect(0, 0, 100, 100)); Assert.True(target.Presenter.Panel.Children.Count > 0); Assert.True(target.Presenter.Panel.Children.Count < 100); target.SelectedItem = "Item99"; // #3148 triggered here. items.Reset(new[] { "Item99" }); Assert.Equal(0, target.SelectedIndex); Assert.Equal(1, target.Presenter.Panel.Children.Count); } } [Fact] public void AutoScrollToSelectedItem_Scrolls_When_Reattached_To_Visual_Tree_If_Selection_Changed_While_Detached_From_Visual_Tree() { var items = new ObservableCollection<string> { "Foo", "Bar", "Baz" }; var target = new ListBox { Template = Template(), Items = items, SelectedIndex = 2, }; var raised = false; Prepare(target); var root = (TestRoot)target.Parent; target.AddHandler(Control.RequestBringIntoViewEvent, (s, e) => raised = true); root.Child = null; target.SelectedIndex = 1; root.Child = target; Assert.True(raised); } [Fact] public void AutoScrollToSelectedItem_Doesnt_Scroll_If_Reattached_To_Visual_Tree_With_No_Selection_Change() { var items = new ObservableCollection<string> { "Foo", "Bar", "Baz" }; var target = new ListBox { Template = Template(), Items = items, SelectedIndex = 2, }; var raised = false; Prepare(target); var root = (TestRoot)target.Parent; target.AddHandler(Control.RequestBringIntoViewEvent, (s, e) => raised = true); root.Child = null; root.Child = target; Assert.False(raised); } [Fact] public void AutoScrollToSelectedItem_Causes_Scroll_When_Turned_On() { var items = new ObservableCollection<string> { "Foo", "Bar", "Baz" }; var target = new ListBox { Template = Template(), Items = items, AutoScrollToSelectedItem = false, }; Prepare(target); var raised = false; target.AddHandler(Control.RequestBringIntoViewEvent, (s, e) => raised = true); target.SelectedIndex = 2; Assert.False(raised); target.AutoScrollToSelectedItem = true; Assert.True(raised); } [Fact] public void Can_Set_Both_SelectedItem_And_SelectedItems_During_Initialization() { // Issue #2969. var target = new ListBox(); var selectedItems = new List<object>(); target.BeginInit(); target.Template = Template(); target.Items = new[] { "Foo", "Bar", "Baz" }; target.SelectedItems = selectedItems; target.SelectedItem = "Bar"; target.EndInit(); Prepare(target); Assert.Equal("Bar", target.SelectedItem); Assert.Equal(1, target.SelectedIndex); Assert.Same(selectedItems, target.SelectedItems); Assert.Equal(new[] { "Bar" }, selectedItems); } [Fact] public void MoveSelection_Wrap_Does_Not_Hang_With_No_Focusable_Controls() { // Issue #3094. var target = new TestSelector { Template = Template(), Items = new[] { new ListBoxItem { Focusable = false }, new ListBoxItem { Focusable = false }, }, SelectedIndex = 0, }; target.Measure(new Size(100, 100)); target.Arrange(new Rect(0, 0, 100, 100)); target.MoveSelection(NavigationDirection.Next, true); } [Fact] public void MoveSelection_Does_Select_Disabled_Controls() { // Issue #3426. var target = new TestSelector { Template = Template(), Items = new[] { new ListBoxItem(), new ListBoxItem { IsEnabled = false }, }, SelectedIndex = 0, }; target.Measure(new Size(100, 100)); target.Arrange(new Rect(0, 0, 100, 100)); target.MoveSelection(NavigationDirection.Next, true); Assert.Equal(0, target.SelectedIndex); } [Fact] public void Pre_Selecting_Item_Should_Set_Selection_After_It_Was_Added_When_AlwaysSelected() { var target = new TestSelector(SelectionMode.AlwaysSelected) { Template = Template() }; var second = new Item { IsSelected = true }; var items = new AvaloniaList<object> { new Item(), second }; target.Items = items; Prepare(target); Assert.Equal(second, target.SelectedItem); Assert.Equal(1, target.SelectedIndex); } [Fact] public void Setting_SelectionMode_Should_Update_SelectionModel() { var target = new TestSelector(); var model = target.Selection; Assert.True(model.SingleSelect); target.SelectionMode = SelectionMode.Multiple; Assert.False(model.SingleSelect); } [Fact] public void Does_The_Best_It_Can_With_AutoSelecting_ViewModel() { // Tests the following scenario: // // - Items changes from empty to having 1 item // - ViewModel auto-selects item 0 in CollectionChanged // - SelectionModel receives CollectionChanged // - And so adjusts the selected item from 0 to 1, which is past the end of the items. // // There's not much we can do about this situation because the order in which // CollectionChanged handlers are called can't be known (the problem also exists with // WPF). The best we can do is not select an invalid index. var vm = new SelectionViewModel(); vm.Items.CollectionChanged += (s, e) => { if (vm.SelectedIndex == -1 && vm.Items.Count > 0) { vm.SelectedIndex = 0; } }; var target = new ListBox { [!ListBox.ItemsProperty] = new Binding("Items"), [!ListBox.SelectedIndexProperty] = new Binding("SelectedIndex"), DataContext = vm, }; Prepare(target); vm.Items.Add("foo"); vm.Items.Add("bar"); Assert.Equal(0, target.SelectedIndex); Assert.Equal(new[] { 0 }, target.Selection.SelectedIndexes); Assert.Equal("foo", target.SelectedItem); Assert.Equal(new[] { "foo" }, target.SelectedItems); } [Fact] public void Preserves_Initial_SelectedItems_When_Bound() { // Issue #4272 (there are two issues there, this addresses the second one). var vm = new SelectionViewModel { Items = { "foo", "bar", "baz" }, SelectedItems = { "bar" }, }; var target = new ListBox { [!ListBox.ItemsProperty] = new Binding("Items"), [!ListBox.SelectedItemsProperty] = new Binding("SelectedItems"), DataContext = vm, }; Prepare(target); Assert.Equal(1, target.SelectedIndex); Assert.Equal(new[] { 1 }, target.Selection.SelectedIndexes); Assert.Equal("bar", target.SelectedItem); Assert.Equal(new[] { "bar" }, target.SelectedItems); } [Fact] public void Preserves_SelectedItem_When_Items_Changed() { // Issue #4048 var target = new SelectingItemsControl { Items = new[] { "foo", "bar", "baz"}, SelectedItem = "bar", }; Prepare(target); Assert.Equal(1, target.SelectedIndex); Assert.Equal("bar", target.SelectedItem); target.Items = new[] { "qux", "foo", "bar" }; Assert.Equal(2, target.SelectedIndex); Assert.Equal("bar", target.SelectedItem); } [Fact] public void Setting_SelectedItems_Raises_PropertyChanged() { var target = new TestSelector { Items = new[] { "foo", "bar", "baz" }, }; var raised = 0; var newValue = new AvaloniaList<object>(); Prepare(target); target.PropertyChanged += (s, e) => { if (e.Property == ListBox.SelectedItemsProperty) { Assert.Null(e.OldValue); Assert.Same(newValue, e.NewValue); ++raised; } }; target.SelectedItems = newValue; Assert.Equal(1, raised); } [Fact] public void Setting_Selection_Raises_SelectedItems_PropertyChanged() { var target = new TestSelector { Items = new[] { "foo", "bar", "baz" }, }; var raised = 0; var oldValue = target.SelectedItems; Prepare(target); target.PropertyChanged += (s, e) => { if (e.Property == ListBox.SelectedItemsProperty) { Assert.Same(oldValue, e.OldValue); Assert.Null(e.NewValue); ++raised; } }; target.Selection = new SelectionModel<int>(); Assert.Equal(1, raised); } [Fact] public void Handles_Removing_Last_Item_In_Two_Controls_With_Bound_SelectedIndex() { var items = new ObservableCollection<string> { "foo" }; // Simulates problem with TabStrip and Carousel with bound SelectedIndex. var tabStrip = new TestSelector { Items = items, SelectionMode = SelectionMode.AlwaysSelected, }; var carousel = new TestSelector { Items = items, [!Carousel.SelectedIndexProperty] = tabStrip[!TabStrip.SelectedIndexProperty], }; var tabStripRaised = 0; var carouselRaised = 0; tabStrip.SelectionChanged += (s, e) => { Assert.Equal(new[] { "foo" }, e.RemovedItems); Assert.Empty(e.AddedItems); ++tabStripRaised; }; carousel.SelectionChanged += (s, e) => { Assert.Equal(new[] { "foo" }, e.RemovedItems); Assert.Empty(e.AddedItems); ++carouselRaised; }; items.RemoveAt(0); Assert.Equal(1, tabStripRaised); Assert.Equal(1, carouselRaised); } [Fact] public void Handles_Removing_Last_Item_In_Controls_With_Bound_SelectedItem() { var items = new ObservableCollection<string> { "foo" }; // Simulates problem with TabStrip and Carousel with bound SelectedItem. var tabStrip = new TestSelector { Items = items, SelectionMode = SelectionMode.AlwaysSelected, }; var carousel = new TestSelector { Items = items, [!Carousel.SelectedItemProperty] = tabStrip[!TabStrip.SelectedItemProperty], }; var tabStripRaised = 0; var carouselRaised = 0; tabStrip.SelectionChanged += (s, e) => { Assert.Equal(new[] { "foo" }, e.RemovedItems); Assert.Empty(e.AddedItems); ++tabStripRaised; }; carousel.SelectionChanged += (s, e) => { Assert.Equal(new[] { "foo" }, e.RemovedItems); Assert.Empty(e.AddedItems); ++carouselRaised; }; items.RemoveAt(0); Assert.Equal(1, tabStripRaised); Assert.Equal(1, carouselRaised); } private static void Prepare(SelectingItemsControl target) { var root = new TestRoot { Child = target, Width = 100, Height = 100, Styles = { new Style(x => x.Is<SelectingItemsControl>()) { Setters = { new Setter(ListBox.TemplateProperty, Template()), }, }, }, }; root.LayoutManager.ExecuteInitialLayoutPass(); } private static FuncControlTemplate Template() { return new FuncControlTemplate<SelectingItemsControl>((control, scope) => new ItemsPresenter { Name = "itemsPresenter", [~ItemsPresenter.ItemsProperty] = control[~ItemsControl.ItemsProperty], [~ItemsPresenter.ItemsPanelProperty] = control[~ItemsControl.ItemsPanelProperty], [~ItemsPresenter.VirtualizationModeProperty] = control[~ListBox.VirtualizationModeProperty], }.RegisterInNameScope(scope)); } private class Item : Control, ISelectable { public string Value { get; set; } public bool IsSelected { get; set; } } private class MasterViewModel : NotifyingBase { private ChildViewModel _child; public ChildViewModel Child { get { return _child; } set { _child = value; RaisePropertyChanged(); } } } private class ChildViewModel : NotifyingBase { public IList<Item> Items { get; set; } public Item SelectedItem { get; set; } public int SelectedIndex { get; set; } } private class SelectionViewModel : NotifyingBase { private int _selectedIndex = -1; public SelectionViewModel() { Items = new ObservableCollection<string>(); SelectedItems = new ObservableCollection<string>(); } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; RaisePropertyChanged(); } } public ObservableCollection<string> Items { get; } public ObservableCollection<string> SelectedItems { get; } } private class RootWithItems : TestRoot { public List<string> Items { get; set; } = new List<string>() { "a", "b", "c", "d", "e" }; public string Selected { get; set; } = "b"; } private class TestSelector : SelectingItemsControl { public TestSelector() { } public TestSelector(SelectionMode selectionMode) { SelectionMode = selectionMode; } public new ISelectionModel Selection { get => base.Selection; set => base.Selection = value; } public new IList SelectedItems { get => base.SelectedItems; set => base.SelectedItems = value; } public new SelectionMode SelectionMode { get => base.SelectionMode; set => base.SelectionMode = value; } public new bool MoveSelection(NavigationDirection direction, bool wrap) { return base.MoveSelection(direction, wrap); } } private class ResettingCollection : List<string>, INotifyCollectionChanged { public ResettingCollection(int itemCount) { AddRange(Enumerable.Range(0, itemCount).Select(x => $"Item{x}")); } public void Reset(IEnumerable<string> items) { Clear(); AddRange(items); CollectionChanged?.Invoke( this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } public event NotifyCollectionChangedEventHandler CollectionChanged; } } }
using System; using System.Collections.Specialized; using System.Web; using MbUnit.Framework; using Moq; using Moq.Stub; using Subtext.Framework; using Subtext.Framework.Services; using Subtext.Framework.Web.HttpModules; namespace UnitTests.Subtext.Framework.Web.HttpModules { [TestFixture] public class BlogRequestModuleTests { [Test] public void ConvertRequestToBlogRequest_WithRequestForCorrectHost_ReturnsBlogRequest() { //arrange var service = new Mock<IBlogLookupService>(); service.Setup(s => s.Lookup(It.IsAny<BlogRequest>())).Returns( new BlogLookupResult(new Blog {IsActive = true}, null)); var httpResponse = new Mock<HttpResponseBase>(); httpResponse.Setup(r => r.End()).Throws( new InvalidOperationException("This method should not have been called")); Mock<HttpRequestBase> httpRequest = CreateRequest("example.com", "/", "/", true); var httpContext = new Mock<HttpContextBase>(); httpContext.Setup(c => c.Request).Returns(httpRequest.Object); httpContext.Setup(c => c.Response).Returns(httpResponse.Object); var module = new BlogRequestModule(service.Object); //act BlogRequest request = module.ConvertRequestToBlogRequest(httpContext.Object); //assert Assert.IsNotNull(request); } [Test] public void ConvertRequestToBlogRequest_WithRequestForAlternateHost_RedirectsToPrimaryHost() { //arrange var service = new Mock<IBlogLookupService>(); service.Setup(s => s.Lookup(It.IsAny<BlogRequest>())).Returns(new BlogLookupResult(null, new Uri( "http://www.example.com/"))); var httpResponse = new Mock<HttpResponseBase>(); httpResponse.Stub(r => r.StatusCode); httpResponse.Stub(r => r.StatusDescription); httpResponse.Stub(r => r.RedirectLocation); Mock<HttpRequestBase> httpRequest = CreateRequest("example.com", "/", "/", true); var httpContext = new Mock<HttpContextBase>(); httpContext.Setup(c => c.Request).Returns(httpRequest.Object); httpContext.Setup(c => c.Response).Returns(httpResponse.Object); var module = new BlogRequestModule(service.Object); //act BlogRequest request = module.ConvertRequestToBlogRequest(httpContext.Object); //assert Assert.IsNull(request); httpResponse.Verify(r => r.End()); Assert.AreEqual(301, httpResponse.Object.StatusCode); Assert.AreEqual("301 Moved Permanently", httpResponse.Object.StatusDescription); Assert.AreEqual("http://www.example.com/", httpResponse.Object.RedirectLocation); } [Test] public void ConvertRequestToBlogRequest_WithNoMatchingBlog_RedirectsToBlogNotConfiguredPage() { //arrange var service = new Mock<IBlogLookupService>(); service.Setup(s => s.Lookup(It.IsAny<BlogRequest>())).Returns((BlogLookupResult)null); var httpResponse = new Mock<HttpResponseBase>(); Mock<HttpRequestBase> httpRequest = CreateRequest("example.com", "/", "/", true); var httpContext = new Mock<HttpContextBase>(); httpContext.Setup(c => c.Request).Returns(httpRequest.Object); httpContext.Setup(c => c.Response).Returns(httpResponse.Object); var module = new BlogRequestModule(service.Object); //act BlogRequest request = module.ConvertRequestToBlogRequest(httpContext.Object); //assert Assert.IsNull(request.Blog); httpResponse.Verify(r => r.Redirect("~/install/BlogNotConfiguredError.aspx", true)); } [Test] public void ConvertRequestToBlogRequest_MatchingInactiveBlog_RedirectsToBlogInactivePage() { //arrange var service = new Mock<IBlogLookupService>(); var result = new BlogLookupResult(new Blog {IsActive = false}, null); service.Setup(s => s.Lookup(It.IsAny<BlogRequest>())).Returns(result); var httpResponse = new Mock<HttpResponseBase>(); Mock<HttpRequestBase> httpRequest = CreateRequest("example.com", "/", "/", true); var httpContext = new Mock<HttpContextBase>(); httpContext.Setup(c => c.Request).Returns(httpRequest.Object); httpContext.Setup(c => c.Response).Returns(httpResponse.Object); var module = new BlogRequestModule(service.Object); //act BlogRequest request = module.ConvertRequestToBlogRequest(httpContext.Object); //assert Assert.IsNull(request); httpResponse.Verify(r => r.Redirect("~/SystemMessages/BlogNotActive.aspx", true)); } [Test] public void ConvertRequestToBlogRequestWithRequestForLoginPage_MatchingInactiveBlog_DoesNotRedirect() { //arrange var service = new Mock<IBlogLookupService>(); var result = new BlogLookupResult(new Blog {IsActive = false}, null); service.Setup(s => s.Lookup(It.IsAny<BlogRequest>())).Returns(result); var httpResponse = new Mock<HttpResponseBase>(); Mock<HttpRequestBase> httpRequest = CreateRequest("example.com", "/", "/login.aspx", true); var httpContext = new Mock<HttpContextBase>(); httpContext.Setup(c => c.Request).Returns(httpRequest.Object); httpContext.Setup(c => c.Response).Returns(httpResponse.Object); var module = new BlogRequestModule(service.Object); //act BlogRequest request = module.ConvertRequestToBlogRequest(httpContext.Object); //assert Assert.IsNotNull(request); } [Test] public void ConvertRequestToBlogRequest_WithNoMatchingBlogButWithRequestForLoginPage_SetsBlogRequestBlogToNull() { //arrange var service = new Mock<IBlogLookupService>(); service.Setup(s => s.Lookup(It.IsAny<BlogRequest>())).Returns((BlogLookupResult)null); var httpResponse = new Mock<HttpResponseBase>(); httpResponse.Setup(r => r.Redirect(It.IsAny<string>(), true)).Throws( new InvalidOperationException("Method should not have been called")); Mock<HttpRequestBase> httpRequest = CreateRequest("example.com", "/", "/login.aspx", true); httpRequest.Setup(r => r.FilePath).Returns("/Login.aspx"); var httpContext = new Mock<HttpContextBase>(); httpContext.Setup(c => c.Request).Returns(httpRequest.Object); httpContext.Setup(c => c.Response).Returns(httpResponse.Object); var module = new BlogRequestModule(service.Object); //act BlogRequest request = module.ConvertRequestToBlogRequest(httpContext.Object); //assert Assert.IsNull(request.Blog); } [Test] public void ConvertRequestToBlogRequest_WithRequestForInstallationDirectory_ReturnsNullBlog() { //arrange var service = new Mock<IBlogLookupService>(); service.Setup(s => s.Lookup(It.IsAny<BlogRequest>())).Throws( new InvalidOperationException("Should not be called")); var httpResponse = new Mock<HttpResponseBase>(); httpResponse.Setup(r => r.Redirect(It.IsAny<string>(), true)).Throws( new InvalidOperationException("Method should not have been called")); Mock<HttpRequestBase> httpRequest = CreateRequest("example.com", "/", "/Install/Anything.aspx", true); httpRequest.Setup(r => r.FilePath).Returns("/Install/Anything.aspx"); var httpContext = new Mock<HttpContextBase>(); httpContext.Setup(c => c.Request).Returns(httpRequest.Object); httpContext.Setup(c => c.Response).Returns(httpResponse.Object); var module = new BlogRequestModule(service.Object); //act BlogRequest request = module.ConvertRequestToBlogRequest(httpContext.Object); //assert Assert.IsNull(request.Blog); } [Test] public void ConvertRequestToBlogRequestForStaticImage_WithNoMatchingBlog_DoesNotRedirect() { //arrange var service = new Mock<IBlogLookupService>(); var result = new BlogLookupResult(null, new Uri("http://localhost/images/blog/services/identiconhandler.ashx")); service.Setup(s => s.Lookup(It.IsAny<BlogRequest>())).Returns(result); var httpResponse = new Mock<HttpResponseBase>(); httpResponse.Setup(r => r.Redirect(It.IsAny<string>(), true)).Throws(new InvalidOperationException("Should not redirect")); Mock<HttpRequestBase> httpRequest = CreateRequest("example.com", "/", "/images/services/identiconhandler.ashx", true); var httpContext = new Mock<HttpContextBase>(); httpContext.Setup(c => c.Request).Returns(httpRequest.Object); httpContext.Setup(c => c.Response).Returns(httpResponse.Object); var module = new BlogRequestModule(service.Object); //act BlogRequest request = module.ConvertRequestToBlogRequest(httpContext.Object); //assert Assert.IsNotNull(request); Assert.IsNull(request.Blog); Assert.AreEqual(RequestLocation.StaticFile, request.RequestLocation); } private static Mock<HttpRequestBase> CreateRequest(string host, string applicationPath, string rawUrl, bool useParametersForHost) { var request = new Mock<HttpRequestBase>(); request.Setup(r => r.RawUrl).Returns(rawUrl); request.Setup(r => r.Path).Returns(rawUrl); request.Setup(r => r.FilePath).Returns(rawUrl); request.Setup(r => r.ApplicationPath).Returns(applicationPath); request.Setup(r => r.IsLocal).Returns(true); request.Setup(r => r.Url).Returns(new Uri("http://" + host + rawUrl)); var parameters = new NameValueCollection(); parameters["HTTP_HOST"] = useParametersForHost ? host : null; request.Setup(r => r.Params).Returns(parameters); return request; } } }
// Copyright (c) 2015, Outercurve Foundation. // 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 Outercurve Foundation 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. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // // This source code was auto-generated by Microsoft.VSDesigner, Version 4.0.30319.1. // #pragma warning disable 1591 namespace WebsitePanel.Installer.Services { using System; using System.Web.Services; using System.Diagnostics; using System.Web.Services.Protocols; using System.ComponentModel; using System.Xml.Serialization; using System.Data; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.0.30319.1")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="InstallerServiceSoap", Namespace="http://websitepanel.net/services")] public partial class InstallerService : System.Web.Services.Protocols.SoapHttpClientProtocol { private System.Threading.SendOrPostCallback GetReleaseFileInfoOperationCompleted; private System.Threading.SendOrPostCallback GetFileChunkOperationCompleted; private System.Threading.SendOrPostCallback GetFileSizeOperationCompleted; private System.Threading.SendOrPostCallback GetAvailableComponentsOperationCompleted; private System.Threading.SendOrPostCallback GetLatestComponentUpdateOperationCompleted; private System.Threading.SendOrPostCallback GetComponentUpdateOperationCompleted; private bool useDefaultCredentialsSetExplicitly; /// <remarks/> public InstallerService() { this.Url = global::WebsitePanel.Installer.Core.Properties.Settings.Default.WebsitePanel_Installer_Core_InstallerService_InstallerService; if ((this.IsLocalFileSystemWebService(this.Url) == true)) { this.UseDefaultCredentials = true; this.useDefaultCredentialsSetExplicitly = false; } else { this.useDefaultCredentialsSetExplicitly = true; } } public new string Url { get { return base.Url; } set { if ((((this.IsLocalFileSystemWebService(base.Url) == true) && (this.useDefaultCredentialsSetExplicitly == false)) && (this.IsLocalFileSystemWebService(value) == false))) { base.UseDefaultCredentials = false; } base.Url = value; } } public new bool UseDefaultCredentials { get { return base.UseDefaultCredentials; } set { base.UseDefaultCredentials = value; this.useDefaultCredentialsSetExplicitly = true; } } /// <remarks/> public event GetReleaseFileInfoCompletedEventHandler GetReleaseFileInfoCompleted; /// <remarks/> public event GetFileChunkCompletedEventHandler GetFileChunkCompleted; /// <remarks/> public event GetFileSizeCompletedEventHandler GetFileSizeCompleted; /// <remarks/> public event GetAvailableComponentsCompletedEventHandler GetAvailableComponentsCompleted; /// <remarks/> public event GetLatestComponentUpdateCompletedEventHandler GetLatestComponentUpdateCompleted; /// <remarks/> public event GetComponentUpdateCompletedEventHandler GetComponentUpdateCompleted; /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://websitepanel.net/services/GetReleaseFileInfo", RequestNamespace="http://websitepanel.net/services", ResponseNamespace="http://websitepanel.net/services", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public System.Data.DataSet GetReleaseFileInfo(string componentCode, string version) { object[] results = this.Invoke("GetReleaseFileInfo", new object[] { componentCode, version}); return ((System.Data.DataSet)(results[0])); } /// <remarks/> public void GetReleaseFileInfoAsync(string componentCode, string version) { this.GetReleaseFileInfoAsync(componentCode, version, null); } /// <remarks/> public void GetReleaseFileInfoAsync(string componentCode, string version, object userState) { if ((this.GetReleaseFileInfoOperationCompleted == null)) { this.GetReleaseFileInfoOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetReleaseFileInfoOperationCompleted); } this.InvokeAsync("GetReleaseFileInfo", new object[] { componentCode, version}, this.GetReleaseFileInfoOperationCompleted, userState); } private void OnGetReleaseFileInfoOperationCompleted(object arg) { if ((this.GetReleaseFileInfoCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetReleaseFileInfoCompleted(this, new GetReleaseFileInfoCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://websitepanel.net/services/GetFileChunk", RequestNamespace="http://websitepanel.net/services", ResponseNamespace="http://websitepanel.net/services", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] [return: System.Xml.Serialization.XmlElementAttribute(DataType="base64Binary")] public byte[] GetFileChunk(string fileName, int offset, int size) { object[] results = this.Invoke("GetFileChunk", new object[] { fileName, offset, size}); return ((byte[])(results[0])); } /// <remarks/> public void GetFileChunkAsync(string fileName, int offset, int size) { this.GetFileChunkAsync(fileName, offset, size, null); } /// <remarks/> public void GetFileChunkAsync(string fileName, int offset, int size, object userState) { if ((this.GetFileChunkOperationCompleted == null)) { this.GetFileChunkOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetFileChunkOperationCompleted); } this.InvokeAsync("GetFileChunk", new object[] { fileName, offset, size}, this.GetFileChunkOperationCompleted, userState); } private void OnGetFileChunkOperationCompleted(object arg) { if ((this.GetFileChunkCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetFileChunkCompleted(this, new GetFileChunkCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://websitepanel.net/services/GetFileSize", RequestNamespace="http://websitepanel.net/services", ResponseNamespace="http://websitepanel.net/services", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public long GetFileSize(string fileName) { object[] results = this.Invoke("GetFileSize", new object[] { fileName}); return ((long)(results[0])); } /// <remarks/> public void GetFileSizeAsync(string fileName) { this.GetFileSizeAsync(fileName, null); } /// <remarks/> public void GetFileSizeAsync(string fileName, object userState) { if ((this.GetFileSizeOperationCompleted == null)) { this.GetFileSizeOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetFileSizeOperationCompleted); } this.InvokeAsync("GetFileSize", new object[] { fileName}, this.GetFileSizeOperationCompleted, userState); } private void OnGetFileSizeOperationCompleted(object arg) { if ((this.GetFileSizeCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetFileSizeCompleted(this, new GetFileSizeCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://websitepanel.net/services/GetAvailableComponents", RequestNamespace="http://websitepanel.net/services", ResponseNamespace="http://websitepanel.net/services", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public System.Data.DataSet GetAvailableComponents() { object[] results = this.Invoke("GetAvailableComponents", new object[0]); return ((System.Data.DataSet)(results[0])); } /// <remarks/> public void GetAvailableComponentsAsync() { this.GetAvailableComponentsAsync(null); } /// <remarks/> public void GetAvailableComponentsAsync(object userState) { if ((this.GetAvailableComponentsOperationCompleted == null)) { this.GetAvailableComponentsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetAvailableComponentsOperationCompleted); } this.InvokeAsync("GetAvailableComponents", new object[0], this.GetAvailableComponentsOperationCompleted, userState); } private void OnGetAvailableComponentsOperationCompleted(object arg) { if ((this.GetAvailableComponentsCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetAvailableComponentsCompleted(this, new GetAvailableComponentsCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://websitepanel.net/services/GetLatestComponentUpdate", RequestNamespace="http://websitepanel.net/services", ResponseNamespace="http://websitepanel.net/services", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public System.Data.DataSet GetLatestComponentUpdate(string componentCode) { object[] results = this.Invoke("GetLatestComponentUpdate", new object[] { componentCode}); return ((System.Data.DataSet)(results[0])); } /// <remarks/> public void GetLatestComponentUpdateAsync(string componentCode) { this.GetLatestComponentUpdateAsync(componentCode, null); } /// <remarks/> public void GetLatestComponentUpdateAsync(string componentCode, object userState) { if ((this.GetLatestComponentUpdateOperationCompleted == null)) { this.GetLatestComponentUpdateOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetLatestComponentUpdateOperationCompleted); } this.InvokeAsync("GetLatestComponentUpdate", new object[] { componentCode}, this.GetLatestComponentUpdateOperationCompleted, userState); } private void OnGetLatestComponentUpdateOperationCompleted(object arg) { if ((this.GetLatestComponentUpdateCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetLatestComponentUpdateCompleted(this, new GetLatestComponentUpdateCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://websitepanel.net/services/GetComponentUpdate", RequestNamespace="http://websitepanel.net/services", ResponseNamespace="http://websitepanel.net/services", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public System.Data.DataSet GetComponentUpdate(string componentCode, string release) { object[] results = this.Invoke("GetComponentUpdate", new object[] { componentCode, release}); return ((System.Data.DataSet)(results[0])); } /// <remarks/> public void GetComponentUpdateAsync(string componentCode, string release) { this.GetComponentUpdateAsync(componentCode, release, null); } /// <remarks/> public void GetComponentUpdateAsync(string componentCode, string release, object userState) { if ((this.GetComponentUpdateOperationCompleted == null)) { this.GetComponentUpdateOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetComponentUpdateOperationCompleted); } this.InvokeAsync("GetComponentUpdate", new object[] { componentCode, release}, this.GetComponentUpdateOperationCompleted, userState); } private void OnGetComponentUpdateOperationCompleted(object arg) { if ((this.GetComponentUpdateCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetComponentUpdateCompleted(this, new GetComponentUpdateCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> public new void CancelAsync(object userState) { base.CancelAsync(userState); } private bool IsLocalFileSystemWebService(string url) { if (((url == null) || (url == string.Empty))) { return false; } System.Uri wsUri = new System.Uri(url); if (((wsUri.Port >= 1024) && (string.Compare(wsUri.Host, "localHost", System.StringComparison.OrdinalIgnoreCase) == 0))) { return true; } return false; } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.0.30319.1")] public delegate void GetReleaseFileInfoCompletedEventHandler(object sender, GetReleaseFileInfoCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.0.30319.1")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetReleaseFileInfoCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetReleaseFileInfoCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public System.Data.DataSet Result { get { this.RaiseExceptionIfNecessary(); return ((System.Data.DataSet)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.0.30319.1")] public delegate void GetFileChunkCompletedEventHandler(object sender, GetFileChunkCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.0.30319.1")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetFileChunkCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetFileChunkCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public byte[] Result { get { this.RaiseExceptionIfNecessary(); return ((byte[])(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.0.30319.1")] public delegate void GetFileSizeCompletedEventHandler(object sender, GetFileSizeCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.0.30319.1")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetFileSizeCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetFileSizeCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public long Result { get { this.RaiseExceptionIfNecessary(); return ((long)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.0.30319.1")] public delegate void GetAvailableComponentsCompletedEventHandler(object sender, GetAvailableComponentsCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.0.30319.1")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetAvailableComponentsCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetAvailableComponentsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public System.Data.DataSet Result { get { this.RaiseExceptionIfNecessary(); return ((System.Data.DataSet)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.0.30319.1")] public delegate void GetLatestComponentUpdateCompletedEventHandler(object sender, GetLatestComponentUpdateCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.0.30319.1")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetLatestComponentUpdateCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetLatestComponentUpdateCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public System.Data.DataSet Result { get { this.RaiseExceptionIfNecessary(); return ((System.Data.DataSet)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.0.30319.1")] public delegate void GetComponentUpdateCompletedEventHandler(object sender, GetComponentUpdateCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.0.30319.1")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetComponentUpdateCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetComponentUpdateCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public System.Data.DataSet Result { get { this.RaiseExceptionIfNecessary(); return ((System.Data.DataSet)(this.results[0])); } } } } #pragma warning restore 1591
using System; using System.Data; using PCSComUtils.PCSExc; using PCSComUtils.Common; using PCSComUtils.Framework.TableFrame.DS; namespace PCSComUtils.Framework.TableFrame.BO { public class TableConfigBO { private const string THIS = "PCSComUtils.Framework.TableFrame.BO.ITableConfigBO"; public TableConfigBO() { } /// <Description> /// This method checks business rule and call Add() method of DS class /// </Description> /// <Inputs> /// Value object /// </Inputs> /// <Outputs> /// N/A /// </Outputs> /// <Returns> /// void /// </Returns> /// <Authors> /// NgocHT /// </Authors> /// <History> /// 27-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void AddTable(object pobjObjectVO,int pintGroupID) { try { sys_TableVO voSysTable = (sys_TableVO)pobjObjectVO; sys_TableAndGroupVO voTableAndGroup = new sys_TableAndGroupVO(); sys_TableDS dsSysTable = new sys_TableDS(); voTableAndGroup.TableGroupID = pintGroupID; voTableAndGroup.TableID = voSysTable.TableID; voTableAndGroup.TableOrder = dsSysTable.MaxTableOrder(pintGroupID) + 1; dsSysTable.AddTable(pobjObjectVO,pintGroupID); } catch(PCSDBException ex) { throw ex; } catch (Exception ex) { throw ex; } } /// <Description> /// This method checks business rule and call AddAndReturnMaxID() method of DS class /// </Description> /// <Inputs> /// Value object /// </Inputs> /// <Outputs> /// N/A /// </Outputs> /// <Returns> /// void /// </Returns> /// <Authors> /// NgocHT /// </Authors> /// <History> /// 27-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public int AddTableAndReturnMaxID(object pobjObjectVO,int pintGroupID) { // try // { sys_TableVO voSysTable = (sys_TableVO)pobjObjectVO; sys_TableAndGroupVO voTableAndGroup = new sys_TableAndGroupVO(); sys_TableDS dsSysTable = new sys_TableDS(); voTableAndGroup.TableGroupID = pintGroupID; voTableAndGroup.TableID = voSysTable.TableID; voTableAndGroup.TableOrder = dsSysTable.MaxTableOrder(pintGroupID) + 1; return dsSysTable.AddTableAndReturnMaxID(pobjObjectVO,pintGroupID); // } // catch(PCSDBException ex) // { // throw ex; // } // catch (Exception ex) // { // throw ex; // } } //************************************************************************** /// <Description> /// This method not implements yet /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 27-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public object GetObjectVO(int pintID,string VOclass) { const string METHOD_NAME = THIS + ".GetObjectVO()"; throw new PCSException(ErrorCode.NOT_IMPLEMENT, METHOD_NAME,new Exception()); } /// <summary> /// Get all columns name of a table /// </summary> /// <param name="pstrTableOrViewName"></param> /// <returns></returns> /// <author>Trada</author> /// <date>Wednesday, Nov 30 2005</date> public DataSet GetAllColumnNameOfTable(string pstrTableOrViewName) { DataSet dstData = new DataSet(); sys_TableDS dssys_Table = new sys_TableDS(); dstData = dssys_Table.GetAllColumnNameOfTable(pstrTableOrViewName); return dstData; } //************************************************************************** /// <Description> /// This method not implements yet /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 27-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Delete(object pObjectVO) { const string METHOD_NAME = THIS + ".Delete()"; throw new PCSException(ErrorCode.NOT_IMPLEMENT, METHOD_NAME,new Exception()); } //************************************************************************** /// <Description> /// This method checks business rule and call Delete() method of DS class /// </Description> /// <Inputs> /// pintID /// </Inputs> /// <Outputs> /// Delete a record from Database /// </Outputs> /// <Returns> /// void /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 27-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Delete(int pintID) { try { sys_TableDS dsSysTable = new sys_TableDS(); dsSysTable.Delete(pintID); } catch(PCSDBException ex) { throw ex; } catch (Exception ex) { throw ex; } } //************************************************************************** /// <Description> /// This method uses to get data /// </Description> /// <Inputs> /// pintID /// </Inputs> /// <Outputs> /// Value object /// </Outputs> /// <Returns> /// object /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 27-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public object GetObjectVO(int pintID) { try { sys_TableDS dsSysTable = new sys_TableDS(); return dsSysTable.GetObjectVO(pintID); } catch(PCSDBException ex) { throw ex; } catch (Exception ex) { throw ex; } } //************************************************************************** /// <Description> /// This method uses to update data /// </Description> /// <Inputs> /// pobjObjecVO /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// void /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 27-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void UpdateTable(object pobjObjecVO) { try { sys_TableDS dsSysTable = new sys_TableDS(); dsSysTable.Update(pobjObjecVO); } catch(PCSDBException ex) { throw ex; } catch (Exception ex) { throw ex; } } //************************************************************************** /// <Description> /// This method uses to get all data /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// DataSet /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// /// </History> /// <Notes> /// </Notes> //************************************************************************** public DataSet List() { try { sys_TableDS dsSysTable = new sys_TableDS(); return dsSysTable.List(); } catch(PCSDBException ex) { throw ex; } catch (Exception ex) { throw ex; } } //************************************************************************** /// <Description> /// This method uses to update a DataSet /// </Description> /// <Inputs> /// DataSet /// </Inputs> /// <Outputs> /// N/A /// </Outputs> /// <Returns> /// void /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 27-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void UpdateDataSet(DataSet pData) { try { sys_TableDS dsSysTable = new sys_TableDS(); dsSysTable.UpdateDataSet(pData); } catch(PCSDBException ex) { throw ex; } catch (Exception ex) { throw ex; } } //************************************************************************** /// <Description> /// This method uses to get all row in sys_table /// </Description> /// <Inputs> /// N/A /// </Inputs> /// <Outputs> /// dataset sys_TableVO /// </Outputs> /// <Returns> /// dataset /// </Returns> /// <Authors> /// NgocHT /// </Authors> /// <History> /// 28-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public DataSet ListTableOrView() { try { sys_TableDS dsSysTable = new sys_TableDS(); return dsSysTable.ListTableOrView(); } catch (Exception ex) { throw (ex); } } #region IObjectBO Members public void Add(object pObjectDetail) { // TODO: Add TableConfigBO.Add implementation } public void Update(object pObjectDetail) { // TODO: Add TableConfigBO.Update implementation } #endregion } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the PnCurriculumIdioma class. /// </summary> [Serializable] public partial class PnCurriculumIdiomaCollection : ActiveList<PnCurriculumIdioma, PnCurriculumIdiomaCollection> { public PnCurriculumIdiomaCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>PnCurriculumIdiomaCollection</returns> public PnCurriculumIdiomaCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { PnCurriculumIdioma o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the PN_curriculum_idiomas table. /// </summary> [Serializable] public partial class PnCurriculumIdioma : ActiveRecord<PnCurriculumIdioma>, IActiveRecord { #region .ctors and Default Settings public PnCurriculumIdioma() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public PnCurriculumIdioma(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public PnCurriculumIdioma(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public PnCurriculumIdioma(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("PN_curriculum_idiomas", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdCurriculumIdiomas = new TableSchema.TableColumn(schema); colvarIdCurriculumIdiomas.ColumnName = "id_curriculum_idiomas"; colvarIdCurriculumIdiomas.DataType = DbType.Int32; colvarIdCurriculumIdiomas.MaxLength = 0; colvarIdCurriculumIdiomas.AutoIncrement = true; colvarIdCurriculumIdiomas.IsNullable = false; colvarIdCurriculumIdiomas.IsPrimaryKey = true; colvarIdCurriculumIdiomas.IsForeignKey = false; colvarIdCurriculumIdiomas.IsReadOnly = false; colvarIdCurriculumIdiomas.DefaultSetting = @""; colvarIdCurriculumIdiomas.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdCurriculumIdiomas); TableSchema.TableColumn colvarIdLegajo = new TableSchema.TableColumn(schema); colvarIdLegajo.ColumnName = "id_legajo"; colvarIdLegajo.DataType = DbType.Int32; colvarIdLegajo.MaxLength = 0; colvarIdLegajo.AutoIncrement = false; colvarIdLegajo.IsNullable = false; colvarIdLegajo.IsPrimaryKey = false; colvarIdLegajo.IsForeignKey = false; colvarIdLegajo.IsReadOnly = false; colvarIdLegajo.DefaultSetting = @""; colvarIdLegajo.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdLegajo); TableSchema.TableColumn colvarIdioma = new TableSchema.TableColumn(schema); colvarIdioma.ColumnName = "idioma"; colvarIdioma.DataType = DbType.AnsiString; colvarIdioma.MaxLength = -1; colvarIdioma.AutoIncrement = false; colvarIdioma.IsNullable = false; colvarIdioma.IsPrimaryKey = false; colvarIdioma.IsForeignKey = false; colvarIdioma.IsReadOnly = false; colvarIdioma.DefaultSetting = @""; colvarIdioma.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdioma); TableSchema.TableColumn colvarLee = new TableSchema.TableColumn(schema); colvarLee.ColumnName = "lee"; colvarLee.DataType = DbType.AnsiStringFixedLength; colvarLee.MaxLength = 1; colvarLee.AutoIncrement = false; colvarLee.IsNullable = false; colvarLee.IsPrimaryKey = false; colvarLee.IsForeignKey = false; colvarLee.IsReadOnly = false; colvarLee.DefaultSetting = @""; colvarLee.ForeignKeyTableName = ""; schema.Columns.Add(colvarLee); TableSchema.TableColumn colvarEscribe = new TableSchema.TableColumn(schema); colvarEscribe.ColumnName = "escribe"; colvarEscribe.DataType = DbType.AnsiStringFixedLength; colvarEscribe.MaxLength = 1; colvarEscribe.AutoIncrement = false; colvarEscribe.IsNullable = false; colvarEscribe.IsPrimaryKey = false; colvarEscribe.IsForeignKey = false; colvarEscribe.IsReadOnly = false; colvarEscribe.DefaultSetting = @""; colvarEscribe.ForeignKeyTableName = ""; schema.Columns.Add(colvarEscribe); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("PN_curriculum_idiomas",schema); } } #endregion #region Props [XmlAttribute("IdCurriculumIdiomas")] [Bindable(true)] public int IdCurriculumIdiomas { get { return GetColumnValue<int>(Columns.IdCurriculumIdiomas); } set { SetColumnValue(Columns.IdCurriculumIdiomas, value); } } [XmlAttribute("IdLegajo")] [Bindable(true)] public int IdLegajo { get { return GetColumnValue<int>(Columns.IdLegajo); } set { SetColumnValue(Columns.IdLegajo, value); } } [XmlAttribute("Idioma")] [Bindable(true)] public string Idioma { get { return GetColumnValue<string>(Columns.Idioma); } set { SetColumnValue(Columns.Idioma, value); } } [XmlAttribute("Lee")] [Bindable(true)] public string Lee { get { return GetColumnValue<string>(Columns.Lee); } set { SetColumnValue(Columns.Lee, value); } } [XmlAttribute("Escribe")] [Bindable(true)] public string Escribe { get { return GetColumnValue<string>(Columns.Escribe); } set { SetColumnValue(Columns.Escribe, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varIdLegajo,string varIdioma,string varLee,string varEscribe) { PnCurriculumIdioma item = new PnCurriculumIdioma(); item.IdLegajo = varIdLegajo; item.Idioma = varIdioma; item.Lee = varLee; item.Escribe = varEscribe; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdCurriculumIdiomas,int varIdLegajo,string varIdioma,string varLee,string varEscribe) { PnCurriculumIdioma item = new PnCurriculumIdioma(); item.IdCurriculumIdiomas = varIdCurriculumIdiomas; item.IdLegajo = varIdLegajo; item.Idioma = varIdioma; item.Lee = varLee; item.Escribe = varEscribe; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdCurriculumIdiomasColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdLegajoColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn IdiomaColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn LeeColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn EscribeColumn { get { return Schema.Columns[4]; } } #endregion #region Columns Struct public struct Columns { public static string IdCurriculumIdiomas = @"id_curriculum_idiomas"; public static string IdLegajo = @"id_legajo"; public static string Idioma = @"idioma"; public static string Lee = @"lee"; public static string Escribe = @"escribe"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
//--------------------------------------------------------------------------- // // <copyright file=DefaultTextStore.cs company=Microsoft> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: the default text store that allows default TSF enabling. // // History: // 11/17/2003 : yutakas // //--------------------------------------------------------------------------- using System; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Threading; using System.Threading; using System.Diagnostics; using System.Security; using MS.Internal; using MS.Internal.PresentationCore; // SecurityHelper using System.Security.Permissions; using MS.Win32; namespace System.Windows.Input { // This class has the default text store implementation. // DefaultTextStore is a TextStore to be shared by any element of the Dispatcher. // When the keyboard focus is on the element, Cicero input goes into this by default. // This DefaultTextStore will be used unless an Element (such as TextBox) set // the focus on the document manager for its own TextStore. internal class DefaultTextStore : UnsafeNativeMethods.ITfContextOwner, UnsafeNativeMethods.ITfContextOwnerCompositionSink, UnsafeNativeMethods.ITfTransitoryExtensionSink { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #region Constructors // Creates a DefaultTextStore instance. internal DefaultTextStore(Dispatcher dispatcher) { // Save the target Dispatcher. _dispatcher = dispatcher; _editCookie = UnsafeNativeMethods.TF_INVALID_COOKIE; _transitoryExtensionSinkCookie = UnsafeNativeMethods.TF_INVALID_COOKIE; } #endregion Constructors //------------------------------------------------------ // // Public Methods - ITfContextOwner // //------------------------------------------------------ #region ITfContextOwner // // ITfContextOwner implementation for Cicero's default text store. // public void GetACPFromPoint(ref UnsafeNativeMethods.POINT point, UnsafeNativeMethods.GetPositionFromPointFlags flags, out int position) { position = 0; } public void GetTextExt(int start, int end, out UnsafeNativeMethods.RECT rect, out bool clipped) { rect = new UnsafeNativeMethods.RECT(); clipped = false; } public void GetScreenExt(out UnsafeNativeMethods.RECT rect) { rect = new UnsafeNativeMethods.RECT(); } public void GetStatus(out UnsafeNativeMethods.TS_STATUS status) { status = new UnsafeNativeMethods.TS_STATUS(); } public void GetWnd(out IntPtr hwnd) { hwnd = IntPtr.Zero; } public void GetValue(ref Guid guidAttribute, out object varValue) { varValue = null; } #endregion ITfContextOwner //------------------------------------------------------ // // Public Methods - ITfContextOwnerCompositionSink // //------------------------------------------------------ #region ITfContextOwnerCompositionSink /// <SecurityNote> /// Critical - UnsafeNativeMethods.ITfCompositionView is a critical type. /// Safe - The method does nothing with the critical Input parameter. /// </SecurityNote> [SecuritySafeCritical] public void OnStartComposition(UnsafeNativeMethods.ITfCompositionView view, out bool ok) { // Return true in ok to start the composition. ok = true; } /// <SecurityNote> /// Critical - UnsafeNativeMethods.ITfCompositionView & UnsafeNativeMethods.ITfRange are critical types. /// Safe - The method does nothing. /// </SecurityNote> [SecuritySafeCritical] public void OnUpdateComposition(UnsafeNativeMethods.ITfCompositionView view, UnsafeNativeMethods.ITfRange rangeNew) { } /// <SecurityNote> /// Critical - UnsafeNativeMethods.ITfCompositionView is a critical type. /// Safe - The method does nothing. /// </SecurityNote> [SecuritySafeCritical] public void OnEndComposition(UnsafeNativeMethods.ITfCompositionView view) { } #endregion ITfContextOwnerCompositionSink //------------------------------------------------------ // // Public Methods - ITfTransitoryExtensionSink // //------------------------------------------------------ #region ITfTransitoryExtensionSink // Transitory Document has been updated. // This is the notification of the changes of the result string and the composition string. ///<SecurityNote> /// Critical: This code acceses critical data in the form of TextCompositionManager /// TreatAsSafe: There exists a demand for unmanaged code. ///</SecurityNote> [SecurityCritical,SecurityTreatAsSafe] public void OnTransitoryExtensionUpdated(UnsafeNativeMethods.ITfContext context, int ecReadOnly, UnsafeNativeMethods.ITfRange rangeResult, UnsafeNativeMethods.ITfRange rangeComposition, out bool fDeleteResultRange) { SecurityHelper.DemandUnmanagedCode(); fDeleteResultRange = true; TextCompositionManager compmgr = InputManager.Current.PrimaryKeyboardDevice.TextCompositionManager; if (rangeResult != null) { string result = StringFromITfRange(rangeResult, ecReadOnly); if (result.Length > 0) { if (_composition == null) { // We don't have the composition now and we got the result string. // The result text is result and automatic termination is true. _composition = new DefaultTextStoreTextComposition(InputManager.Current, Keyboard.FocusedElement, result, TextCompositionAutoComplete.On); TextCompositionManager.StartComposition(_composition); // relese composition. _composition = null; } else { // Finalize the composition. _composition.SetCompositionText(""); _composition.SetText(result); // We don't call _composition.Complete() here. We just want to generate // TextInput events. TextCompositionManager.CompleteComposition(_composition); // relese composition. _composition = null; } } } if (rangeComposition != null) { string comp = StringFromITfRange(rangeComposition, ecReadOnly); if (comp.Length > 0) { if (_composition == null) { // Start the new composition. _composition = new DefaultTextStoreTextComposition(InputManager.Current, Keyboard.FocusedElement, "", TextCompositionAutoComplete.Off); _composition.SetCompositionText(comp); TextCompositionManager.StartComposition(_composition); } else { // Update the current composition. _composition.SetCompositionText(comp); _composition.SetText(""); TextCompositionManager.UpdateComposition(_composition); } } } } #endregion ITfTransitoryExtensionSink //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ //------------------------------------------------------ // // Public Events // //------------------------------------------------------ //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ // Return the text services host associated with the current Dispatcher. internal static DefaultTextStore Current { get { // DefaultTextStore is per Dispatcher and the cached referrence is stored in InputMethod class. DefaultTextStore defaulttextstore = InputMethod.Current.DefaultTextStore; if(defaulttextstore == null) { defaulttextstore = new DefaultTextStore(Dispatcher.CurrentDispatcher); InputMethod.Current.DefaultTextStore = defaulttextstore; defaulttextstore.Register(); } return defaulttextstore; } } //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ // Pointer to ITfDocumentMgr interface. /// <SecurityNote> /// Critical: This exposes ITfDocumentMgr that has methods with SuppressUnmanagedCodeSecurity. /// </SecurityNote> internal UnsafeNativeMethods.ITfDocumentMgr DocumentManager { [SecurityCritical] get { return _doc.Value;} [SecurityCritical] set { _doc = new SecurityCriticalData<UnsafeNativeMethods.ITfDocumentMgr>(value); } } // EditCookie for ITfContext. internal int EditCookie { // get { return _editCookie; } set { _editCookie = value; } } internal int TransitoryExtensionSinkCookie { get { return _transitoryExtensionSinkCookie; } set { _transitoryExtensionSinkCookie = value; } } // // Get Transitory's DocumentMgr from GUID_COMPARTMENT_TRANSITORYEXTENSION_DOCUMENTMANAGER. // /// <SecurityNote> /// Critical: This code acceses ITfDocumentMgr, ItfCompartment and ITfCompartmentMgr /// TreatAsSafe: There exists a demand for unmanaged code /// </SecurityNote> internal UnsafeNativeMethods.ITfDocumentMgr TransitoryDocumentManager { [SecurityCritical,SecurityTreatAsSafe] get { SecurityHelper.DemandUnmanagedCode(); UnsafeNativeMethods.ITfDocumentMgr doc; UnsafeNativeMethods.ITfCompartmentMgr compartmentMgr; UnsafeNativeMethods.ITfCompartment compartment; // get compartment manager of the parent doc. compartmentMgr = (UnsafeNativeMethods.ITfCompartmentMgr)DocumentManager; // get compartment. Guid guid = UnsafeNativeMethods.GUID_COMPARTMENT_TRANSITORYEXTENSION_DOCUMENTMANAGER; compartmentMgr.GetCompartment(ref guid, out compartment); // get value of the compartment. object obj; compartment.GetValue(out obj); doc = obj as UnsafeNativeMethods.ITfDocumentMgr; Marshal.ReleaseComObject(compartment); return doc; } } //------------------------------------------------------ // // Internal Events // //------------------------------------------------------ //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ // get the text from ITfRange. /// <SecurityNote> /// Critical - calls unmanaged code (GetExtent) /// </SecurityNote> [SecurityCritical] private string StringFromITfRange(UnsafeNativeMethods.ITfRange range, int ecReadOnly) { // Transitory Document uses ther TextStore, which is ACP base. UnsafeNativeMethods.ITfRangeACP rangeacp = (UnsafeNativeMethods.ITfRangeACP)range; int start; int count; int countRet; rangeacp.GetExtent(out start, out count); char[] text = new char[count]; rangeacp.GetText(ecReadOnly, 0, text, count, out countRet); return new string(text); } // This function calls TextServicesContext to create TSF document and start transitory extension. /// <SecurityNote> /// Critical - directly access the text store /// TreatAsSafe - registers "this" as a text store (safe operation) /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] private void Register() { // Create TSF document and advise the sink to it. TextServicesContext.DispatcherCurrent.RegisterTextStore(this); } //------------------------------------------------------ // // Private Properties // //------------------------------------------------------ //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ // Dispatcher for this text store private readonly Dispatcher _dispatcher; // The current active composition. private TextComposition _composition; // The TSF document object. This is a native resource. /// <SecurityNote> /// Critical: UnsafeNativeMethods.ITfDocumentMgr has methods with SuppressUnmanagedCodeSecurity. /// </SecurityNote> [SecurityCritical] private SecurityCriticalData<UnsafeNativeMethods.ITfDocumentMgr> _doc; // The edit cookie TSF returns from CreateContext. private int _editCookie; // The transitory extension sink cookie. private int _transitoryExtensionSinkCookie; } }
// ---------------------------------------------------------------------------------- // // 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; using System.Security.Cryptography.X509Certificates; [TestClass] public class ScenarioTest : ServiceManagementTest { private string serviceName; string perfFile; [TestInitialize] public void Initialize() { serviceName = Utilities.GetUniqueShortName(serviceNamePrefix); pass = false; testStartTime = DateTime.Now; } /// <summary> /// </summary> [TestMethod(), TestCategory("Scenario"), TestCategory("BVT"), 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); try { if (string.IsNullOrEmpty(imageName)) imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows" }, false); vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName, serviceName, imageName, username, password, locationName); // Verify PersistentVMRoleContext vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName); Assert.AreEqual(newAzureQuickVMName, vmRoleCtxt.Name, true); try { vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName + "wrongVMName", serviceName); Assert.Fail("Should Fail!!"); } catch (Exception e) { Console.WriteLine("Fail as expected: {0}", e.ToString()); } // Cleanup vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName, serviceName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName)); pass = true; } catch (Exception e) { pass = false; Console.WriteLine(e.ToString()); throw; } } /// <summary> /// Basic Provisioning a Virtual Machine /// </summary> [TestMethod(), TestCategory("Scenario"), TestCategory("BVT"), 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 newAzureLinuxVMName = Utilities.GetUniqueShortName("PSLinuxVM"); string linuxImageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Linux" }, false); vmPowershellCmdlets.NewAzureQuickVM(OS.Linux, newAzureLinuxVMName, serviceName, linuxImageName, "user", password, locationName); // Verify PersistentVMRoleContext vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(newAzureLinuxVMName, serviceName); Assert.AreEqual(newAzureLinuxVMName, vmRoleCtxt.Name, true); try { vmPowershellCmdlets.RemoveAzureVM(newAzureLinuxVMName + "wrongVMName", serviceName); Assert.Fail("Should Fail!!"); } catch (Exception e) { Console.WriteLine("Fail as expected: {0}", e.ToString()); } // Cleanup vmPowershellCmdlets.RemoveAzureVM(newAzureLinuxVMName, serviceName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureLinuxVMName, serviceName)); pass = true; } /// <summary> /// Verify Advanced Provisioning /// </summary> [TestMethod(), 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" }, 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.CustomProbe, 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" }, 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" }, 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" }, 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" }, 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" }, 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" }, 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" }, 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.RetryFunctionUntilSuccess<ManagementOperationContext>(vmPowershellCmdlets.RemoveAzureVNetConfig, "in use", 10, 30); Utilities.RetryActionUntilSuccess(() => vmPowershellCmdlets.RemoveAzureVNetConfig(), "in use", 10, 30); pass = true; } catch (Exception e) { pass = false; if (cleanupIfFailed) { try { vmPowershellCmdlets.RemoveAzureVNetGateway(vnet1); } catch { } Utilities.RetryActionUntilSuccess(() => vmPowershellCmdlets.RemoveAzureVNetConfig(), "in use", 10, 30); //Utilities.RetryFunctionUntilSuccess<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; } } } }
using System; using UnityEngine; namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] [RequireComponent (typeof(Camera))] [AddComponentMenu("Image Effects/Rendering/Screen Space Ambient Occlusion")] public class ScreenSpaceAmbientOcclusion : MonoBehaviour { public enum SSAOSamples { Low = 0, Medium = 1, High = 2, } [Range(0.05f, 1.0f)] public float m_Radius = 0.4f; public SSAOSamples m_SampleCount = SSAOSamples.Medium; [Range(0.5f, 4.0f)] public float m_OcclusionIntensity = 1.5f; [Range(0, 4)] public int m_Blur = 2; [Range(1,6)] public int m_Downsampling = 2; [Range(0.2f, 2.0f)] public float m_OcclusionAttenuation = 1.0f; [Range(0.00001f, 0.5f)] public float m_MinZ = 0.01f; public Shader m_SSAOShader; private Material m_SSAOMaterial; public Texture2D m_RandomTexture; private bool m_Supported; private static Material CreateMaterial (Shader shader) { if (!shader) return null; Material m = new Material (shader); m.hideFlags = HideFlags.HideAndDontSave; return m; } private static void DestroyMaterial (Material mat) { if (mat) { DestroyImmediate (mat); mat = null; } } void OnDisable() { DestroyMaterial (m_SSAOMaterial); } void Start() { if (!SystemInfo.supportsImageEffects || !SystemInfo.SupportsRenderTextureFormat (RenderTextureFormat.Depth)) { m_Supported = false; enabled = false; return; } CreateMaterials (); if (!m_SSAOMaterial || m_SSAOMaterial.passCount != 5) { m_Supported = false; enabled = false; return; } //CreateRandomTable (26, 0.2f); m_Supported = true; } void OnEnable () { GetComponent<Camera>().depthTextureMode |= DepthTextureMode.DepthNormals; } private void CreateMaterials () { if (!m_SSAOMaterial && m_SSAOShader.isSupported) { m_SSAOMaterial = CreateMaterial (m_SSAOShader); m_SSAOMaterial.SetTexture ("_RandomTexture", m_RandomTexture); } } [ImageEffectOpaque] void OnRenderImage (RenderTexture source, RenderTexture destination) { if (!m_Supported || !m_SSAOShader.isSupported) { enabled = false; return; } CreateMaterials (); m_Downsampling = Mathf.Clamp (m_Downsampling, 1, 6); m_Radius = Mathf.Clamp (m_Radius, 0.05f, 1.0f); m_MinZ = Mathf.Clamp (m_MinZ, 0.00001f, 0.5f); m_OcclusionIntensity = Mathf.Clamp (m_OcclusionIntensity, 0.5f, 4.0f); m_OcclusionAttenuation = Mathf.Clamp (m_OcclusionAttenuation, 0.2f, 2.0f); m_Blur = Mathf.Clamp (m_Blur, 0, 4); // Render SSAO term into a smaller texture RenderTexture rtAO = RenderTexture.GetTemporary (source.width / m_Downsampling, source.height / m_Downsampling, 0); float fovY = GetComponent<Camera>().fieldOfView; float far = GetComponent<Camera>().farClipPlane; float y = Mathf.Tan (fovY * Mathf.Deg2Rad * 0.5f) * far; float x = y * GetComponent<Camera>().aspect; m_SSAOMaterial.SetVector ("_FarCorner", new Vector3(x,y,far)); int noiseWidth, noiseHeight; if (m_RandomTexture) { noiseWidth = m_RandomTexture.width; noiseHeight = m_RandomTexture.height; } else { noiseWidth = 1; noiseHeight = 1; } m_SSAOMaterial.SetVector ("_NoiseScale", new Vector3 ((float)rtAO.width / noiseWidth, (float)rtAO.height / noiseHeight, 0.0f)); m_SSAOMaterial.SetVector ("_Params", new Vector4( m_Radius, m_MinZ, 1.0f / m_OcclusionAttenuation, m_OcclusionIntensity)); bool doBlur = m_Blur > 0; Graphics.Blit (doBlur ? null : source, rtAO, m_SSAOMaterial, (int)m_SampleCount); if (doBlur) { // Blur SSAO horizontally RenderTexture rtBlurX = RenderTexture.GetTemporary (source.width, source.height, 0); m_SSAOMaterial.SetVector ("_TexelOffsetScale", new Vector4 ((float)m_Blur / source.width, 0,0,0)); m_SSAOMaterial.SetTexture ("_SSAO", rtAO); Graphics.Blit (null, rtBlurX, m_SSAOMaterial, 3); RenderTexture.ReleaseTemporary (rtAO); // original rtAO not needed anymore // Blur SSAO vertically RenderTexture rtBlurY = RenderTexture.GetTemporary (source.width, source.height, 0); m_SSAOMaterial.SetVector ("_TexelOffsetScale", new Vector4 (0, (float)m_Blur/source.height, 0,0)); m_SSAOMaterial.SetTexture ("_SSAO", rtBlurX); Graphics.Blit (source, rtBlurY, m_SSAOMaterial, 3); RenderTexture.ReleaseTemporary (rtBlurX); // blurX RT not needed anymore rtAO = rtBlurY; // AO is the blurred one now } // Modulate scene rendering with SSAO m_SSAOMaterial.SetTexture ("_SSAO", rtAO); Graphics.Blit (source, destination, m_SSAOMaterial, 4); RenderTexture.ReleaseTemporary (rtAO); } /* private void CreateRandomTable (int count, float minLength) { Random.seed = 1337; Vector3[] samples = new Vector3[count]; // initial samples for (int i = 0; i < count; ++i) samples[i] = Random.onUnitSphere; // energy minimization: push samples away from others int iterations = 100; while (iterations-- > 0) { for (int i = 0; i < count; ++i) { Vector3 vec = samples[i]; Vector3 res = Vector3.zero; // minimize with other samples for (int j = 0; j < count; ++j) { Vector3 force = vec - samples[j]; float fac = Vector3.Dot (force, force); if (fac > 0.00001f) res += force * (1.0f / fac); } samples[i] = (samples[i] + res * 0.5f).normalized; } } // now scale samples between minLength and 1.0 for (int i = 0; i < count; ++i) { samples[i] = samples[i] * Random.Range (minLength, 1.0f); } string table = string.Format ("#define SAMPLE_COUNT {0}\n", count); table += "const float3 RAND_SAMPLES[SAMPLE_COUNT] = {\n"; for (int i = 0; i < count; ++i) { Vector3 v = samples[i]; table += string.Format("\tfloat3({0},{1},{2}),\n", v.x, v.y, v.z); } table += "};\n"; Debug.Log (table); } */ } }
#pragma warning disable 649, 1572, 1573 // ReSharper disable RedundantUsingDirective #region Using using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Text; using Khronos; #endregion // ReSharper disable StringLiteralTypo // ReSharper disable CheckNamespace // ReSharper disable InconsistentNaming // ReSharper disable JoinDeclarationAndInitializer // ReSharper disable InvalidXmlDocComment // ReSharper disable CommentTypo namespace OpenGL { public partial class Gl { /// <summary> /// [GL] Value of GL_VERSION_ES_CL_1_0 symbol. /// </summary> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] public const int VERSION_ES_CL_1_0 = 1; /// <summary> /// [GL] Value of GL_VERSION_ES_CM_1_1 symbol. /// </summary> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] public const int VERSION_ES_CM_1_1 = 1; /// <summary> /// [GL] Value of GL_VERSION_ES_CL_1_1 symbol. /// </summary> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] public const int VERSION_ES_CL_1_1 = 1; /// <summary> /// [GLES1.1] glClipPlanef: specify a plane against which all geometry is clipped /// </summary> /// <param name="p"> /// A <see cref="T:ClipPlaneName" />. /// </param> /// <param name="eqn"> /// A <see cref="T:float[]" />. /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1", Profile = "common")] public static void ClipPlane(ClipPlaneName p, float[] eqn) { Debug.Assert(eqn.Length >= 4); unsafe { fixed (float* p_eqn = eqn) { Debug.Assert(Delegates.pglClipPlanef != null, "pglClipPlanef not implemented"); Delegates.pglClipPlanef((int) p, p_eqn); } } DebugCheckErrors(null); } /// <summary> /// [GLES1.1] glFrustumf: multiply the current matrix by a perspective matrix /// </summary> /// <param name="left"> /// Specify the coordinates for the left and right vertical clipping planes. /// </param> /// <param name="right"> /// Specify the coordinates for the left and right vertical clipping planes. /// </param> /// <param name="bottom"> /// Specify the coordinates for the bottom and top horizontal clipping planes. /// </param> /// <param name="top"> /// Specify the coordinates for the bottom and top horizontal clipping planes. /// </param> /// <param name="near"> /// Specify the distances to the near and far depth clipping planes. Both distances must be positive. /// </param> /// <param name="far"> /// Specify the distances to the near and far depth clipping planes. Both distances must be positive. /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1", Profile = "common")] public static void Frustum(float left, float right, float bottom, float top, float near, float far) { Debug.Assert(Delegates.pglFrustumf != null, "pglFrustumf not implemented"); Delegates.pglFrustumf(left, right, bottom, top, near, far); DebugCheckErrors(null); } /// <summary> /// [GLES1.1] glGetClipPlanef: return the coefficients of the specified clipping plane /// </summary> /// <param name="plane"> /// Specifies a clipping plane. The number of clipping planes depends on the implementation, but at least six clipping /// planes are supported. Symbolic names of the form Gl.CLIP_PLANEi, where i is an integer between 0 and /// Gl.MAX_CLIP_PLANES-1, are accepted. /// </param> /// <param name="equation"> /// Returns four fixed-point or floating-point values that are the coefficients of the plane equation of /// <paramref /// name="plane" /> /// in eye coordinates in the order p1, p2, p3, and p4. The initial value is (0, 0, 0, 0). /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1", Profile = "common")] public static void GetClipPlane(ClipPlaneName plane, [Out] float[] equation) { Debug.Assert(equation.Length >= 4); unsafe { fixed (float* p_equation = equation) { Debug.Assert(Delegates.pglGetClipPlanef != null, "pglGetClipPlanef not implemented"); Delegates.pglGetClipPlanef((int) plane, p_equation); } } DebugCheckErrors(null); } /// <summary> /// [GLES1.1] glOrthof: multiply the current matrix with an orthographic matrix /// </summary> /// <param name="left"> /// Specify the coordinates for the left and right vertical clipping planes. /// </param> /// <param name="right"> /// Specify the coordinates for the left and right vertical clipping planes. /// </param> /// <param name="bottom"> /// Specify the coordinates for the bottom and top horizontal clipping planes. /// </param> /// <param name="top"> /// Specify the coordinates for the bottom and top horizontal clipping planes. /// </param> /// <param name="near"> /// Specify the distances to the nearer and farther depth clipping planes. These values are negative if the plane is to be /// behind the viewer. /// </param> /// <param name="far"> /// Specify the distances to the nearer and farther depth clipping planes. These values are negative if the plane is to be /// behind the viewer. /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1", Profile = "common")] public static void Ortho(float left, float right, float bottom, float top, float near, float far) { Debug.Assert(Delegates.pglOrthof != null, "pglOrthof not implemented"); Delegates.pglOrthof(left, right, bottom, top, near, far); DebugCheckErrors(null); } /// <summary> /// [GLES1.1] glAlphaFuncx: specify the alpha test function /// </summary> /// <param name="func"> /// Specifies the alpha comparison function. Symbolic constants Gl.NEVER, Gl.LESS, Gl.EQUAL, Gl.LEQUAL, Gl.GREATER, /// Gl.NOTEQUAL, Gl.GEQUAL, and Gl.ALWAYS are accepted. The initial value is Gl.ALWAYS. /// </param> /// <param name="ref"> /// Specifies the reference value that incoming alpha values are compared to. This value is clamped to the range [0, 1], /// where 0 represents the lowest possible alpha value and 1 the highest possible value. The initial reference value is 0. /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] public static void AlphaFunc(AlphaFunction func, IntPtr @ref) { Debug.Assert(Delegates.pglAlphaFuncx != null, "pglAlphaFuncx not implemented"); Delegates.pglAlphaFuncx((int) func, @ref); DebugCheckErrors(null); } /// <summary> /// [GLES1.1] glClearColorx: specify clear values for the color buffer /// </summary> /// <param name="red"> /// Specify the red, green, blue, and alpha values used when the color buffer is cleared. The initial values are all 0. /// </param> /// <param name="green"> /// Specify the red, green, blue, and alpha values used when the color buffer is cleared. The initial values are all 0. /// </param> /// <param name="blue"> /// Specify the red, green, blue, and alpha values used when the color buffer is cleared. The initial values are all 0. /// </param> /// <param name="alpha"> /// Specify the red, green, blue, and alpha values used when the color buffer is cleared. The initial values are all 0. /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] public static void ClearColor(IntPtr red, IntPtr green, IntPtr blue, IntPtr alpha) { Debug.Assert(Delegates.pglClearColorx != null, "pglClearColorx not implemented"); Delegates.pglClearColorx(red, green, blue, alpha); DebugCheckErrors(null); } /// <summary> /// [GLES1.1] glClearDepthx: specify the clear value for the depth buffer /// </summary> /// <param name="depth"> /// Specifies the depth value used when the depth buffer is cleared. The initial value is 1. /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] public static void ClearDepth(IntPtr depth) { Debug.Assert(Delegates.pglClearDepthx != null, "pglClearDepthx not implemented"); Delegates.pglClearDepthx(depth); DebugCheckErrors(null); } /// <summary> /// [GLES1.1] glClipPlanex: specify a plane against which all geometry is clipped /// </summary> /// <param name="plane"> /// Specifies which clipping plane is being positioned. Symbolic names of the form Gl.CLIP_PLANEi, where i is an integer /// between 0 and Gl.MAX_CLIP_PLANES-1, are accepted. /// </param> /// <param name="equation"> /// Specifies the address of an array of four fixed-point or floating-point values. These are the coefficients of a plane /// equation in object coordinates: p1, p2, p3, and p4, in that order. /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] public static void ClipPlane(ClipPlaneName plane, IntPtr[] equation) { Debug.Assert(equation.Length >= 4); unsafe { fixed (IntPtr* p_equation = equation) { Debug.Assert(Delegates.pglClipPlanex != null, "pglClipPlanex not implemented"); Delegates.pglClipPlanex((int) plane, p_equation); } } DebugCheckErrors(null); } /// <summary> /// [GLES1.1] glColor4x: set the current color /// </summary> /// <param name="red"> /// Specify new red, green, blue, and alpha values for the current color. /// </param> /// <param name="green"> /// Specify new red, green, blue, and alpha values for the current color. /// </param> /// <param name="blue"> /// Specify new red, green, blue, and alpha values for the current color. /// </param> /// <param name="alpha"> /// Specify new red, green, blue, and alpha values for the current color. /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] public static void Color4(IntPtr red, IntPtr green, IntPtr blue, IntPtr alpha) { Debug.Assert(Delegates.pglColor4x != null, "pglColor4x not implemented"); Delegates.pglColor4x(red, green, blue, alpha); DebugCheckErrors(null); } /// <summary> /// [GLES1.1] glDepthRangex: specify mapping of depth values from normalized device coordinates to window coordinates /// </summary> /// <param name="n"> /// A <see cref="T:IntPtr" />. /// </param> /// <param name="f"> /// A <see cref="T:IntPtr" />. /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] public static void DepthRange(IntPtr n, IntPtr f) { Debug.Assert(Delegates.pglDepthRangex != null, "pglDepthRangex not implemented"); Delegates.pglDepthRangex(n, f); DebugCheckErrors(null); } /// <summary> /// [GLES1.1] glFrustumx: multiply the current matrix by a perspective matrix /// </summary> /// <param name="left"> /// Specify the coordinates for the left and right vertical clipping planes. /// </param> /// <param name="right"> /// Specify the coordinates for the left and right vertical clipping planes. /// </param> /// <param name="bottom"> /// Specify the coordinates for the bottom and top horizontal clipping planes. /// </param> /// <param name="top"> /// Specify the coordinates for the bottom and top horizontal clipping planes. /// </param> /// <param name="near"> /// Specify the distances to the near and far depth clipping planes. Both distances must be positive. /// </param> /// <param name="far"> /// Specify the distances to the near and far depth clipping planes. Both distances must be positive. /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] public static void Frustum(IntPtr left, IntPtr right, IntPtr bottom, IntPtr top, IntPtr near, IntPtr far) { Debug.Assert(Delegates.pglFrustumx != null, "pglFrustumx not implemented"); Delegates.pglFrustumx(left, right, bottom, top, near, far); DebugCheckErrors(null); } /// <summary> /// [GLES1.1] glGetClipPlanex: return the coefficients of the specified clipping plane /// </summary> /// <param name="plane"> /// Specifies a clipping plane. The number of clipping planes depends on the implementation, but at least six clipping /// planes are supported. Symbolic names of the form Gl.CLIP_PLANEi, where i is an integer between 0 and /// Gl.MAX_CLIP_PLANES-1, are accepted. /// </param> /// <param name="equation"> /// Returns four fixed-point or floating-point values that are the coefficients of the plane equation of /// <paramref /// name="plane" /> /// in eye coordinates in the order p1, p2, p3, and p4. The initial value is (0, 0, 0, 0). /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] public static void GetClipPlane(ClipPlaneName plane, [Out] IntPtr[] equation) { Debug.Assert(equation.Length >= 4); unsafe { fixed (IntPtr* p_equation = equation) { Debug.Assert(Delegates.pglGetClipPlanex != null, "pglGetClipPlanex not implemented"); Delegates.pglGetClipPlanex((int) plane, p_equation); } } DebugCheckErrors(null); } /// <summary> /// [GLES1.1] glGetFixedv: return the value or values of a selected parameter /// </summary> /// <param name="pname"> /// Specifies the parameter value to be returned. The symbolic constants in the list below are accepted. /// </param> /// <param name="params"> /// Returns the value or values of the specified parameter. /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] public static void GetFixed(GetPName pname, [Out] IntPtr[] @params) { unsafe { fixed (IntPtr* p_params = @params) { Debug.Assert(Delegates.pglGetFixedv != null, "pglGetFixedv not implemented"); Delegates.pglGetFixedv((int) pname, p_params); } } DebugCheckErrors(null); } /// <summary> /// [GLES1.1] glGetTexParameterxv: return texture parameter values /// </summary> /// <param name="target"> /// Specifies the target texture, which must be Gl.TEXTURE_2D. /// </param> /// <param name="pname"> /// Specifies the symbolic name of a texture parameter. Which can be one of the following: Gl.TEXTURE_MIN_FILTER, /// Gl.TEXTURE_MAG_FILTER, Gl.TEXTURE_WRAP_S, Gl.TEXTURE_WRAP_T, or Gl.GENERATE_MIPMAP. /// </param> /// <param name="params"> /// Returns texture parameters. /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] public static void GetTexParameter(TextureTarget target, GetTextureParameter pname, [Out] IntPtr[] @params) { unsafe { fixed (IntPtr* p_params = @params) { Debug.Assert(Delegates.pglGetTexParameterxv != null, "pglGetTexParameterxv not implemented"); Delegates.pglGetTexParameterxv((int) target, (int) pname, p_params); } } DebugCheckErrors(null); } /// <summary> /// [GLES1.1] glLineWidthx: specify the width of rasterized lines /// </summary> /// <param name="width"> /// Specifies the width of rasterized lines. The initial value is 1. /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] public static void LineWidth(IntPtr width) { Debug.Assert(Delegates.pglLineWidthx != null, "pglLineWidthx not implemented"); Delegates.pglLineWidthx(width); DebugCheckErrors(null); } /// <summary> /// [GLES1.1] glLoadMatrixx: replace the current matrix with the specified matrix /// </summary> /// <param name="m"> /// Specifies a pointer to 16 consecutive values, which are used as the elements of a 4x4 column-major matrix. /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] public static void LoadMatrixx(IntPtr[] m) { Debug.Assert(m.Length >= 16); unsafe { fixed (IntPtr* p_m = m) { Debug.Assert(Delegates.pglLoadMatrixx != null, "pglLoadMatrixx not implemented"); Delegates.pglLoadMatrixx(p_m); } } DebugCheckErrors(null); } /// <summary> /// [GLES1.1] glLoadMatrixx: replace the current matrix with the specified matrix /// </summary> /// <param name="m"> /// Specifies a pointer to 16 consecutive values, which are used as the elements of a 4x4 column-major matrix. /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] public static unsafe void LoadMatrixx(IntPtr* m) { Debug.Assert(Delegates.pglLoadMatrixx != null, "pglLoadMatrixx not implemented"); Delegates.pglLoadMatrixx(m); DebugCheckErrors(null); } /// <summary> /// [GLES1.1] glLoadMatrixx: replace the current matrix with the specified matrix /// </summary> /// <param name="m"> /// Specifies a pointer to 16 consecutive values, which are used as the elements of a 4x4 column-major matrix. /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] public static void LoadMatrixx<T>(T m) where T : struct { Debug.Assert(Delegates.pglLoadMatrixx != null, "pglLoadMatrixx not implemented"); unsafe { TypedReference refM = __makeref(m); IntPtr refMPtr = *(IntPtr*) (&refM); Delegates.pglLoadMatrixx((IntPtr*) refMPtr.ToPointer()); } DebugCheckErrors(null); } /// <summary> /// [GLES1.1] glMultMatrixx: multiply the current matrix with the specified matrix /// </summary> /// <param name="m"> /// Points to 16 consecutive values that are used as the elements of a 4x4 column-major matrix. /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] public static void MultMatrixx(IntPtr[] m) { Debug.Assert(m.Length >= 16); unsafe { fixed (IntPtr* p_m = m) { Debug.Assert(Delegates.pglMultMatrixx != null, "pglMultMatrixx not implemented"); Delegates.pglMultMatrixx(p_m); } } DebugCheckErrors(null); } /// <summary> /// [GLES1.1] glMultMatrixx: multiply the current matrix with the specified matrix /// </summary> /// <param name="m"> /// Points to 16 consecutive values that are used as the elements of a 4x4 column-major matrix. /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] public static unsafe void MultMatrixx(IntPtr* m) { Debug.Assert(Delegates.pglMultMatrixx != null, "pglMultMatrixx not implemented"); Delegates.pglMultMatrixx(m); DebugCheckErrors(null); } /// <summary> /// [GLES1.1] glMultMatrixx: multiply the current matrix with the specified matrix /// </summary> /// <param name="m"> /// Points to 16 consecutive values that are used as the elements of a 4x4 column-major matrix. /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] public static void MultMatrixx<T>(T m) where T : struct { Debug.Assert(Delegates.pglMultMatrixx != null, "pglMultMatrixx not implemented"); unsafe { TypedReference refM = __makeref(m); IntPtr refMPtr = *(IntPtr*) (&refM); Delegates.pglMultMatrixx((IntPtr*) refMPtr.ToPointer()); } DebugCheckErrors(null); } /// <summary> /// [GLES1.1] glMultiTexCoord4x: set the current texture coordinates /// </summary> /// <param name="texture"> /// A <see cref="T:TextureUnit" />. /// </param> /// <param name="s"> /// Specify <paramref name="s" />, <paramref name="t" />, <paramref name="r" />, and <paramref name="q" /> texture /// coordinates /// for <paramref name="target" /> texture unit. /// </param> /// <param name="t"> /// Specify <paramref name="s" />, <paramref name="t" />, <paramref name="r" />, and <paramref name="q" /> texture /// coordinates /// for <paramref name="target" /> texture unit. /// </param> /// <param name="r"> /// Specify <paramref name="s" />, <paramref name="t" />, <paramref name="r" />, and <paramref name="q" /> texture /// coordinates /// for <paramref name="target" /> texture unit. /// </param> /// <param name="q"> /// Specify <paramref name="s" />, <paramref name="t" />, <paramref name="r" />, and <paramref name="q" /> texture /// coordinates /// for <paramref name="target" /> texture unit. /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] public static void MultiTexCoord4(TextureUnit texture, IntPtr s, IntPtr t, IntPtr r, IntPtr q) { Debug.Assert(Delegates.pglMultiTexCoord4x != null, "pglMultiTexCoord4x not implemented"); Delegates.pglMultiTexCoord4x((int) texture, s, t, r, q); DebugCheckErrors(null); } /// <summary> /// [GLES1.1] glNormal3x: set the current normal vector /// </summary> /// <param name="nx"> /// Specify the <paramref name="x" />, <paramref name="y" />, and <paramref name="z" /> coordinates of the new current /// normal. /// The initial value is (0, 0, 1). /// </param> /// <param name="ny"> /// Specify the <paramref name="x" />, <paramref name="y" />, and <paramref name="z" /> coordinates of the new current /// normal. /// The initial value is (0, 0, 1). /// </param> /// <param name="nz"> /// Specify the <paramref name="x" />, <paramref name="y" />, and <paramref name="z" /> coordinates of the new current /// normal. /// The initial value is (0, 0, 1). /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] public static void Normal3(IntPtr nx, IntPtr ny, IntPtr nz) { Debug.Assert(Delegates.pglNormal3x != null, "pglNormal3x not implemented"); Delegates.pglNormal3x(nx, ny, nz); DebugCheckErrors(null); } /// <summary> /// [GLES1.1] glOrthox: multiply the current matrix with an orthographic matrix /// </summary> /// <param name="left"> /// Specify the coordinates for the left and right vertical clipping planes. /// </param> /// <param name="right"> /// Specify the coordinates for the left and right vertical clipping planes. /// </param> /// <param name="bottom"> /// Specify the coordinates for the bottom and top horizontal clipping planes. /// </param> /// <param name="top"> /// Specify the coordinates for the bottom and top horizontal clipping planes. /// </param> /// <param name="near"> /// Specify the distances to the nearer and farther depth clipping planes. These values are negative if the plane is to be /// behind the viewer. /// </param> /// <param name="far"> /// Specify the distances to the nearer and farther depth clipping planes. These values are negative if the plane is to be /// behind the viewer. /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] public static void Orthox(IntPtr left, IntPtr right, IntPtr bottom, IntPtr top, IntPtr near, IntPtr far) { Debug.Assert(Delegates.pglOrthox != null, "pglOrthox not implemented"); Delegates.pglOrthox(left, right, bottom, top, near, far); DebugCheckErrors(null); } /// <summary> /// [GLES1.1] glPointParameterx: specify parameters for point rasterization /// </summary> /// <param name="pname"> /// Specifies the single-valued parameter to be updated. Can be either Gl.POINT_SIZE_MIN, Gl.POINT_SIZE_MAX, or /// Gl.POINT_FADE_THRESHOLD_SIZE. /// </param> /// <param name="param"> /// Specifies the value that the parameter will be set to. /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] public static void PointParameter(int pname, IntPtr param) { Debug.Assert(Delegates.pglPointParameterx != null, "pglPointParameterx not implemented"); Delegates.pglPointParameterx(pname, param); DebugCheckErrors(null); } /// <summary> /// [GLES1.1] glPointParameterxv: specify parameters for point rasterization /// </summary> /// <param name="pname"> /// Specifies the single-valued parameter to be updated. Can be either Gl.POINT_SIZE_MIN, Gl.POINT_SIZE_MAX, or /// Gl.POINT_FADE_THRESHOLD_SIZE. /// </param> /// <param name="params"> /// A <see cref="T:IntPtr[]" />. /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] public static void PointParameter(int pname, IntPtr[] @params) { unsafe { fixed (IntPtr* p_params = @params) { Debug.Assert(Delegates.pglPointParameterxv != null, "pglPointParameterxv not implemented"); Delegates.pglPointParameterxv(pname, p_params); } } DebugCheckErrors(null); } /// <summary> /// [GLES1.1] glPointSizex: specify the diameter of rasterized points /// </summary> /// <param name="size"> /// Specifies the diameter of rasterized points. The initial value is 1. /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] public static void PointSize(IntPtr size) { Debug.Assert(Delegates.pglPointSizex != null, "pglPointSizex not implemented"); Delegates.pglPointSizex(size); DebugCheckErrors(null); } /// <summary> /// [GLES1.1] glPolygonOffsetx: set the scale and units used to calculate depth values /// </summary> /// <param name="factor"> /// Specifies a scale factor that is used to create a variable depth offset for each polygon. The initial value is 0. /// </param> /// <param name="units"> /// Is multiplied by an implementation-specific value to create a constant depth offset. The initial value is 0. /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] public static void PolygonOffset(IntPtr factor, IntPtr units) { Debug.Assert(Delegates.pglPolygonOffsetx != null, "pglPolygonOffsetx not implemented"); Delegates.pglPolygonOffsetx(factor, units); DebugCheckErrors(null); } /// <summary> /// [GLES1.1] glRotatex: multiply the current matrix by a rotation matrix /// </summary> /// <param name="angle"> /// Specifies the angle of rotation, in degrees. /// </param> /// <param name="x"> /// Specify the <paramref name="x" />, <paramref name="y" />, and <paramref name="z" /> coordinates of a vector, /// respectively. /// </param> /// <param name="y"> /// Specify the <paramref name="x" />, <paramref name="y" />, and <paramref name="z" /> coordinates of a vector, /// respectively. /// </param> /// <param name="z"> /// Specify the <paramref name="x" />, <paramref name="y" />, and <paramref name="z" /> coordinates of a vector, /// respectively. /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] public static void Rotate(IntPtr angle, IntPtr x, IntPtr y, IntPtr z) { Debug.Assert(Delegates.pglRotatex != null, "pglRotatex not implemented"); Delegates.pglRotatex(angle, x, y, z); DebugCheckErrors(null); } /// <summary> /// [GLES1.1] glSampleCoveragex: specify mask to modify multisampled pixel fragments /// </summary> /// <param name="value"> /// Specifies the coverage of the modification mask. The value is clamped to the range [0, 1], where 0 represents no /// coverage and 1 full coverage. The initial value is 1. /// </param> /// <param name="invert"> /// Specifies whether the modification mask implied by <paramref name="value" /> is inverted or not. The initial value is /// Gl.FALSE. /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] public static void SampleCoverage(int value, bool invert) { Debug.Assert(Delegates.pglSampleCoveragex != null, "pglSampleCoveragex not implemented"); Delegates.pglSampleCoveragex(value, invert); DebugCheckErrors(null); } /// <summary> /// [GLES1.1] glScalex: multiply the current matrix by a general scaling matrix /// </summary> /// <param name="x"> /// Specify scale factors along the <paramref name="x" />, <paramref name="y" />, and <paramref name="z" /> axes, /// respectively. /// </param> /// <param name="y"> /// Specify scale factors along the <paramref name="x" />, <paramref name="y" />, and <paramref name="z" /> axes, /// respectively. /// </param> /// <param name="z"> /// Specify scale factors along the <paramref name="x" />, <paramref name="y" />, and <paramref name="z" /> axes, /// respectively. /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] public static void Scale(IntPtr x, IntPtr y, IntPtr z) { Debug.Assert(Delegates.pglScalex != null, "pglScalex not implemented"); Delegates.pglScalex(x, y, z); DebugCheckErrors(null); } /// <summary> /// [GLES1.1] glTexParameterx: set texture parameters /// </summary> /// <param name="target"> /// Specifies the target texture, which must be Gl.TEXTURE_2D. /// </param> /// <param name="pname"> /// Specifies the symbolic name of a single-valued texture parameter. Which can be one of the following: /// Gl.TEXTURE_MIN_FILTER, Gl.TEXTURE_MAG_FILTER, Gl.TEXTURE_WRAP_S, Gl.TEXTURE_WRAP_T, or Gl.GENERATE_MIPMAP. /// </param> /// <param name="param"> /// Specifies the value of <paramref name="pname" />. /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] public static void TexParameter(TextureTarget target, GetTextureParameter pname, IntPtr param) { Debug.Assert(Delegates.pglTexParameterx != null, "pglTexParameterx not implemented"); Delegates.pglTexParameterx((int) target, (int) pname, param); DebugCheckErrors(null); } /// <summary> /// [GLES1.1] glTexParameterxv: set texture parameters /// </summary> /// <param name="target"> /// Specifies the target texture, which must be Gl.TEXTURE_2D. /// </param> /// <param name="pname"> /// Specifies the symbolic name of a single-valued texture parameter. Which can be one of the following: /// Gl.TEXTURE_MIN_FILTER, Gl.TEXTURE_MAG_FILTER, Gl.TEXTURE_WRAP_S, Gl.TEXTURE_WRAP_T, or Gl.GENERATE_MIPMAP. /// </param> /// <param name="params"> /// A <see cref="T:IntPtr[]" />. /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] public static void TexParameter(TextureTarget target, GetTextureParameter pname, IntPtr[] @params) { unsafe { fixed (IntPtr* p_params = @params) { Debug.Assert(Delegates.pglTexParameterxv != null, "pglTexParameterxv not implemented"); Delegates.pglTexParameterxv((int) target, (int) pname, p_params); } } DebugCheckErrors(null); } /// <summary> /// [GLES1.1] glTranslatex: multiply the current matrix by a translation matrix /// </summary> /// <param name="x"> /// Specify the <paramref name="x" />, <paramref name="y" />, and <paramref name="z" /> coordinates of a translation /// vector. /// </param> /// <param name="y"> /// Specify the <paramref name="x" />, <paramref name="y" />, and <paramref name="z" /> coordinates of a translation /// vector. /// </param> /// <param name="z"> /// Specify the <paramref name="x" />, <paramref name="y" />, and <paramref name="z" /> coordinates of a translation /// vector. /// </param> [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] public static void Translate(IntPtr x, IntPtr y, IntPtr z) { Debug.Assert(Delegates.pglTranslatex != null, "pglTranslatex not implemented"); Delegates.pglTranslatex(x, y, z); DebugCheckErrors(null); } internal static unsafe partial class Delegates { [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1", Profile = "common")] [SuppressUnmanagedCodeSecurity] internal delegate void glClipPlanef(int p, float* eqn); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1", Profile = "common")] [ThreadStatic] internal static glClipPlanef pglClipPlanef; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1", Profile = "common")] [SuppressUnmanagedCodeSecurity] internal delegate void glFrustumf(float l, float r, float b, float t, float n, float f); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1", Profile = "common")] [ThreadStatic] internal static glFrustumf pglFrustumf; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1", Profile = "common")] [SuppressUnmanagedCodeSecurity] internal delegate void glGetClipPlanef(int plane, float* equation); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1", Profile = "common")] [ThreadStatic] internal static glGetClipPlanef pglGetClipPlanef; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1", Profile = "common")] [SuppressUnmanagedCodeSecurity] internal delegate void glOrthof(float l, float r, float b, float t, float n, float f); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1", Profile = "common")] [ThreadStatic] internal static glOrthof pglOrthof; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glAlphaFuncx(int func, IntPtr @ref); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glAlphaFuncx pglAlphaFuncx; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glClearColorx(IntPtr red, IntPtr green, IntPtr blue, IntPtr alpha); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glClearColorx pglClearColorx; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glClearDepthx(IntPtr depth); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glClearDepthx pglClearDepthx; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glClipPlanex(int plane, IntPtr* equation); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glClipPlanex pglClipPlanex; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glColor4x(IntPtr red, IntPtr green, IntPtr blue, IntPtr alpha); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glColor4x pglColor4x; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glDepthRangex(IntPtr n, IntPtr f); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glDepthRangex pglDepthRangex; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glFogx(int pname, IntPtr param); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glFogx pglFogx; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glFogxv(int pname, IntPtr* param); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glFogxv pglFogxv; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glFrustumx(IntPtr l, IntPtr r, IntPtr b, IntPtr t, IntPtr n, IntPtr f); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glFrustumx pglFrustumx; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glGetClipPlanex(int plane, IntPtr* equation); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glGetClipPlanex pglGetClipPlanex; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glGetFixedv(int pname, IntPtr* @params); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glGetFixedv pglGetFixedv; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glGetLightxv(int light, int pname, IntPtr* @params); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glGetLightxv pglGetLightxv; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glGetMaterialxv(int face, int pname, IntPtr* @params); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glGetMaterialxv pglGetMaterialxv; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glGetTexEnvxv(int target, int pname, IntPtr* @params); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glGetTexEnvxv pglGetTexEnvxv; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glGetTexParameterxv(int target, int pname, IntPtr* @params); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glGetTexParameterxv pglGetTexParameterxv; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glLightModelx(int pname, IntPtr param); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glLightModelx pglLightModelx; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glLightModelxv(int pname, IntPtr* param); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glLightModelxv pglLightModelxv; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glLightx(int light, int pname, IntPtr param); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glLightx pglLightx; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glLightxv(int light, int pname, IntPtr* @params); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glLightxv pglLightxv; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glLineWidthx(IntPtr width); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glLineWidthx pglLineWidthx; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glLoadMatrixx(IntPtr* m); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glLoadMatrixx pglLoadMatrixx; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glMaterialx(int face, int pname, IntPtr param); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glMaterialx pglMaterialx; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glMaterialxv(int face, int pname, IntPtr* param); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glMaterialxv pglMaterialxv; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glMultMatrixx(IntPtr* m); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glMultMatrixx pglMultMatrixx; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glMultiTexCoord4x(int texture, IntPtr s, IntPtr t, IntPtr r, IntPtr q); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glMultiTexCoord4x pglMultiTexCoord4x; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glNormal3x(IntPtr nx, IntPtr ny, IntPtr nz); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glNormal3x pglNormal3x; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glOrthox(IntPtr l, IntPtr r, IntPtr b, IntPtr t, IntPtr n, IntPtr f); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glOrthox pglOrthox; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glPointParameterx(int pname, IntPtr param); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glPointParameterx pglPointParameterx; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glPointParameterxv(int pname, IntPtr* @params); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glPointParameterxv pglPointParameterxv; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glPointSizex(IntPtr size); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glPointSizex pglPointSizex; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glPolygonOffsetx(IntPtr factor, IntPtr units); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glPolygonOffsetx pglPolygonOffsetx; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glRotatex(IntPtr angle, IntPtr x, IntPtr y, IntPtr z); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glRotatex pglRotatex; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glSampleCoveragex(int value, [MarshalAs(UnmanagedType.I1)] bool invert); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glSampleCoveragex pglSampleCoveragex; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glScalex(IntPtr x, IntPtr y, IntPtr z); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glScalex pglScalex; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glTexEnvx(int target, int pname, IntPtr param); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glTexEnvx pglTexEnvx; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glTexEnvxv(int target, int pname, IntPtr* @params); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glTexEnvxv pglTexEnvxv; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glTexParameterx(int target, int pname, IntPtr param); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glTexParameterx pglTexParameterx; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glTexParameterxv(int target, int pname, IntPtr* @params); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glTexParameterxv pglTexParameterxv; [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [SuppressUnmanagedCodeSecurity] internal delegate void glTranslatex(IntPtr x, IntPtr y, IntPtr z); [RequiredByFeature("GL_VERSION_ES_CM_1_0", Api = "gles1")] [ThreadStatic] internal static glTranslatex pglTranslatex; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; namespace Microsoft.Azure.Management.Sql.Models { /// <summary> /// Represents the properties of an Azure SQL Database Elastic Pool. /// </summary> public partial class ElasticPoolActivityProperties { private string _elasticPoolName; /// <summary> /// Optional. Gets the name of the Elastic Pool. /// </summary> public string ElasticPoolName { get { return this._elasticPoolName; } set { this._elasticPoolName = value; } } private System.DateTime? _endTime; /// <summary> /// Optional. Gets the time the operation finished. /// </summary> public System.DateTime? EndTime { get { return this._endTime; } set { this._endTime = value; } } private int? _errorCode; /// <summary> /// Optional. Gets the error code if available. /// </summary> public int? ErrorCode { get { return this._errorCode; } set { this._errorCode = value; } } private string _errorMessage; /// <summary> /// Optional. Gets the error message if available. /// </summary> public string ErrorMessage { get { return this._errorMessage; } set { this._errorMessage = value; } } private int? _errorSeverity; /// <summary> /// Optional. Gets the error severity if available. /// </summary> public int? ErrorSeverity { get { return this._errorSeverity; } set { this._errorSeverity = value; } } private string _operation; /// <summary> /// Optional. Gets the operation name. /// </summary> public string Operation { get { return this._operation; } set { this._operation = value; } } private Guid _operationId; /// <summary> /// Optional. Gets the unique operation ID. /// </summary> public Guid OperationId { get { return this._operationId; } set { this._operationId = value; } } private int? _percentComplete; /// <summary> /// Optional. Gets the percentage complete if available. /// </summary> public int? PercentComplete { get { return this._percentComplete; } set { this._percentComplete = value; } } private int? _requestedDatabaseDtuMax; /// <summary> /// Optional. Gets the requested max DTU per database if available. /// </summary> public int? RequestedDatabaseDtuMax { get { return this._requestedDatabaseDtuMax; } set { this._requestedDatabaseDtuMax = value; } } private int? _requestedDatabaseDtuMin; /// <summary> /// Optional. Gets the requested min DTU per database if available. /// </summary> public int? RequestedDatabaseDtuMin { get { return this._requestedDatabaseDtuMin; } set { this._requestedDatabaseDtuMin = value; } } private int? _requestedDtu; /// <summary> /// Optional. Gets the requested DTU for the pool if available. /// </summary> public int? RequestedDtu { get { return this._requestedDtu; } set { this._requestedDtu = value; } } private string _requestedElasticPoolName; /// <summary> /// Optional. Gets the requested name for the Elastic Pool if available. /// </summary> public string RequestedElasticPoolName { get { return this._requestedElasticPoolName; } set { this._requestedElasticPoolName = value; } } private long? _requestedStorageLimitInGB; /// <summary> /// Optional. Gets the requested storage limit for the pool in GB if /// available. /// </summary> public long? RequestedStorageLimitInGB { get { return this._requestedStorageLimitInGB; } set { this._requestedStorageLimitInGB = value; } } private string _serverName; /// <summary> /// Optional. Gets the name of the Azure Sql Database Server the /// Elastic Pool is in. /// </summary> public string ServerName { get { return this._serverName; } set { this._serverName = value; } } private System.DateTime? _startTime; /// <summary> /// Optional. Gets the time the operation started. /// </summary> public System.DateTime? StartTime { get { return this._startTime; } set { this._startTime = value; } } private string _state; /// <summary> /// Optional. Gets the current state of the operation. /// </summary> public string State { get { return this._state; } set { this._state = value; } } /// <summary> /// Initializes a new instance of the ElasticPoolActivityProperties /// class. /// </summary> public ElasticPoolActivityProperties() { } } }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Spanner.V1.Snippets { using Google.Api.Gax; using Google.Api.Gax.Grpc; using Google.Cloud.Spanner.Common.V1; using apis = Google.Cloud.Spanner.V1; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading; using System.Threading.Tasks; /// <summary>Generated snippets</summary> public class GeneratedSpannerClientSnippets { /// <summary>Snippet for CreateSessionAsync</summary> public async Task CreateSessionAsync() { // Snippet: CreateSessionAsync(DatabaseName,CallSettings) // Additional: CreateSessionAsync(DatabaseName,CancellationToken) // Create client SpannerClient spannerClient = await SpannerClient.CreateAsync(); // Initialize request argument(s) DatabaseName database = new DatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); // Make the request Session response = await spannerClient.CreateSessionAsync(database); // End snippet } /// <summary>Snippet for CreateSession</summary> public void CreateSession() { // Snippet: CreateSession(DatabaseName,CallSettings) // Create client SpannerClient spannerClient = SpannerClient.Create(); // Initialize request argument(s) DatabaseName database = new DatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"); // Make the request Session response = spannerClient.CreateSession(database); // End snippet } /// <summary>Snippet for CreateSessionAsync</summary> public async Task CreateSessionAsync_RequestObject() { // Snippet: CreateSessionAsync(CreateSessionRequest,CallSettings) // Additional: CreateSessionAsync(CreateSessionRequest,CancellationToken) // Create client SpannerClient spannerClient = await SpannerClient.CreateAsync(); // Initialize request argument(s) CreateSessionRequest request = new CreateSessionRequest { DatabaseAsDatabaseName = new DatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }; // Make the request Session response = await spannerClient.CreateSessionAsync(request); // End snippet } /// <summary>Snippet for CreateSession</summary> public void CreateSession_RequestObject() { // Snippet: CreateSession(CreateSessionRequest,CallSettings) // Create client SpannerClient spannerClient = SpannerClient.Create(); // Initialize request argument(s) CreateSessionRequest request = new CreateSessionRequest { DatabaseAsDatabaseName = new DatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"), }; // Make the request Session response = spannerClient.CreateSession(request); // End snippet } /// <summary>Snippet for GetSessionAsync</summary> public async Task GetSessionAsync() { // Snippet: GetSessionAsync(SessionName,CallSettings) // Additional: GetSessionAsync(SessionName,CancellationToken) // Create client SpannerClient spannerClient = await SpannerClient.CreateAsync(); // Initialize request argument(s) SessionName name = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); // Make the request Session response = await spannerClient.GetSessionAsync(name); // End snippet } /// <summary>Snippet for GetSession</summary> public void GetSession() { // Snippet: GetSession(SessionName,CallSettings) // Create client SpannerClient spannerClient = SpannerClient.Create(); // Initialize request argument(s) SessionName name = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); // Make the request Session response = spannerClient.GetSession(name); // End snippet } /// <summary>Snippet for GetSessionAsync</summary> public async Task GetSessionAsync_RequestObject() { // Snippet: GetSessionAsync(GetSessionRequest,CallSettings) // Additional: GetSessionAsync(GetSessionRequest,CancellationToken) // Create client SpannerClient spannerClient = await SpannerClient.CreateAsync(); // Initialize request argument(s) GetSessionRequest request = new GetSessionRequest { SessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), }; // Make the request Session response = await spannerClient.GetSessionAsync(request); // End snippet } /// <summary>Snippet for GetSession</summary> public void GetSession_RequestObject() { // Snippet: GetSession(GetSessionRequest,CallSettings) // Create client SpannerClient spannerClient = SpannerClient.Create(); // Initialize request argument(s) GetSessionRequest request = new GetSessionRequest { SessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), }; // Make the request Session response = spannerClient.GetSession(request); // End snippet } /// <summary>Snippet for ListSessionsAsync</summary> public async Task ListSessionsAsync() { // Snippet: ListSessionsAsync(string,string,int?,CallSettings) // Create client SpannerClient spannerClient = await SpannerClient.CreateAsync(); // Initialize request argument(s) string formattedDatabase = new Google.Cloud.Spanner.Common.V1.DatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]").ToString(); // Make the request PagedAsyncEnumerable<ListSessionsResponse, Session> response = spannerClient.ListSessionsAsync(formattedDatabase); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Session item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListSessionsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Session item in page) { Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Session> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Session item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListSessions</summary> public void ListSessions() { // Snippet: ListSessions(string,string,int?,CallSettings) // Create client SpannerClient spannerClient = SpannerClient.Create(); // Initialize request argument(s) string formattedDatabase = new Google.Cloud.Spanner.Common.V1.DatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]").ToString(); // Make the request PagedEnumerable<ListSessionsResponse, Session> response = spannerClient.ListSessions(formattedDatabase); // Iterate over all response items, lazily performing RPCs as required foreach (Session item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListSessionsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Session item in page) { Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Session> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Session item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListSessionsAsync</summary> public async Task ListSessionsAsync_RequestObject() { // Snippet: ListSessionsAsync(ListSessionsRequest,CallSettings) // Create client SpannerClient spannerClient = await SpannerClient.CreateAsync(); // Initialize request argument(s) ListSessionsRequest request = new ListSessionsRequest { Database = new Google.Cloud.Spanner.Common.V1.DatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]").ToString(), }; // Make the request PagedAsyncEnumerable<ListSessionsResponse, Session> response = spannerClient.ListSessionsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Session item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListSessionsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Session item in page) { Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Session> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Session item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListSessions</summary> public void ListSessions_RequestObject() { // Snippet: ListSessions(ListSessionsRequest,CallSettings) // Create client SpannerClient spannerClient = SpannerClient.Create(); // Initialize request argument(s) ListSessionsRequest request = new ListSessionsRequest { Database = new Google.Cloud.Spanner.Common.V1.DatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]").ToString(), }; // Make the request PagedEnumerable<ListSessionsResponse, Session> response = spannerClient.ListSessions(request); // Iterate over all response items, lazily performing RPCs as required foreach (Session item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListSessionsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Session item in page) { Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Session> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Session item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for DeleteSessionAsync</summary> public async Task DeleteSessionAsync() { // Snippet: DeleteSessionAsync(SessionName,CallSettings) // Additional: DeleteSessionAsync(SessionName,CancellationToken) // Create client SpannerClient spannerClient = await SpannerClient.CreateAsync(); // Initialize request argument(s) SessionName name = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); // Make the request await spannerClient.DeleteSessionAsync(name); // End snippet } /// <summary>Snippet for DeleteSession</summary> public void DeleteSession() { // Snippet: DeleteSession(SessionName,CallSettings) // Create client SpannerClient spannerClient = SpannerClient.Create(); // Initialize request argument(s) SessionName name = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); // Make the request spannerClient.DeleteSession(name); // End snippet } /// <summary>Snippet for DeleteSessionAsync</summary> public async Task DeleteSessionAsync_RequestObject() { // Snippet: DeleteSessionAsync(DeleteSessionRequest,CallSettings) // Additional: DeleteSessionAsync(DeleteSessionRequest,CancellationToken) // Create client SpannerClient spannerClient = await SpannerClient.CreateAsync(); // Initialize request argument(s) DeleteSessionRequest request = new DeleteSessionRequest { SessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), }; // Make the request await spannerClient.DeleteSessionAsync(request); // End snippet } /// <summary>Snippet for DeleteSession</summary> public void DeleteSession_RequestObject() { // Snippet: DeleteSession(DeleteSessionRequest,CallSettings) // Create client SpannerClient spannerClient = SpannerClient.Create(); // Initialize request argument(s) DeleteSessionRequest request = new DeleteSessionRequest { SessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), }; // Make the request spannerClient.DeleteSession(request); // End snippet } /// <summary>Snippet for ExecuteSqlAsync</summary> public async Task ExecuteSqlAsync_RequestObject() { // Snippet: ExecuteSqlAsync(ExecuteSqlRequest,CallSettings) // Additional: ExecuteSqlAsync(ExecuteSqlRequest,CancellationToken) // Create client SpannerClient spannerClient = await SpannerClient.CreateAsync(); // Initialize request argument(s) ExecuteSqlRequest request = new ExecuteSqlRequest { SessionAsSessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Sql = "", }; // Make the request ResultSet response = await spannerClient.ExecuteSqlAsync(request); // End snippet } /// <summary>Snippet for ExecuteSql</summary> public void ExecuteSql_RequestObject() { // Snippet: ExecuteSql(ExecuteSqlRequest,CallSettings) // Create client SpannerClient spannerClient = SpannerClient.Create(); // Initialize request argument(s) ExecuteSqlRequest request = new ExecuteSqlRequest { SessionAsSessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Sql = "", }; // Make the request ResultSet response = spannerClient.ExecuteSql(request); // End snippet } /// <summary>Snippet for ExecuteStreamingSql</summary> public async Task ExecuteStreamingSql() { // Snippet: ExecuteStreamingSql(ExecuteSqlRequest,CallSettings) // Create client SpannerClient spannerClient = SpannerClient.Create(); // Initialize request argument ExecuteSqlRequest request = new ExecuteSqlRequest { SessionAsSessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Sql = "", }; // Make the request, returning a streaming response SpannerClient.ExecuteStreamingSqlStream streamingResponse = spannerClient.ExecuteStreamingSql(request); // Read streaming responses from server until complete IAsyncEnumerator<PartialResultSet> responseStream = streamingResponse.ResponseStream; while (await responseStream.MoveNext()) { PartialResultSet response = responseStream.Current; // Do something with streamed response } // The response stream has completed // End snippet } /// <summary>Snippet for ReadAsync</summary> public async Task ReadAsync_RequestObject() { // Snippet: ReadAsync(ReadRequest,CallSettings) // Additional: ReadAsync(ReadRequest,CancellationToken) // Create client SpannerClient spannerClient = await SpannerClient.CreateAsync(); // Initialize request argument(s) ReadRequest request = new ReadRequest { SessionAsSessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Table = "", Columns = { }, KeySet = new KeySet(), }; // Make the request ResultSet response = await spannerClient.ReadAsync(request); // End snippet } /// <summary>Snippet for Read</summary> public void Read_RequestObject() { // Snippet: Read(ReadRequest,CallSettings) // Create client SpannerClient spannerClient = SpannerClient.Create(); // Initialize request argument(s) ReadRequest request = new ReadRequest { SessionAsSessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Table = "", Columns = { }, KeySet = new KeySet(), }; // Make the request ResultSet response = spannerClient.Read(request); // End snippet } /// <summary>Snippet for StreamingRead</summary> public async Task StreamingRead() { // Snippet: StreamingRead(ReadRequest,CallSettings) // Create client SpannerClient spannerClient = SpannerClient.Create(); // Initialize request argument ReadRequest request = new ReadRequest { SessionAsSessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Table = "", Columns = { }, KeySet = new KeySet(), }; // Make the request, returning a streaming response SpannerClient.StreamingReadStream streamingResponse = spannerClient.StreamingRead(request); // Read streaming responses from server until complete IAsyncEnumerator<PartialResultSet> responseStream = streamingResponse.ResponseStream; while (await responseStream.MoveNext()) { PartialResultSet response = responseStream.Current; // Do something with streamed response } // The response stream has completed // End snippet } /// <summary>Snippet for BeginTransactionAsync</summary> public async Task BeginTransactionAsync() { // Snippet: BeginTransactionAsync(SessionName,TransactionOptions,CallSettings) // Additional: BeginTransactionAsync(SessionName,TransactionOptions,CancellationToken) // Create client SpannerClient spannerClient = await SpannerClient.CreateAsync(); // Initialize request argument(s) SessionName session = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); TransactionOptions options = new TransactionOptions(); // Make the request Transaction response = await spannerClient.BeginTransactionAsync(session, options); // End snippet } /// <summary>Snippet for BeginTransaction</summary> public void BeginTransaction() { // Snippet: BeginTransaction(SessionName,TransactionOptions,CallSettings) // Create client SpannerClient spannerClient = SpannerClient.Create(); // Initialize request argument(s) SessionName session = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); TransactionOptions options = new TransactionOptions(); // Make the request Transaction response = spannerClient.BeginTransaction(session, options); // End snippet } /// <summary>Snippet for BeginTransactionAsync</summary> public async Task BeginTransactionAsync_RequestObject() { // Snippet: BeginTransactionAsync(BeginTransactionRequest,CallSettings) // Additional: BeginTransactionAsync(BeginTransactionRequest,CancellationToken) // Create client SpannerClient spannerClient = await SpannerClient.CreateAsync(); // Initialize request argument(s) BeginTransactionRequest request = new BeginTransactionRequest { SessionAsSessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Options = new TransactionOptions(), }; // Make the request Transaction response = await spannerClient.BeginTransactionAsync(request); // End snippet } /// <summary>Snippet for BeginTransaction</summary> public void BeginTransaction_RequestObject() { // Snippet: BeginTransaction(BeginTransactionRequest,CallSettings) // Create client SpannerClient spannerClient = SpannerClient.Create(); // Initialize request argument(s) BeginTransactionRequest request = new BeginTransactionRequest { SessionAsSessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Options = new TransactionOptions(), }; // Make the request Transaction response = spannerClient.BeginTransaction(request); // End snippet } /// <summary>Snippet for CommitAsync</summary> public async Task CommitAsync1() { // Snippet: CommitAsync(SessionName,ByteString,IEnumerable<Mutation>,CallSettings) // Additional: CommitAsync(SessionName,ByteString,IEnumerable<Mutation>,CancellationToken) // Create client SpannerClient spannerClient = await SpannerClient.CreateAsync(); // Initialize request argument(s) SessionName session = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); ByteString transactionId = ByteString.Empty; IEnumerable<Mutation> mutations = new List<Mutation>(); // Make the request CommitResponse response = await spannerClient.CommitAsync(session, transactionId, mutations); // End snippet } /// <summary>Snippet for Commit</summary> public void Commit1() { // Snippet: Commit(SessionName,ByteString,IEnumerable<Mutation>,CallSettings) // Create client SpannerClient spannerClient = SpannerClient.Create(); // Initialize request argument(s) SessionName session = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); ByteString transactionId = ByteString.Empty; IEnumerable<Mutation> mutations = new List<Mutation>(); // Make the request CommitResponse response = spannerClient.Commit(session, transactionId, mutations); // End snippet } /// <summary>Snippet for CommitAsync</summary> public async Task CommitAsync2() { // Snippet: CommitAsync(SessionName,TransactionOptions,IEnumerable<Mutation>,CallSettings) // Additional: CommitAsync(SessionName,TransactionOptions,IEnumerable<Mutation>,CancellationToken) // Create client SpannerClient spannerClient = await SpannerClient.CreateAsync(); // Initialize request argument(s) SessionName session = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); TransactionOptions singleUseTransaction = new TransactionOptions(); IEnumerable<Mutation> mutations = new List<Mutation>(); // Make the request CommitResponse response = await spannerClient.CommitAsync(session, singleUseTransaction, mutations); // End snippet } /// <summary>Snippet for Commit</summary> public void Commit2() { // Snippet: Commit(SessionName,TransactionOptions,IEnumerable<Mutation>,CallSettings) // Create client SpannerClient spannerClient = SpannerClient.Create(); // Initialize request argument(s) SessionName session = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); TransactionOptions singleUseTransaction = new TransactionOptions(); IEnumerable<Mutation> mutations = new List<Mutation>(); // Make the request CommitResponse response = spannerClient.Commit(session, singleUseTransaction, mutations); // End snippet } /// <summary>Snippet for CommitAsync</summary> public async Task CommitAsync_RequestObject() { // Snippet: CommitAsync(CommitRequest,CallSettings) // Additional: CommitAsync(CommitRequest,CancellationToken) // Create client SpannerClient spannerClient = await SpannerClient.CreateAsync(); // Initialize request argument(s) CommitRequest request = new CommitRequest { SessionAsSessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Mutations = { }, }; // Make the request CommitResponse response = await spannerClient.CommitAsync(request); // End snippet } /// <summary>Snippet for Commit</summary> public void Commit_RequestObject() { // Snippet: Commit(CommitRequest,CallSettings) // Create client SpannerClient spannerClient = SpannerClient.Create(); // Initialize request argument(s) CommitRequest request = new CommitRequest { SessionAsSessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), Mutations = { }, }; // Make the request CommitResponse response = spannerClient.Commit(request); // End snippet } /// <summary>Snippet for RollbackAsync</summary> public async Task RollbackAsync() { // Snippet: RollbackAsync(SessionName,ByteString,CallSettings) // Additional: RollbackAsync(SessionName,ByteString,CancellationToken) // Create client SpannerClient spannerClient = await SpannerClient.CreateAsync(); // Initialize request argument(s) SessionName session = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); ByteString transactionId = ByteString.Empty; // Make the request await spannerClient.RollbackAsync(session, transactionId); // End snippet } /// <summary>Snippet for Rollback</summary> public void Rollback() { // Snippet: Rollback(SessionName,ByteString,CallSettings) // Create client SpannerClient spannerClient = SpannerClient.Create(); // Initialize request argument(s) SessionName session = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"); ByteString transactionId = ByteString.Empty; // Make the request spannerClient.Rollback(session, transactionId); // End snippet } /// <summary>Snippet for RollbackAsync</summary> public async Task RollbackAsync_RequestObject() { // Snippet: RollbackAsync(RollbackRequest,CallSettings) // Additional: RollbackAsync(RollbackRequest,CancellationToken) // Create client SpannerClient spannerClient = await SpannerClient.CreateAsync(); // Initialize request argument(s) RollbackRequest request = new RollbackRequest { SessionAsSessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), TransactionId = ByteString.Empty, }; // Make the request await spannerClient.RollbackAsync(request); // End snippet } /// <summary>Snippet for Rollback</summary> public void Rollback_RequestObject() { // Snippet: Rollback(RollbackRequest,CallSettings) // Create client SpannerClient spannerClient = SpannerClient.Create(); // Initialize request argument(s) RollbackRequest request = new RollbackRequest { SessionAsSessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"), TransactionId = ByteString.Empty, }; // Make the request spannerClient.Rollback(request); // End snippet } /// <summary>Snippet for PartitionQueryAsync</summary> public async Task PartitionQueryAsync_RequestObject() { // Snippet: PartitionQueryAsync(PartitionQueryRequest,CallSettings) // Additional: PartitionQueryAsync(PartitionQueryRequest,CancellationToken) // Create client SpannerClient spannerClient = await SpannerClient.CreateAsync(); // Initialize request argument(s) PartitionQueryRequest request = new PartitionQueryRequest { Session = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").ToString(), Sql = "", }; // Make the request PartitionResponse response = await spannerClient.PartitionQueryAsync(request); // End snippet } /// <summary>Snippet for PartitionQuery</summary> public void PartitionQuery_RequestObject() { // Snippet: PartitionQuery(PartitionQueryRequest,CallSettings) // Create client SpannerClient spannerClient = SpannerClient.Create(); // Initialize request argument(s) PartitionQueryRequest request = new PartitionQueryRequest { Session = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").ToString(), Sql = "", }; // Make the request PartitionResponse response = spannerClient.PartitionQuery(request); // End snippet } /// <summary>Snippet for PartitionReadAsync</summary> public async Task PartitionReadAsync_RequestObject() { // Snippet: PartitionReadAsync(PartitionReadRequest,CallSettings) // Additional: PartitionReadAsync(PartitionReadRequest,CancellationToken) // Create client SpannerClient spannerClient = await SpannerClient.CreateAsync(); // Initialize request argument(s) PartitionReadRequest request = new PartitionReadRequest { Session = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").ToString(), Table = "", KeySet = new KeySet(), }; // Make the request PartitionResponse response = await spannerClient.PartitionReadAsync(request); // End snippet } /// <summary>Snippet for PartitionRead</summary> public void PartitionRead_RequestObject() { // Snippet: PartitionRead(PartitionReadRequest,CallSettings) // Create client SpannerClient spannerClient = SpannerClient.Create(); // Initialize request argument(s) PartitionReadRequest request = new PartitionReadRequest { Session = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]").ToString(), Table = "", KeySet = new KeySet(), }; // Make the request PartitionResponse response = spannerClient.PartitionRead(request); // End snippet } } }
/* * Farseer Physics Engine based on Box2D.XNA port: * Copyright (c) 2010 Ian Qvist * * Box2D.XNA port of Box2D: * Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler * * Original source Box2D: * Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * 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. */ using System.Diagnostics; using FarseerPhysics.Common; using Microsoft.Xna.Framework; namespace FarseerPhysics.Dynamics.Joints { /// <summary> /// A gear joint is used to connect two joints together. Either joint /// can be a revolute or prismatic joint. You specify a gear ratio /// to bind the motions together: /// coordinate1 + ratio * coordinate2 = ant /// The ratio can be negative or positive. If one joint is a revolute joint /// and the other joint is a prismatic joint, then the ratio will have units /// of length or units of 1/length. /// @warning The revolute and prismatic joints must be attached to /// fixed bodies (which must be body1 on those joints). /// </summary> public class GearJoint : Joint { private Jacobian _J; private float _ant; private FixedPrismaticJoint _fixedPrismatic1; private FixedPrismaticJoint _fixedPrismatic2; private FixedRevoluteJoint _fixedRevolute1; private FixedRevoluteJoint _fixedRevolute2; private float _impulse; private float _mass; private PrismaticJoint _prismatic1; private PrismaticJoint _prismatic2; private RevoluteJoint _revolute1; private RevoluteJoint _revolute2; /// <summary> /// Requires two existing revolute or prismatic joints (any combination will work). /// The provided joints must attach a dynamic body to a static body. /// </summary> /// <param name="jointA">The first joint.</param> /// <param name="jointB">The second joint.</param> /// <param name="ratio">The ratio.</param> public GearJoint(Joint jointA, Joint jointB, float ratio) : base(jointA.BodyA, jointA.BodyB) { JointType = JointType.Gear; JointA = jointA; JointB = jointB; Ratio = ratio; JointType type1 = jointA.JointType; JointType type2 = jointB.JointType; // Make sure its the right kind of joint Debug.Assert(type1 == JointType.Revolute || type1 == JointType.Prismatic || type1 == JointType.FixedRevolute || type1 == JointType.FixedPrismatic); Debug.Assert(type2 == JointType.Revolute || type2 == JointType.Prismatic || type2 == JointType.FixedRevolute || type2 == JointType.FixedPrismatic); // In the case of a prismatic and revolute joint, the first body must be static. if (type1 == JointType.Revolute || type1 == JointType.Prismatic) Debug.Assert(jointA.BodyA.BodyType == BodyType.Static); if (type2 == JointType.Revolute || type2 == JointType.Prismatic) Debug.Assert(jointB.BodyA.BodyType == BodyType.Static); float coordinate1 = 0.0f, coordinate2 = 0.0f; switch (type1) { case JointType.Revolute: BodyA = jointA.BodyB; _revolute1 = (RevoluteJoint) jointA; LocalAnchor1 = _revolute1.LocalAnchorB; coordinate1 = _revolute1.JointAngle; break; case JointType.Prismatic: BodyA = jointA.BodyB; _prismatic1 = (PrismaticJoint) jointA; LocalAnchor1 = _prismatic1.LocalAnchorB; coordinate1 = _prismatic1.JointTranslation; break; case JointType.FixedRevolute: BodyA = jointA.BodyA; _fixedRevolute1 = (FixedRevoluteJoint) jointA; LocalAnchor1 = _fixedRevolute1.LocalAnchorA; coordinate1 = _fixedRevolute1.JointAngle; break; case JointType.FixedPrismatic: BodyA = jointA.BodyA; _fixedPrismatic1 = (FixedPrismaticJoint) jointA; LocalAnchor1 = _fixedPrismatic1.LocalAnchorA; coordinate1 = _fixedPrismatic1.JointTranslation; break; } switch (type2) { case JointType.Revolute: BodyB = jointB.BodyB; _revolute2 = (RevoluteJoint) jointB; LocalAnchor2 = _revolute2.LocalAnchorB; coordinate2 = _revolute2.JointAngle; break; case JointType.Prismatic: BodyB = jointB.BodyB; _prismatic2 = (PrismaticJoint) jointB; LocalAnchor2 = _prismatic2.LocalAnchorB; coordinate2 = _prismatic2.JointTranslation; break; case JointType.FixedRevolute: BodyB = jointB.BodyA; _fixedRevolute2 = (FixedRevoluteJoint) jointB; LocalAnchor2 = _fixedRevolute2.LocalAnchorA; coordinate2 = _fixedRevolute2.JointAngle; break; case JointType.FixedPrismatic: BodyB = jointB.BodyA; _fixedPrismatic2 = (FixedPrismaticJoint) jointB; LocalAnchor2 = _fixedPrismatic2.LocalAnchorA; coordinate2 = _fixedPrismatic2.JointTranslation; break; } _ant = coordinate1 + Ratio * coordinate2; } public override Vector2 WorldAnchorA { get { return BodyA.GetWorldPoint(LocalAnchor1); } } public override Vector2 WorldAnchorB { get { return BodyB.GetWorldPoint(LocalAnchor2); } } /// <summary> /// The gear ratio. /// </summary> public float Ratio { get; set; } /// <summary> /// The first revolute/prismatic joint attached to the gear joint. /// </summary> public Joint JointA { get; set; } /// <summary> /// The second revolute/prismatic joint attached to the gear joint. /// </summary> public Joint JointB { get; set; } public Vector2 LocalAnchor1 { get; private set; } public Vector2 LocalAnchor2 { get; private set; } public override Vector2 GetReactionForce(float inv_dt) { Vector2 P = _impulse * _J.LinearB; return inv_dt * P; } public override float GetReactionTorque(float inv_dt) { Transform xf1; BodyB.GetTransform(out xf1); Vector2 r = MathUtils.Multiply(ref xf1.R, LocalAnchor2 - BodyB.LocalCenter); Vector2 P = _impulse * _J.LinearB; float L = _impulse * _J.AngularB - MathUtils.Cross(r, P); return inv_dt * L; } internal override void InitVelocityConstraints(ref TimeStep step) { Body b1 = BodyA; Body b2 = BodyB; float K = 0.0f; _J.SetZero(); if (_revolute1 != null || _fixedRevolute1 != null) { _J.AngularA = -1.0f; K += b1.InvI; } else { Vector2 ug; if (_prismatic1 != null) ug = _prismatic1.LocalXAxis1; // MathUtils.Multiply(ref xfg1.R, _prismatic1.LocalXAxis1); else ug = _fixedPrismatic1.LocalXAxis1; // MathUtils.Multiply(ref xfg1.R, _prismatic1.LocalXAxis1); Transform xf1 /*, xfg1*/; b1.GetTransform(out xf1); //g1.GetTransform(out xfg1); Vector2 r = MathUtils.Multiply(ref xf1.R, LocalAnchor1 - b1.LocalCenter); float crug = MathUtils.Cross(r, ug); _J.LinearA = -ug; _J.AngularA = -crug; K += b1.InvMass + b1.InvI * crug * crug; } if (_revolute2 != null || _fixedRevolute2 != null) { _J.AngularB = -Ratio; K += Ratio * Ratio * b2.InvI; } else { Vector2 ug; if (_prismatic2 != null) ug = _prismatic2.LocalXAxis1; // MathUtils.Multiply(ref xfg1.R, _prismatic1.LocalXAxis1); else ug = _fixedPrismatic2.LocalXAxis1; // MathUtils.Multiply(ref xfg1.R, _prismatic1.LocalXAxis1); Transform /*xfg1,*/ xf2; //g1.GetTransform(out xfg1); b2.GetTransform(out xf2); Vector2 r = MathUtils.Multiply(ref xf2.R, LocalAnchor2 - b2.LocalCenter); float crug = MathUtils.Cross(r, ug); _J.LinearB = -Ratio * ug; _J.AngularB = -Ratio * crug; K += Ratio * Ratio * (b2.InvMass + b2.InvI * crug * crug); } // Compute effective mass. Debug.Assert(K > 0.0f); _mass = K > 0.0f ? 1.0f / K : 0.0f; if (Settings.EnableWarmstarting) { // Warm starting. b1.LinearVelocityInternal += b1.InvMass * _impulse * _J.LinearA; b1.AngularVelocityInternal += b1.InvI * _impulse * _J.AngularA; b2.LinearVelocityInternal += b2.InvMass * _impulse * _J.LinearB; b2.AngularVelocityInternal += b2.InvI * _impulse * _J.AngularB; } else { _impulse = 0.0f; } } internal override void SolveVelocityConstraints(ref TimeStep step) { Body b1 = BodyA; Body b2 = BodyB; float Cdot = _J.Compute(b1.LinearVelocityInternal, b1.AngularVelocityInternal, b2.LinearVelocityInternal, b2.AngularVelocityInternal); float impulse = _mass * (-Cdot); _impulse += impulse; b1.LinearVelocityInternal += b1.InvMass * impulse * _J.LinearA; b1.AngularVelocityInternal += b1.InvI * impulse * _J.AngularA; b2.LinearVelocityInternal += b2.InvMass * impulse * _J.LinearB; b2.AngularVelocityInternal += b2.InvI * impulse * _J.AngularB; } internal override bool SolvePositionConstraints() { const float linearError = 0.0f; Body b1 = BodyA; Body b2 = BodyB; float coordinate1 = 0.0f, coordinate2 = 0.0f; if (_revolute1 != null) { coordinate1 = _revolute1.JointAngle; } else if (_fixedRevolute1 != null) { coordinate1 = _fixedRevolute1.JointAngle; } else if (_prismatic1 != null) { coordinate1 = _prismatic1.JointTranslation; } else if (_fixedPrismatic1 != null) { coordinate1 = _fixedPrismatic1.JointTranslation; } if (_revolute2 != null) { coordinate2 = _revolute2.JointAngle; } else if (_fixedRevolute2 != null) { coordinate2 = _fixedRevolute2.JointAngle; } else if (_prismatic2 != null) { coordinate2 = _prismatic2.JointTranslation; } else if (_fixedPrismatic2 != null) { coordinate2 = _fixedPrismatic2.JointTranslation; } float C = _ant - (coordinate1 + Ratio * coordinate2); float impulse = _mass * (-C); b1.Sweep.C += b1.InvMass * impulse * _J.LinearA; b1.Sweep.A += b1.InvI * impulse * _J.AngularA; b2.Sweep.C += b2.InvMass * impulse * _J.LinearB; b2.Sweep.A += b2.InvI * impulse * _J.AngularB; b1.SynchronizeTransform(); b2.SynchronizeTransform(); // TODO_ERIN not implemented return linearError < Settings.LinearSlop; } } }
using BTDB.FieldHandler; using BTDB.IL; using BTDB.KVDBLayer; using BTDB.ODBLayer; using BTDB.StreamLayer; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Runtime.CompilerServices; using System.Security.Cryptography; using BTDB.Encrypted; namespace BTDB.EventStoreLayer { public delegate object Layer1Loader(ref SpanReader reader, ITypeBinaryDeserializerContext? ctx, ITypeSerializersId2LoaderMapping mapping, ITypeDescriptor descriptor); public delegate void Layer1SimpleSaver(ref SpanWriter writer, object value); public delegate void Layer1ComplexSaver(ref SpanWriter writer, ITypeBinarySerializerContext ctx, object value); public class TypeSerializers : ITypeSerializers { ITypeNameMapper _typeNameMapper; readonly TypeSerializersOptions _options; readonly ConcurrentDictionary<ITypeDescriptor, Layer1Loader> _loaders = new ConcurrentDictionary<ITypeDescriptor, Layer1Loader>(ReferenceEqualityComparer<ITypeDescriptor>.Instance); readonly ConcurrentDictionary<(ITypeDescriptor, Type), Action<object, IDescriptorSerializerLiteContext>> _newDescriptorSavers = new ConcurrentDictionary<(ITypeDescriptor, Type), Action<object, IDescriptorSerializerLiteContext>>(); readonly ConcurrentDictionary<ITypeDescriptor, bool> _descriptorSet = new ConcurrentDictionary<ITypeDescriptor, bool>(ReferenceEqualityComparer<ITypeDescriptor>.Instance); ConcurrentDictionary<Type, ITypeDescriptor> _type2DescriptorMap = new ConcurrentDictionary<Type, ITypeDescriptor>(ReferenceEqualityComparer<Type>.Instance); readonly object _buildTypeLock = new object(); readonly ConcurrentDictionary<(ITypeDescriptor, Type), Layer1SimpleSaver> _simpleSavers = new ConcurrentDictionary<(ITypeDescriptor, Type), Layer1SimpleSaver>(); readonly ConcurrentDictionary<(ITypeDescriptor, Type), Layer1ComplexSaver> _complexSavers = new ConcurrentDictionary<(ITypeDescriptor, Type), Layer1ComplexSaver>(); readonly Func<ITypeDescriptor, Layer1Loader> _loaderFactoryAction; readonly Func<Type, ITypeDescriptor> _buildFromTypeAction; readonly ISymmetricCipher _symmetricCipher; public TypeSerializers(ITypeNameMapper? typeNameMapper = null, TypeSerializersOptions? options = null) { ConvertorGenerator = DefaultTypeConvertorGenerator.Instance; _typeNameMapper = typeNameMapper ?? new FullNameTypeMapper(); ForgotAllTypesAndSerializers(); _loaderFactoryAction = LoaderFactory; _buildFromTypeAction = BuildFromType; _options = options ?? TypeSerializersOptions.Default; _symmetricCipher = _options.SymmetricCipher ?? new InvalidSymmetricCipher(); } public void SetTypeNameMapper(ITypeNameMapper? typeNameMapper) { _typeNameMapper = typeNameMapper ?? new FullNameTypeMapper(); } public ITypeDescriptor? DescriptorOf(object? obj) { if (obj == null) return null; if (obj is IKnowDescriptor knowDescriptor) return knowDescriptor.GetDescriptor(); return DescriptorOf(obj.GetType()); } public bool IsSafeToLoad(Type type) { return DescriptorOf(type) != null; } public ITypeConvertorGenerator ConvertorGenerator { get; private set; } public ITypeNameMapper TypeNameMapper => _typeNameMapper; public ITypeDescriptor? DescriptorOf(Type objType) { var res = _type2DescriptorMap.GetOrAdd(objType, _buildFromTypeAction); if (res != null) _descriptorSet.GetOrAdd(res, true); return res; } ITypeDescriptor? BuildFromType(Type type) { ITypeDescriptor result; lock (_buildTypeLock) { var buildFromTypeCtx = new BuildFromTypeCtx(this, _type2DescriptorMap); buildFromTypeCtx.Create(type); buildFromTypeCtx.MergeTypesByShape(); buildFromTypeCtx.SetNewDescriptors(); result = buildFromTypeCtx.GetFinalDescriptor(type); } return result; } class BuildFromTypeCtx : ITypeDescriptorFactory { readonly TypeSerializers _typeSerializers; readonly ConcurrentDictionary<Type, ITypeDescriptor> _type2DescriptorMap; readonly Dictionary<Type, ITypeDescriptor> _temporaryMap = new Dictionary<Type, ITypeDescriptor>(); readonly Dictionary<ITypeDescriptor, ITypeDescriptor> _remap = new Dictionary<ITypeDescriptor, ITypeDescriptor>(ReferenceEqualityComparer<ITypeDescriptor>.Instance); public BuildFromTypeCtx(TypeSerializers typeSerializers, ConcurrentDictionary<Type, ITypeDescriptor> type2DescriptorMap) { _typeSerializers = typeSerializers; _type2DescriptorMap = type2DescriptorMap; } public ITypeDescriptor? Create(Type type) { if (_type2DescriptorMap.TryGetValue(type, out var result)) return result; if (_temporaryMap.TryGetValue(type, out result)) return result; if (!type.IsSubclassOf(typeof(Delegate))) { if (type.IsGenericType) { var typeAlternative = type.SpecializationOf(typeof(IDictionary<,>)); if (typeAlternative != null) { result = new DictionaryTypeDescriptor(_typeSerializers, type); goto haveDescriptor; } typeAlternative = type.SpecializationOf(typeof(ICollection<>)); if (typeAlternative != null) { result = new ListTypeDescriptor(_typeSerializers, typeAlternative); goto haveDescriptor; } if (_typeSerializers._options.IgnoreIIndirect && type.InheritsOrImplements(typeof(IIndirect<>))) { return null; } if (Nullable.GetUnderlyingType(type) != null) { result = new NullableTypeDescriptor(_typeSerializers, type); goto haveDescriptor; } if (type.InheritsOrImplements(typeof(ITuple))) { result = new TupleTypeDescriptor(_typeSerializers, type); goto haveDescriptor; } result = new ObjectTypeDescriptor(_typeSerializers, type); } else if (type.IsArray) { var typeAlternative = type.SpecializationOf(typeof(ICollection<>)); result = new ListTypeDescriptor(_typeSerializers, typeAlternative!); } else if (type.IsEnum) { result = new EnumTypeDescriptor(_typeSerializers, type); } else if (type.IsValueType) { throw new BTDBException($"Unsupported value type {type.Name}."); } else { result = new ObjectTypeDescriptor(_typeSerializers, type); } } haveDescriptor: _temporaryMap[type] = result; if (result != null) { if (!result.FinishBuildFromType(this)) { _temporaryMap.Remove(type); return null; } } return result; } public void MergeTypesByShape() { foreach (var typeDescriptor in _temporaryMap) { var d = typeDescriptor.Value; foreach (var existingTypeDescriptor in _type2DescriptorMap) { if (d.Equals(existingTypeDescriptor.Value)) { _remap[d] = existingTypeDescriptor.Value; break; } } } foreach (var typeDescriptor in _temporaryMap) { var d = typeDescriptor.Value; d.MapNestedTypes(desc => { if (_remap.TryGetValue(desc, out var res)) return res; return desc; }); } } public ITypeDescriptor? GetFinalDescriptor(Type type) { if (_temporaryMap.TryGetValue(type, out var result)) { if (_remap.TryGetValue(result, out var result2)) return result2; return result; } return null; } public void SetNewDescriptors() { foreach (var typeDescriptor in _temporaryMap) { var d = typeDescriptor.Value; if (_remap.TryGetValue(d, out _)) continue; _type2DescriptorMap.TryAdd(d.GetPreferredType(), d); } } } public void ForgotAllTypesAndSerializers() { _loaders.Clear(); _newDescriptorSavers.Clear(); foreach (var p in _descriptorSet) { p.Key.ClearMappingToType(); } _descriptorSet.Clear(); _type2DescriptorMap = new ConcurrentDictionary<Type, ITypeDescriptor>(EnumDefaultTypes(), ReferenceEqualityComparer<Type>.Instance); } static IEnumerable<KeyValuePair<Type, ITypeDescriptor>> EnumDefaultTypes() { foreach (var predefinedType in BasicSerializersFactory.TypeDescriptors) { yield return new KeyValuePair<Type, ITypeDescriptor>(predefinedType.GetPreferredType(), predefinedType); var descriptorMultipleNativeTypes = predefinedType as ITypeDescriptorMultipleNativeTypes; if (descriptorMultipleNativeTypes == null) continue; foreach (var type in descriptorMultipleNativeTypes.GetNativeTypes()) { yield return new KeyValuePair<Type, ITypeDescriptor>(type, predefinedType); } } } public Layer1Loader GetLoader(ITypeDescriptor descriptor) { return _loaders.GetOrAdd(descriptor, _loaderFactoryAction); } Layer1Loader LoaderFactory(ITypeDescriptor descriptor) { Type loadAsType = null; try { loadAsType = LoadAsType(descriptor); } catch (EventSkippedException) { } var methodBuilder = ILBuilder.Instance.NewMethod<Layer1Loader>("DeserializerFor" + descriptor.Name); var il = methodBuilder.Generator; if (descriptor.AnyOpNeedsCtx()) { var localCtx = il.DeclareLocal(typeof(ITypeBinaryDeserializerContext), "ctx"); var haveCtx = il.DefineLabel(); il .Ldarg(1) .Dup() .Stloc(localCtx) .Brtrue(haveCtx) .Ldarg(2) // ReSharper disable once ObjectCreationAsStatement .Newobj(() => new DeserializerCtx(null)) .Castclass(typeof(ITypeBinaryDeserializerContext)) .Stloc(localCtx) .Mark(haveCtx); if (loadAsType == null) descriptor.GenerateSkip(il, ilGen => ilGen.Ldarg(0), ilGen => ilGen.Ldloc(localCtx)); else descriptor.GenerateLoad(il, ilGen => ilGen.Ldarg(0), ilGen => ilGen.Ldloc(localCtx), ilGen => ilGen.Ldarg(3), loadAsType); } else { if (loadAsType == null) descriptor.GenerateSkip(il, ilGen => ilGen.Ldarg(0), ilGen => ilGen.Ldarg(1)); else descriptor.GenerateLoad(il, ilGen => ilGen.Ldarg(0), ilGen => ilGen.Ldarg(1), ilGen => ilGen.Ldarg(3), loadAsType); } if (loadAsType == null) { il.Ldnull(); } else if (loadAsType.IsValueType) { il.Box(loadAsType); } else if (loadAsType != typeof(object)) { il.Castclass(typeof(object)); } il.Ret(); return methodBuilder.Create(); } public Type LoadAsType(ITypeDescriptor descriptor) { return descriptor.GetPreferredType() ?? NameToType(descriptor.Name!) ?? typeof(object); } public Type LoadAsType(ITypeDescriptor descriptor, Type targetType) { return descriptor.GetPreferredType(targetType) ?? NameToType(descriptor.Name!) ?? typeof(object); } class DeserializerCtx : ITypeBinaryDeserializerContext { readonly ITypeSerializersId2LoaderMapping _mapping; readonly List<object> _backRefs = new List<object>(); public DeserializerCtx(ITypeSerializersId2LoaderMapping mapping) { _mapping = mapping; } public object? LoadObject(ref SpanReader reader) { var typeId = reader.ReadVUInt32(); if (typeId == 0) { return null; } if (typeId == 1) { var backRefId = reader.ReadVUInt32(); return _backRefs[(int)backRefId]; } return _mapping.Load(typeId, ref reader, this); } public void AddBackRef(object obj) { _backRefs.Add(obj); } public void SkipObject(ref SpanReader reader) { var typeId = reader.ReadVUInt32(); if (typeId == 0) { return; } if (typeId == 1) { var backRefId = reader.ReadVUInt32(); if (backRefId > _backRefs.Count) throw new InvalidDataException(); return; } _mapping.Load(typeId, ref reader, this); } public EncryptedString LoadEncryptedString(ref SpanReader reader) { var cipher = _mapping.GetSymmetricCipher(); var enc = reader.ReadByteArray(); var size = cipher!.CalcPlainSizeFor(enc); var dec = new byte[size]; if (!cipher.Decrypt(enc, dec)) { throw new CryptographicException(); } var r = new SpanReader(dec); return r.ReadString(); } public void SkipEncryptedString(ref SpanReader reader) { reader.SkipByteArray(); } } public Layer1SimpleSaver GetSimpleSaver(ITypeDescriptor descriptor, Type type) { return _simpleSavers.GetOrAdd((descriptor, type), NewSimpleSaver); } static Layer1SimpleSaver? NewSimpleSaver((ITypeDescriptor descriptor, Type type) v) { var (descriptor, type) = v; if (descriptor.AnyOpNeedsCtx()) return null; var method = ILBuilder.Instance.NewMethod<Layer1SimpleSaver>(descriptor.Name + "SimpleSaver"); var il = method.Generator; descriptor.GenerateSave(il, ilgen => ilgen.Ldarg(0), null, ilgen => { ilgen.Ldarg(1); if (type != typeof(object)) { ilgen.UnboxAny(type); } }, type); il.Ret(); return method.Create(); } public Layer1ComplexSaver GetComplexSaver(ITypeDescriptor descriptor, Type type) { return _complexSavers.GetOrAdd((descriptor, type), NewComplexSaver); } static Layer1ComplexSaver NewComplexSaver((ITypeDescriptor descriptor, Type type) v) { var (descriptor, type) = v; var method = ILBuilder.Instance.NewMethod<Layer1ComplexSaver>(descriptor.Name + "ComplexSaver"); var il = method.Generator; descriptor.GenerateSave(il, ilgen => ilgen.Ldarg(0), ilgen => ilgen.Ldarg(1), ilgen => { ilgen.Ldarg(2); if (type != typeof(object)) { ilgen.UnboxAny(type); } }, type); il.Ret(); return method.Create(); } public Action<object, IDescriptorSerializerLiteContext>? GetNewDescriptorSaver(ITypeDescriptor descriptor, Type preciseType) { return _newDescriptorSavers.GetOrAdd((descriptor, preciseType), NewDescriptorSaverFactory); } static Action<object, IDescriptorSerializerLiteContext>? NewDescriptorSaverFactory((ITypeDescriptor descriptor, Type type) pair) { var gen = pair.descriptor.BuildNewDescriptorGenerator(); if (gen == null) { return null; } var method = ILBuilder.Instance.NewMethod<Action<object, IDescriptorSerializerLiteContext>>( "GatherAllObjectsForTypeExtraction_" + pair.descriptor.Name); var il = method.Generator; gen.GenerateTypeIterator(il, ilgen => ilgen.Ldarg(0), ilgen => ilgen.Ldarg(1), pair.type); il.Ret(); return method.Create(); } public ITypeSerializersMapping CreateMapping() { return new TypeSerializersMapping(this); } public static void StoreDescriptor(ITypeDescriptor descriptor, ref SpanWriter writer, Func<ITypeDescriptor, uint> descriptor2Id) { switch (descriptor) { case ListTypeDescriptor: writer.WriteUInt8((byte)TypeCategory.List); break; case DictionaryTypeDescriptor: writer.WriteUInt8((byte)TypeCategory.Dictionary); break; case ObjectTypeDescriptor: writer.WriteUInt8((byte)TypeCategory.Class); break; case EnumTypeDescriptor: writer.WriteUInt8((byte)TypeCategory.Enum); break; case NullableTypeDescriptor: writer.WriteUInt8((byte)TypeCategory.Nullable); break; case TupleTypeDescriptor: writer.WriteUInt8((byte)TypeCategory.Tuple); break; default: throw new ArgumentOutOfRangeException(); } ((IPersistTypeDescriptor)descriptor).Persist(ref writer, (ref SpanWriter w, ITypeDescriptor d) => w.WriteVUInt32(descriptor2Id(d))); } public ITypeDescriptor MergeDescriptor(ITypeDescriptor descriptor) { foreach (var (typeDescriptor, _) in _descriptorSet) { if (descriptor.Equals(typeDescriptor)) { return typeDescriptor; } } _descriptorSet.GetOrAdd(descriptor, true); return descriptor; } public string TypeToName(Type type) { return _typeNameMapper.ToName(type); } Type? NameToType(string name) { return _typeNameMapper.ToType(name); } public ISymmetricCipher GetSymmetricCipher() { return _symmetricCipher; } } }
#define SQLITE_ASCII #define SQLITE_DISABLE_LFS #define SQLITE_ENABLE_OVERSIZE_CELL_CHECK #define SQLITE_MUTEX_OMIT #define SQLITE_OMIT_AUTHORIZATION #define SQLITE_OMIT_DEPRECATED #define SQLITE_OMIT_GET_TABLE #define SQLITE_OMIT_INCRBLOB #define SQLITE_OMIT_LOOKASIDE #define SQLITE_OMIT_SHARED_CACHE #define SQLITE_OMIT_UTF16 #define SQLITE_OMIT_WAL #define SQLITE_OS_WIN #define SQLITE_SYSTEM_MALLOC #define VDBE_PROFILE_OFF #define WINDOWS_MOBILE #define NDEBUG #define _MSC_VER #define YYFALLBACK using System.Diagnostics; namespace Community.CsharpSqlite { using u8 = System.Byte; public partial class Sqlite3 { /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** An tokenizer for SQL ** ** This file contains C code that implements the sqlite3_complete() API. ** This code used to be part of the tokenizer.c source file. But by ** separating it out, the code will be automatically omitted from ** static links that do not use it. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 ** ************************************************************************* */ //#include "sqliteInt.h" #if !SQLITE_OMIT_COMPLETE /* ** This is defined in tokenize.c. We just have to import the definition. */ #if !SQLITE_AMALGAMATION #if SQLITE_ASCII //#define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0) static bool IdChar( u8 C ) { return ( sqlite3CtypeMap[(char)C] & 0x46 ) != 0; } #endif //#if SQLITE_EBCDIC //extern const char sqlite3IsEbcdicIdChar[]; //#define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40])) //#endif #endif // * SQLITE_AMALGAMATION */ /* ** Token types used by the sqlite3_complete() routine. See the header ** comments on that procedure for additional information. */ const int tkSEMI = 0; const int tkWS = 1; const int tkOTHER = 2; #if !SQLITE_OMIT_TRIGGER const int tkEXPLAIN = 3; const int tkCREATE = 4; const int tkTEMP = 5; const int tkTRIGGER = 6; const int tkEND = 7; #endif /* ** Return TRUE if the given SQL string ends in a semicolon. ** ** Special handling is require for CREATE TRIGGER statements. ** Whenever the CREATE TRIGGER keywords are seen, the statement ** must end with ";END;". ** ** This implementation uses a state machine with 8 states: ** ** (0) INVALID We have not yet seen a non-whitespace character. ** ** (1) START At the beginning or end of an SQL statement. This routine ** returns 1 if it ends in the START state and 0 if it ends ** in any other state. ** ** (2) NORMAL We are in the middle of statement which ends with a single ** semicolon. ** ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of ** a statement. ** ** (4) CREATE The keyword CREATE has been seen at the beginning of a ** statement, possibly preceeded by EXPLAIN and/or followed by ** TEMP or TEMPORARY ** ** (5) TRIGGER We are in the middle of a trigger definition that must be ** ended by a semicolon, the keyword END, and another semicolon. ** ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at ** the end of a trigger definition. ** ** (7) END We've seen the ";END" of the ";END;" that occurs at the end ** of a trigger difinition. ** ** Transitions between states above are determined by tokens extracted ** from the input. The following tokens are significant: ** ** (0) tkSEMI A semicolon. ** (1) tkWS Whitespace. ** (2) tkOTHER Any other SQL token. ** (3) tkEXPLAIN The "explain" keyword. ** (4) tkCREATE The "create" keyword. ** (5) tkTEMP The "temp" or "temporary" keyword. ** (6) tkTRIGGER The "trigger" keyword. ** (7) tkEND The "end" keyword. ** ** Whitespace never causes a state transition and is always ignored. ** This means that a SQL string of all whitespace is invalid. ** ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed ** to recognize the end of a trigger can be omitted. All we have to do ** is look for a semicolon that is not part of an string or comment. */ static public int sqlite3_complete( string zSql ) { int state = 0; /* Current state, using numbers defined in header comment */ int token; /* Value of the next token */ #if !SQLITE_OMIT_TRIGGER /* A complex statement machine used to detect the end of a CREATE TRIGGER ** statement. This is the normal case. */ u8[][] trans = new u8[][] { /* Token: */ /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */ /* 0 INVALID: */ new u8[]{ 1, 0, 2, 3, 4, 2, 2, 2, }, /* 1 START: */ new u8[]{ 1, 1, 2, 3, 4, 2, 2, 2, }, /* 2 NORMAL: */ new u8[]{ 1, 2, 2, 2, 2, 2, 2, 2, }, /* 3 EXPLAIN: */ new u8[]{ 1, 3, 3, 2, 4, 2, 2, 2, }, /* 4 CREATE: */ new u8[]{ 1, 4, 2, 2, 2, 4, 5, 2, }, /* 5 TRIGGER: */ new u8[]{ 6, 5, 5, 5, 5, 5, 5, 5, }, /* 6 SEMI: */ new u8[]{ 6, 6, 5, 5, 5, 5, 5, 7, }, /* 7 END: */ new u8[]{ 1, 7, 5, 5, 5, 5, 5, 5, }, }; #else /* If triggers are not supported by this compile then the statement machine ** used to detect the end of a statement is much simplier */ u8[][] trans = new u8[][] { /* Token: */ /* State: ** SEMI WS OTHER */ /* 0 INVALID: */new u8[] { 1, 0, 2, }, /* 1 START: */new u8[] { 1, 1, 2, }, /* 2 NORMAL: */new u8[] { 1, 2, 2, }, }; #endif // * SQLITE_OMIT_TRIGGER */ int zIdx = 0; while ( zIdx < zSql.Length ) { switch ( zSql[zIdx] ) { case ';': { /* A semicolon */ token = tkSEMI; break; } case ' ': case '\r': case '\t': case '\n': case '\f': { /* White space is ignored */ token = tkWS; break; } case '/': { /* C-style comments */ if ( zSql[zIdx + 1] != '*' ) { token = tkOTHER; break; } zIdx += 2; while ( zIdx < zSql.Length && zSql[zIdx] != '*' || zIdx < zSql.Length - 1 && zSql[zIdx + 1] != '/' ) { zIdx++; } if ( zIdx == zSql.Length ) return 0; zIdx++; token = tkWS; break; } case '-': { /* SQL-style comments from "--" to end of line */ if ( zSql[zIdx + 1] != '-' ) { token = tkOTHER; break; } while ( zIdx < zSql.Length && zSql[zIdx] != '\n' ) { zIdx++; } if ( zIdx == zSql.Length ) return state == 1 ? 1 : 0;//if( *zSql==0 ) return state==1; token = tkWS; break; } case '[': { /* Microsoft-style identifiers in [...] */ zIdx++; while ( zIdx < zSql.Length && zSql[zIdx] != ']' ) { zIdx++; } if ( zIdx == zSql.Length ) return 0; token = tkOTHER; break; } case '`': /* Grave-accent quoted symbols used by MySQL */ case '"': /* single- and double-quoted strings */ case '\'': { int c = zSql[zIdx]; zIdx++; while ( zIdx < zSql.Length && zSql[zIdx] != c ) { zIdx++; } if ( zIdx == zSql.Length ) return 0; token = tkOTHER; break; } default: { //#if SQLITE_EBCDIC // unsigned char c; //#endif if ( IdChar( (u8)zSql[zIdx] ) ) { /* Keywords and unquoted identifiers */ int nId; for ( nId = 1; ( zIdx + nId ) < zSql.Length && IdChar( (u8)zSql[zIdx + nId] ); nId++ ) { } #if SQLITE_OMIT_TRIGGER token = tkOTHER; #else switch ( zSql[zIdx] ) { case 'c': case 'C': { if ( nId == 6 && sqlite3StrNICmp( zSql, zIdx, "create", 6 ) == 0 ) { token = tkCREATE; } else { token = tkOTHER; } break; } case 't': case 'T': { if ( nId == 7 && sqlite3StrNICmp( zSql, zIdx, "trigger", 7 ) == 0 ) { token = tkTRIGGER; } else if ( nId == 4 && sqlite3StrNICmp( zSql, zIdx, "temp", 4 ) == 0 ) { token = tkTEMP; } else if ( nId == 9 && sqlite3StrNICmp( zSql, zIdx, "temporary", 9 ) == 0 ) { token = tkTEMP; } else { token = tkOTHER; } break; } case 'e': case 'E': { if ( nId == 3 && sqlite3StrNICmp( zSql, zIdx, "end", 3 ) == 0 ) { token = tkEND; } else #if !SQLITE_OMIT_EXPLAIN if ( nId == 7 && sqlite3StrNICmp( zSql, zIdx, "explain", 7 ) == 0 ) { token = tkEXPLAIN; } else #endif { token = tkOTHER; } break; } default: { token = tkOTHER; break; } } #endif // * SQLITE_OMIT_TRIGGER */ zIdx += nId - 1; } else { /* Operators and special symbols */ token = tkOTHER; } break; } } state = trans[state][token]; zIdx++; } return ( state == 1 ) ? 1 : 0;//return state==1; } #if !SQLITE_OMIT_UTF16 /* ** This routine is the same as the sqlite3_complete() routine described ** above, except that the parameter is required to be UTF-16 encoded, not ** UTF-8. */ int sqlite3_complete16(const void *zSql){ sqlite3_value pVal; char const *zSql8; int rc = SQLITE_NOMEM; #if !SQLITE_OMIT_AUTOINIT rc = sqlite3_initialize(); if( rc !=0) return rc; #endif pVal = sqlite3ValueNew(0); sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC); zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8); if( zSql8 ){ rc = sqlite3_complete(zSql8); }else{ rc = SQLITE_NOMEM; } sqlite3ValueFree(pVal); return sqlite3ApiExit(0, rc); } #endif // * SQLITE_OMIT_UTF16 */ #endif // * SQLITE_OMIT_COMPLETE */ } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Build.Framework; using Microsoft.Build.Tasks; using Microsoft.Build.UnitTests; using Microsoft.Build.Utilities; using Microsoft.Build.Shared; using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; using System.IO; using System.Text.RegularExpressions; using System.Text; using System.Xml.Xsl; using System.Xml; using Xunit; namespace Microsoft.Build.UnitTests { #if !MONO /// <summary> /// These tests run. The temporary output folder for this test is Path.Combine(Path.GetTempPath(), DateTime.Now.Ticks.ToString()) /// 1. When combination of (xml, xmlfile) x (xsl, xslfile). /// 2. When Xsl parameters are missing. /// 3. When Xml parameters are missing. /// 4. Both missing. /// 5. Too many Xml parameters. /// 6. Too many Xsl parameters. /// 7. Setting Out parameter to file. /// 8. Setting Out parameter to screen. /// 9. Setting correct "Parameter" parameters for Xsl. /// 10. Setting the combination of "Parameter" parameters (Name, Namespace, Value) and testing the cases when they should run ok. /// 11. Setting "Parameter" parameter as empty string (should run OK). /// 12. Compiled Dll with type information. /// 13. Compiled Dll without type information. /// 14. Load Xslt with incorrect character as CNAME (load exception). /// 15. Missing XmlFile file. /// 16. Missing XslFile file. /// 17. Missing XsltCompiledDll file. /// 18. Bad XML on "Parameter" parameter. /// 19. Out parameter pointing to nonexistent location (K:\folder\file.xml) /// 20. XslDocument that throws runtime exception. /// 21. Passing a dll that has two types to XsltCompiledDll parameter without specifying a type. /// </summary> sealed public class XslTransformation_Tests { /// <summary> /// The "surround" regex. /// </summary> private readonly Regex _surroundMatch = new Regex("surround", RegexOptions.Multiline | RegexOptions.Compiled); /// <summary> /// The contents of xmldocument for tests. /// </summary> private readonly string _xmlDocument = "<root Name=\"param1\" Value=\"value111\"><abc><cde/></abc></root>"; /// <summary> /// The contents of another xmldocument for tests. /// </summary> private readonly string _xmlDocument2 = "<root></root>"; /// <summary> /// The contents of xsl document for tests. /// </summary> private readonly string _xslDocument = "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns:msxsl=\"urn:schemas-microsoft-com:xslt\" exclude-result-prefixes=\"msxsl\"><xsl:output method=\"xml\" indent=\"yes\"/><xsl:template match=\"@* | node()\"><surround><xsl:copy><xsl:apply-templates select=\"@* | node()\"/></xsl:copy></surround></xsl:template></xsl:stylesheet>"; #if FEATURE_COMPILED_XSL /// <summary> /// The contents of another xsl document for tests /// </summary> private readonly string _xslDocument2 = "<?xml version = \"1.0\" ?><xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"><xsl:template match = \"myInclude\"><xsl:apply-templates select = \"document(@path)\"/></xsl:template><xsl:template match = \"@*|node()\"><xsl:copy><xsl:apply-templates select = \"@*|node()\"/></xsl:copy></xsl:template></xsl:stylesheet>"; #endif /// <summary> /// The contents of xslparameters for tests. /// </summary> private readonly string _xslParameters = "<Parameter Name=\"param1\" Value=\"1\" /><Parameter Name=\"param2\" Namespace=\"http://eksiduyuru.com\" Value=\"2\" />"; /// <summary> /// The contents of xslt file for testing parameters. /// </summary> private readonly string _xslParameterDocument = "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns:msxsl=\"urn:schemas-microsoft-com:xslt\" exclude-result-prefixes=\"msxsl\" xmlns:myns=\"http://eksiduyuru.com\"><xsl:output method=\"xml\" indent=\"yes\"/><xsl:param name=\"param1\" /><xsl:param name=\"myns:param2\" /><xsl:template match=\"/\"><values>param 1: <xsl:value-of select=\"$param1\" />param 2: <xsl:value-of select=\"$myns:param2\" /></values></xsl:template></xsl:stylesheet>"; /// <summary> /// The errorious xsl documents /// </summary> private readonly string _errorXslDocument = "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns:msxsl=\"urn:schemas-microsoft-com:xslt\"><xsl:template match=\"/\"><xsl:element name=\"$a\"></xsl:element></xsl:template></xsl:stylesheet>"; /// <summary> /// The errorious xsl document 2. /// </summary> private readonly string _errorXslDocument2 = "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns:msxsl=\"urn:schemas-microsoft-com:xslt\" exclude-result-prefixes=\"msxsl\"><xsl:template match=\"/\"><xsl:message terminate=\"yes\">error?</xsl:message></xsl:template></xsl:stylesheet>"; /// <summary> /// When combination of (xml, xmlfile) x (xsl, xslfile). /// </summary> [Fact] public void XmlXslParameters() { string dir; TaskItem[] outputPaths; List<KeyValuePair<XslTransformation.XmlInput.XmlModes, object>> xmlInputs; List<KeyValuePair<XslTransformation.XsltInput.XslModes, object>> xslInputs; MockEngine engine; Prepare(out dir, out _, out _, out _, out outputPaths, out xmlInputs, out xslInputs, out engine); // Test when Xml and Xsl parameters are correct for (int xmi = 0; xmi < xmlInputs.Count; xmi++) { for (int xsi = 0; xsi < xslInputs.Count; xsi++) { XslTransformation t = new XslTransformation(); t.BuildEngine = engine; t.OutputPaths = outputPaths; XslTransformation.XmlInput.XmlModes xmlKey = xmlInputs[xmi].Key; object xmlValue = xmlInputs[xmi].Value; XslTransformation.XsltInput.XslModes xslKey = xslInputs[xsi].Key; object xslValue = xslInputs[xsi].Value; switch (xmlKey) { case XslTransformation.XmlInput.XmlModes.Xml: t.XmlContent = (string)xmlValue; break; case XslTransformation.XmlInput.XmlModes.XmlFile: t.XmlInputPaths = (TaskItem[])xmlValue; break; default: Assert.True(false, "Test error"); break; } switch (xslKey) { case XslTransformation.XsltInput.XslModes.Xslt: t.XslContent = (string)xslValue; break; case XslTransformation.XsltInput.XslModes.XsltFile: t.XslInputPath = (TaskItem)xslValue; break; case XslTransformation.XsltInput.XslModes.XsltCompiledDll: t.XslCompiledDllPath = (TaskItem)xslValue; break; default: Assert.True(false, "Test error"); break; } Assert.True(t.Execute()); // "The test should have passed at the both params correct test" } } CleanUp(dir); } /// <summary> /// When Xsl parameters are missing. /// </summary> [Fact] public void MissingXslParameter() { string dir; TaskItem[] xmlPaths; TaskItem xslPath; TaskItem xslCompiledPath; TaskItem[] outputPaths; List<KeyValuePair<XslTransformation.XmlInput.XmlModes, object>> xmlInputs; List<KeyValuePair<XslTransformation.XsltInput.XslModes, object>> xslInputs; MockEngine engine; Prepare(out dir, out xmlPaths, out xslPath, out xslCompiledPath, out outputPaths, out xmlInputs, out xslInputs, out engine); // test Xsl missing. for (int xmi = 0; xmi < xmlInputs.Count; xmi++) { XslTransformation t = new XslTransformation(); t.BuildEngine = engine; t.OutputPaths = outputPaths; XslTransformation.XmlInput.XmlModes xmlKey = xmlInputs[xmi].Key; object xmlValue = xmlInputs[xmi].Value; switch (xmlKey) { case XslTransformation.XmlInput.XmlModes.Xml: t.XmlContent = (string)xmlValue; break; case XslTransformation.XmlInput.XmlModes.XmlFile: t.XmlInputPaths = (TaskItem[])xmlValue; break; default: Assert.True(false, "Test error"); break; } Assert.False(t.Execute()); // "The test should fail when there is missing Xsl params" Console.WriteLine(engine.Log); Assert.Contains("MSB3701", engine.Log); // "The output should contain MSB3701 error message at missing Xsl params test" } CleanUp(dir); } /// <summary> /// When Xml parameters are missing. /// </summary> [Fact] public void MissingXmlParameter() { string dir; TaskItem[] xmlPaths; TaskItem xslPath; TaskItem xslCompiledPath; TaskItem[] outputPaths; List<KeyValuePair<XslTransformation.XmlInput.XmlModes, object>> xmlInputs; List<KeyValuePair<XslTransformation.XsltInput.XslModes, object>> xslInputs; MockEngine engine; Prepare(out dir, out xmlPaths, out xslPath, out xslCompiledPath, out outputPaths, out xmlInputs, out xslInputs, out engine); // Test Xml missing. for (int xsi = 0; xsi < xslInputs.Count; xsi++) { XslTransformation t = new XslTransformation(); t.BuildEngine = engine; t.OutputPaths = outputPaths; XslTransformation.XsltInput.XslModes xslKey = xslInputs[xsi].Key; object xslValue = xslInputs[xsi].Value; switch (xslKey) { case XslTransformation.XsltInput.XslModes.Xslt: t.XslContent = (string)xslValue; break; case XslTransformation.XsltInput.XslModes.XsltFile: t.XslInputPath = (TaskItem)xslValue; break; case XslTransformation.XsltInput.XslModes.XsltCompiledDll: t.XslCompiledDllPath = (TaskItem)xslValue; break; default: Assert.True(false, "Test error"); break; } Assert.False(t.Execute()); // "The test should fail when there is missing Xml params" Console.WriteLine(engine.Log); Assert.Contains("MSB3701", engine.Log); // "The output should contain MSB3701 error message at missing Xml params test" engine.Log = ""; } CleanUp(dir); } /// <summary> /// Both missing. /// </summary> [Fact] public void MissingXmlXslParameter() { string dir; TaskItem[] xmlPaths; TaskItem xslPath; TaskItem xslCompiledPath; TaskItem[] outputPaths; List<KeyValuePair<XslTransformation.XmlInput.XmlModes, object>> xmlInputs; List<KeyValuePair<XslTransformation.XsltInput.XslModes, object>> xslInputs; MockEngine engine; Prepare(out dir, out xmlPaths, out xslPath, out xslCompiledPath, out outputPaths, out xmlInputs, out xslInputs, out engine); // Test both missing. { XslTransformation t = new XslTransformation(); t.BuildEngine = engine; t.OutputPaths = outputPaths; Assert.False(t.Execute()); // "The test should fail when there is no params" Console.WriteLine(engine.Log); Assert.Contains("MSB3701", engine.Log); // "The output should contain MSB3701 error message" } CleanUp(dir); } /// <summary> /// Too many Xml parameters. /// </summary> [Fact] public void ManyXmlParameters() { string dir; TaskItem[] xmlPaths; TaskItem xslPath; TaskItem xslCompiledPath; TaskItem[] outputPaths; List<KeyValuePair<XslTransformation.XmlInput.XmlModes, object>> xmlInputs; List<KeyValuePair<XslTransformation.XsltInput.XslModes, object>> xslInputs; MockEngine engine; Prepare(out dir, out xmlPaths, out xslPath, out xslCompiledPath, out outputPaths, out xmlInputs, out xslInputs, out engine); // Test too many Xml. { XslTransformation t = new XslTransformation(); t.BuildEngine = engine; t.OutputPaths = outputPaths; t.XmlContent = _xmlDocument; t.XmlInputPaths = xmlPaths; t.XslContent = _xslDocument; Assert.Equal(_xmlDocument, t.XmlContent); Assert.Equal(xmlPaths, t.XmlInputPaths); Assert.False(t.Execute()); // "The test should fail when there are too many files" Console.WriteLine(engine.Log); Assert.Contains("MSB3701", engine.Log); } CleanUp(dir); } /// <summary> /// Too many Xsl parameters. /// </summary> [Fact] public void ManyXslParameters() { string dir; TaskItem[] xmlPaths; TaskItem xslPath; TaskItem xslCompiledPath; TaskItem[] outputPaths; List<KeyValuePair<XslTransformation.XmlInput.XmlModes, object>> xmlInputs; List<KeyValuePair<XslTransformation.XsltInput.XslModes, object>> xslInputs; MockEngine engine; Prepare(out dir, out xmlPaths, out xslPath, out xslCompiledPath, out outputPaths, out xmlInputs, out xslInputs, out engine); // Test too many Xsl. { XslTransformation t = new XslTransformation(); t.BuildEngine = engine; t.OutputPaths = outputPaths; t.XmlContent = _xmlDocument; t.XslContent = _xslDocument; t.XslInputPath = xslPath; Assert.Equal(_xslDocument, t.XslContent); Assert.Equal(xslPath, t.XslInputPath); Assert.False(t.Execute()); // "The test should fail when there are too many files" Console.WriteLine(engine.Log); Assert.Contains("MSB3701", engine.Log); // "The output should contain MSB3701 error message at no params test" } CleanUp(dir); } /// <summary> /// Test out parameter. /// </summary> [Fact] public void OutputTest() { string dir; TaskItem[] xmlPaths; TaskItem xslPath; TaskItem xslCompiledPath; TaskItem[] outputPaths; List<KeyValuePair<XslTransformation.XmlInput.XmlModes, object>> xmlInputs; List<KeyValuePair<XslTransformation.XsltInput.XslModes, object>> xslInputs; MockEngine engine; Prepare(out dir, out xmlPaths, out xslPath, out xslCompiledPath, out outputPaths, out xmlInputs, out xslInputs, out engine); // Test Out { XslTransformation t = new XslTransformation(); t.BuildEngine = engine; t.XmlContent = _xmlDocument; t.XslContent = _xslDocument; t.OutputPaths = outputPaths; Assert.True(t.Execute()); // "Test out should have given true when executed" Assert.Equal(String.Empty, engine.Log); // "The log should be empty" Console.WriteLine(engine.Log); using (StreamReader sr = new StreamReader(t.OutputPaths[0].ItemSpec)) { string fileContents = sr.ReadToEnd(); MatchCollection mc = _surroundMatch.Matches(fileContents); Assert.Equal(8, mc.Count); // "The file test doesn't match" } } CleanUp(dir); } /// <summary> /// Setting correct "Parameter" parameters for Xsl. /// </summary> [Fact] public void XsltParamatersCorrect() { string dir; TaskItem[] xmlPaths; TaskItem xslPath; TaskItem xslCompiledPath; TaskItem[] outputPaths; List<KeyValuePair<XslTransformation.XmlInput.XmlModes, object>> xmlInputs; List<KeyValuePair<XslTransformation.XsltInput.XslModes, object>> xslInputs; MockEngine engine; Prepare(out dir, out xmlPaths, out xslPath, out xslCompiledPath, out outputPaths, out xmlInputs, out xslInputs, out engine); // Test Correct Xslt Parameters { XslTransformation t = new XslTransformation(); t.BuildEngine = engine; t.OutputPaths = outputPaths; t.XmlContent = _xmlDocument; t.XslContent = _xslParameterDocument; t.Parameters = _xslParameters; t.Execute(); Console.WriteLine(engine.Log); using (StreamReader sr = new StreamReader(t.OutputPaths[0].ItemSpec)) { string fileContents = sr.ReadToEnd(); Assert.Contains("param 1: 1param 2: 2", fileContents); } } CleanUp(dir); } /// <summary> /// Setting the combination of "Parameter" parameters (Name, Namespace, Value) and testing the cases when they should run ok. /// </summary> [Fact] public void XsltParametersIncorrect() { string dir; TaskItem[] xmlPaths; TaskItem xslPath; TaskItem xslCompiledPath; TaskItem[] outputPaths; List<KeyValuePair<XslTransformation.XmlInput.XmlModes, object>> xmlInputs; List<KeyValuePair<XslTransformation.XsltInput.XslModes, object>> xslInputs; MockEngine engine; Prepare(out dir, out xmlPaths, out xslPath, out xslCompiledPath, out outputPaths, out xmlInputs, out xslInputs, out engine); // Test Xslt Parameters { string[] attrs = new string[] { "Name=\"param2\"", "Namespace=\"http://eksiduyuru.com\"", "Value=\"2\"" }; for (int i = 0; i < Math.Pow(2, attrs.Length); i++) { string res = ""; for (int k = 0; k < attrs.Length; k++) { if ((i & (int)Math.Pow(2, k)) != 0) { res += attrs[k] + " "; } } XslTransformation t = new XslTransformation(); t.BuildEngine = engine; t.OutputPaths = outputPaths; t.XmlContent = _xmlDocument; t.XslContent = _xslParameterDocument; t.Parameters = "<Parameter " + res + "/>"; Assert.Equal("<Parameter " + res + "/>", t.Parameters); bool result = t.Execute(); Console.WriteLine(engine.Log); if (i == 5 || i == 7) { Assert.True(result); // "Only 5th and 7th values should pass." } else { Assert.False(result); // "Only 5th and 7th values should pass." } } } CleanUp(dir); } /// <summary> /// Setting "Parameter" parameter as empty string (should run OK). /// </summary> [Fact] public void EmptyParameters() { string dir; TaskItem[] xmlPaths; TaskItem xslPath; TaskItem xslCompiledPath; TaskItem[] outputPaths; List<KeyValuePair<XslTransformation.XmlInput.XmlModes, object>> xmlInputs; List<KeyValuePair<XslTransformation.XsltInput.XslModes, object>> xslInputs; MockEngine engine; Prepare(out dir, out xmlPaths, out xslPath, out xslCompiledPath, out outputPaths, out xmlInputs, out xslInputs, out engine); // load empty parameters { XslTransformation t = new XslTransformation(); t.BuildEngine = engine; t.OutputPaths = outputPaths; t.XmlInputPaths = xmlPaths; t.XslInputPath = xslPath; t.Parameters = " "; Assert.True(t.Execute()); // "This test should've passed (empty parameters)." Console.WriteLine(engine.Log); } CleanUp(dir); } #if FEATURE_COMPILED_XSL /// <summary> /// Compiled Dll with type information. /// </summary> [Fact] public void CompiledDllWithType() { string dir; TaskItem xslCompiledPath; TaskItem[] outputPaths; MockEngine engine; Prepare(out dir, out _, out _, out xslCompiledPath, out outputPaths, out _, out _, out engine); // Test Compiled DLLs // with type specified. { XslTransformation t = new XslTransformation(); t.BuildEngine = engine; t.OutputPaths = outputPaths; t.XmlContent = _xmlDocument; xslCompiledPath.ItemSpec = xslCompiledPath.ItemSpec + ";xslt"; t.XslCompiledDllPath = xslCompiledPath; Assert.Equal(xslCompiledPath.ItemSpec, t.XslCompiledDllPath.ItemSpec); Assert.True(t.Execute()); // "XsltComiledDll1 execution should've passed" Console.WriteLine(engine.Log); Assert.DoesNotContain("MSB", engine.Log); // "The log should not contain any errors. (XsltComiledDll1)" } CleanUp(dir); } /// <summary> /// Compiled Dll without type information. /// </summary> [Fact] public void CompiledDllWithoutType() { string dir; TaskItem xslCompiledPath; TaskItem[] outputPaths; MockEngine engine; Prepare(out dir, out _, out _, out xslCompiledPath, out outputPaths, out _, out _, out engine); // without type specified. { XslTransformation t = new XslTransformation(); t.BuildEngine = engine; t.OutputPaths = outputPaths; t.XmlContent = _xmlDocument; t.XslCompiledDllPath = xslCompiledPath; Assert.True(t.Execute(), "XsltComiledDll2 execution should've passed" + engine.Log); Console.WriteLine(engine.Log); Assert.False(engine.MockLogger.ErrorCount > 0); // "The log should not contain any errors. (XsltComiledDll2)" } CleanUp(dir); } #endif /// <summary> /// Load Xslt with incorrect character as CNAME (load exception). /// </summary> [Fact] public void BadXsltFile() { string dir; TaskItem[] outputPaths; MockEngine engine; Prepare(out dir, out _, out _, out _, out outputPaths, out _, out _, out engine); // load bad xslt { XslTransformation t = new XslTransformation(); t.BuildEngine = engine; t.OutputPaths = outputPaths; t.XmlContent = _xmlDocument; t.XslContent = _errorXslDocument; try { t.Execute(); Console.WriteLine(engine.Log); } catch (Exception e) { Assert.Contains("The '$' character", e.Message); } } CleanUp(dir); } /// <summary> /// Load Xslt with incorrect character as CNAME (load exception). /// </summary> [Fact] public void MissingOutputFile() { Assert.Throws<System.ArgumentNullException>(() => { string dir; TaskItem[] xmlPaths; TaskItem xslPath; TaskItem xslCompiledPath; TaskItem[] outputPaths; List<KeyValuePair<XslTransformation.XmlInput.XmlModes, object>> xmlInputs; List<KeyValuePair<XslTransformation.XsltInput.XslModes, object>> xslInputs; MockEngine engine; Prepare(out dir, out xmlPaths, out xslPath, out xslCompiledPath, out outputPaths, out xmlInputs, out xslInputs, out engine); // load missing xml { XslTransformation t = new XslTransformation(); t.BuildEngine = engine; t.XmlInputPaths = xmlPaths; t.XslInputPath = xslPath; Assert.False(t.Execute()); // "This test should've failed (no output)." Console.WriteLine(engine.Log); } CleanUp(dir); } ); } /// <summary> /// Missing XmlFile file. /// </summary> [Fact] public void MissingXmlFile() { string dir; TaskItem[] xmlPaths; TaskItem xslPath; TaskItem[] outputPaths; MockEngine engine; Prepare(out dir, out xmlPaths, out xslPath, out _, out outputPaths, out _, out _, out engine); // load missing xml { XslTransformation t = new XslTransformation(); t.BuildEngine = engine; t.OutputPaths = outputPaths; xmlPaths[0].ItemSpec = xmlPaths[0].ItemSpec + "bad"; t.XmlInputPaths = xmlPaths; t.XslInputPath = xslPath; Console.WriteLine(engine.Log); Assert.False(t.Execute()); // "This test should've failed (bad xml)." Assert.Contains("MSB3703", engine.Log); } CleanUp(dir); } /// <summary> /// Missing XslFile file. /// </summary> [Fact] public void MissingXsltFile() { string dir; TaskItem[] xmlPaths; TaskItem xslPath; TaskItem[] outputPaths; MockEngine engine; Prepare(out dir, out xmlPaths, out xslPath, out _, out outputPaths, out _, out _, out engine); // load missing xsl { XslTransformation t = new XslTransformation(); t.BuildEngine = engine; t.OutputPaths = outputPaths; t.XmlInputPaths = xmlPaths; xslPath.ItemSpec = xslPath.ItemSpec + "bad"; t.XslInputPath = xslPath; Assert.False(t.Execute()); // "This test should've failed (bad xslt)." Console.WriteLine(engine.Log); Assert.Contains("MSB3704", engine.Log); } CleanUp(dir); } #if FEATURE_COMPILED_XSL /// <summary> /// Missing XsltCompiledDll file. /// </summary> [Fact] public void MissingCompiledDllFile() { string dir; TaskItem xslCompiledPath; TaskItem[] outputPaths; MockEngine engine; Prepare(out dir, out _, out _, out xslCompiledPath, out outputPaths, out _, out _, out engine); // missing xsltCompiledDll { XslTransformation t = new XslTransformation(); t.BuildEngine = engine; t.OutputPaths = outputPaths; t.XmlContent = _xmlDocument; xslCompiledPath.ItemSpec = xslCompiledPath.ItemSpec + "bad;xslt"; t.XslCompiledDllPath = xslCompiledPath; Assert.False(t.Execute()); // "XsltComiledDllBad execution should've failed" Console.WriteLine(engine.Log); Assert.Contains("MSB3704", engine.Log); } CleanUp(dir); } #endif /// <summary> /// Bad XML on "Parameter" parameter. /// </summary> [Fact] public void BadXmlAsParameter() { string dir; TaskItem[] outputPaths; MockEngine engine; Prepare(out dir, out _, out _, out _, out outputPaths, out _, out _, out engine); // load bad xml on parameters { XslTransformation t = new XslTransformation(); t.BuildEngine = engine; t.OutputPaths = outputPaths; t.XmlContent = _xmlDocument; t.XslContent = _xslParameterDocument; t.Parameters = "<<>>"; try { Assert.False(t.Execute()); // "This test should've failed (bad params1)." Console.WriteLine(engine.Log); } catch (Exception e) { Assert.Contains("'<'", e.Message); } } CleanUp(dir); } /// <summary> /// Out parameter pointing to nonexistent location (K:\folder\file.xml) /// </summary> [Fact] public void OutputFileCannotBeWritten() { string dir; TaskItem[] outputPaths; MockEngine engine; Prepare(out dir, out _, out _, out _, out outputPaths, out _, out _, out engine); // load bad output { XslTransformation t = new XslTransformation(); t.BuildEngine = engine; t.OutputPaths = outputPaths; t.XmlContent = _xmlDocument; t.XslContent = _xslDocument; t.OutputPaths = new TaskItem[] { new TaskItem("k:\\folder\\file.xml") }; try { Assert.False(t.Execute()); // "This test should've failed (bad output)." Console.WriteLine(engine.Log); } catch (Exception e) { Assert.Contains("MSB3701", e.Message); } } CleanUp(dir); } /// <summary> /// XslDocument that throws runtime exception. /// </summary> [Fact] public void XsltDocumentThrowsError() { string dir; TaskItem[] outputPaths; MockEngine engine; Prepare(out dir, out _, out _, out _, out outputPaths, out _, out _, out engine); // load error xslDocument { XslTransformation t = new XslTransformation(); t.BuildEngine = engine; t.OutputPaths = outputPaths; t.XmlContent = _xmlDocument; t.XslContent = _errorXslDocument2; try { Assert.False(t.Execute()); // "This test should've failed (xsl with error)." Console.WriteLine(engine.Log); } catch (Exception e) { Assert.Contains("error?", e.Message); } } CleanUp(dir); } #if FEATURE_COMPILED_XSL /// <summary> /// Passing a dll that has two types to XsltCompiledDll parameter without specifying a type. /// </summary> [Fact] public void CompiledDllWithTwoTypes() { string dir; TaskItem[] outputPaths; MockEngine engine; Prepare(out dir, out _, out _, out _, out outputPaths, out _, out _, out engine); // doubletype string doubleTypePath = Path.Combine(dir, "double.dll"); CompileDoubleType(doubleTypePath); { XslTransformation t = new XslTransformation(); t.BuildEngine = engine; t.OutputPaths = outputPaths; t.XmlContent = _xmlDocument; t.XslCompiledDllPath = new TaskItem(doubleTypePath); try { t.Execute(); Console.WriteLine(engine.Log); } catch (Exception e) { Assert.Contains("error?", e.Message); } System.Diagnostics.Debug.WriteLine(engine.Log); } CleanUp(dir); } #endif /// <summary> /// Matching XmlInputPaths and OutputPaths /// </summary> [Fact] public void MultipleXmlInputs_Matching() { string dir; TaskItem[] xmlPaths; TaskItem xslPath; TaskItem[] outputPaths; MockEngine engine; Prepare(out dir, out xmlPaths, out xslPath, out _, out outputPaths, out _, out _, out engine); var otherXmlPath = new TaskItem(Path.Combine(dir, Guid.NewGuid().ToString())); using (StreamWriter sw = new StreamWriter(otherXmlPath.ItemSpec, false)) { sw.Write(_xmlDocument2); } // xmlPaths have one XmlPath, lets duplicate it TaskItem[] xmlMultiPaths = new TaskItem[] { xmlPaths[0], otherXmlPath, xmlPaths[0], xmlPaths[0] }; // outputPaths have one output path, lets duplicate it TaskItem[] outputMultiPaths = new TaskItem[] { new TaskItem(outputPaths[0].ItemSpec + ".1.xml"), new TaskItem(outputPaths[0].ItemSpec + ".2.xml"), new TaskItem(outputPaths[0].ItemSpec + ".3.xml"), new TaskItem(outputPaths[0].ItemSpec + ".4.xml") }; { XslTransformation t = new XslTransformation(); t.BuildEngine = engine; t.XslInputPath = xslPath; t.XmlInputPaths = xmlMultiPaths; t.OutputPaths = outputMultiPaths; Assert.True(t.Execute(), "CompiledDllWithTwoTypes execution should've passed" + engine.Log); Console.WriteLine(engine.Log); foreach (TaskItem tsk in t.OutputPaths) { Assert.True(File.Exists(tsk.ItemSpec), tsk.ItemSpec + " should exist on output dir"); } // The first and second input XML files are not equivalent, so their output files // should be different Assert.NotEqual(new FileInfo(xmlMultiPaths[0].ItemSpec).Length, new FileInfo(xmlMultiPaths[1].ItemSpec).Length); Assert.NotEqual(new FileInfo(outputMultiPaths[0].ItemSpec).Length, new FileInfo(outputMultiPaths[1].ItemSpec).Length); System.Diagnostics.Debug.WriteLine(engine.Log); } CleanUp(dir); } /// <summary> /// Not Matching XmlInputPaths and OutputPaths /// </summary> [Fact] public void MultipleXmlInputs_NotMatching() { string dir; TaskItem[] xmlPaths; TaskItem xslPath; TaskItem[] outputPaths; MockEngine engine; Prepare(out dir, out xmlPaths, out xslPath, out _, out outputPaths, out _, out _, out engine); // xmlPaths have one XmlPath, lets duplicate it **4 times ** TaskItem[] xmlMultiPaths = new TaskItem[] { xmlPaths[0], xmlPaths[0], xmlPaths[0], xmlPaths[0] }; // outputPaths have one output path, lets duplicate it **3 times ** TaskItem[] outputMultiPathsShort = new TaskItem[] { new TaskItem(outputPaths[0].ItemSpec + ".1.xml"), new TaskItem(outputPaths[0].ItemSpec + ".2.xml"), new TaskItem(outputPaths[0].ItemSpec + ".3.xml") }; TaskItem[] outputMultiPathsLong = new TaskItem[] { new TaskItem(outputPaths[0].ItemSpec + ".1.xml"), new TaskItem(outputPaths[0].ItemSpec + ".2.xml"), new TaskItem(outputPaths[0].ItemSpec + ".3.xml"), new TaskItem(outputPaths[0].ItemSpec + ".4.xml"), new TaskItem(outputPaths[0].ItemSpec + ".5.xml") }; // Short version. { XslTransformation t = new XslTransformation(); t.BuildEngine = engine; t.XslInputPath = xslPath; t.XmlInputPaths = xmlMultiPaths; t.OutputPaths = outputMultiPathsShort; Assert.False(t.Execute(), "CompiledDllWithTwoTypes execution should've failed" + engine.Log); System.Diagnostics.Debug.WriteLine(engine.Log); } // Long version { XslTransformation t = new XslTransformation(); t.BuildEngine = engine; t.XslInputPath = xslPath; t.XmlInputPaths = xmlMultiPaths; t.OutputPaths = outputMultiPathsLong; Assert.False(t.Execute(), "CompiledDllWithTwoTypes execution should've failed" + engine.Log); Console.WriteLine(engine.Log); System.Diagnostics.Debug.WriteLine(engine.Log); } CleanUp(dir); } #if FEATURE_COMPILED_XSL /// <summary> /// Validate that the XslTransformation task allows use of the document function /// </summary> [Fact] public void XslDocumentFunctionWorks() { string dir; TaskItem[] outputPaths; MockEngine engine; Prepare(out dir, out _, out _, out _, out outputPaths, out _, out _, out engine); var otherXslPath = new TaskItem(Path.Combine(dir, Guid.NewGuid().ToString() + ".xslt")); using (StreamWriter sw = new StreamWriter(otherXslPath.ItemSpec, false)) { sw.Write(_xslDocument2); } // Initialize first xml file for the XslTransformation task to consume var myXmlPath1 = new TaskItem(Path.Combine(dir, "a.xml")); using (StreamWriter sw = new StreamWriter(myXmlPath1.ItemSpec, false)) { sw.Write("<document><myInclude path = \"b.xml\"/></document>"); } // Initialize second xml file for the first one to consume var myXmlPath2 = new TaskItem(Path.Combine(dir, "b.xml")); using (StreamWriter sw = new StreamWriter(myXmlPath2.ItemSpec, false)) { sw.Write("<stuff/>"); } // Validate that execution passes when UseTrustedSettings is true XslTransformation t = new XslTransformation(); t.BuildEngine = engine; t.OutputPaths = outputPaths; t.XmlInputPaths = new TaskItem[] { myXmlPath1 }; t.XslInputPath = otherXslPath; t.UseTrustedSettings = true; Assert.True(t.Execute()); // "Test should have passed and allowed the use of the document() function within the xslt file" // Validate that execution fails when UseTrustedSettings is false t = new XslTransformation(); t.BuildEngine = engine; t.OutputPaths = outputPaths; t.XmlInputPaths = new TaskItem[] { myXmlPath1 }; t.XslInputPath = otherXslPath; t.UseTrustedSettings = false; Assert.False(t.Execute()); // "Test should have failed and not allowed the use of the document() function within the xslt file" CleanUp(dir); } #endif /// <summary> /// Prepares the test environment, creates necessary files. /// </summary> /// <param name="dir">The temp dir</param> /// <param name="xmlPaths">The xml file's path</param> /// <param name="xslPath">The xsl file's path</param> /// <param name="xslCompiledPath">The xsl dll's path</param> /// <param name="outputPaths">The output file's path</param> /// <param name="xmlInputs">The xml input ways</param> /// <param name="xslInputs">The xsl input ways</param> /// <param name="engine">The Mock engine</param> private void Prepare(out string dir, out TaskItem[] xmlPaths, out TaskItem xslPath, out TaskItem xslCompiledPath, out TaskItem[] outputPaths, out List<KeyValuePair<XslTransformation.XmlInput.XmlModes, object>> xmlInputs, out List<KeyValuePair<XslTransformation.XsltInput.XslModes, object>> xslInputs, out MockEngine engine) { dir = Path.Combine(Path.GetTempPath(), DateTime.Now.Ticks.ToString()); Directory.CreateDirectory(dir); // save XML and XSLT documents. xmlPaths = new TaskItem[] { new TaskItem(Path.Combine(dir, "doc.xml")) }; xslPath = new TaskItem(Path.Combine(dir, "doc.xslt")); xslCompiledPath = new TaskItem(Path.Combine(dir, "doc.dll")); outputPaths = new TaskItem[] { new TaskItem(Path.Combine(dir, "testout.xml")) }; using (StreamWriter sw = new StreamWriter(xmlPaths[0].ItemSpec, false)) { sw.Write(_xmlDocument); sw.Close(); } using (StreamWriter sw = new StreamWriter(xslPath.ItemSpec, false)) { sw.Write(_xslDocument); sw.Close(); } xmlInputs = new List<KeyValuePair<XslTransformation.XmlInput.XmlModes, object>>(); xslInputs = new List<KeyValuePair<XslTransformation.XsltInput.XslModes, object>>(); xmlInputs.Add(new KeyValuePair<XslTransformation.XmlInput.XmlModes, object>(XslTransformation.XmlInput.XmlModes.Xml, _xmlDocument)); xmlInputs.Add(new KeyValuePair<XslTransformation.XmlInput.XmlModes, object>(XslTransformation.XmlInput.XmlModes.XmlFile, xmlPaths)); xslInputs.Add(new KeyValuePair<XslTransformation.XsltInput.XslModes, object>(XslTransformation.XsltInput.XslModes.Xslt, _xslDocument)); xslInputs.Add(new KeyValuePair<XslTransformation.XsltInput.XslModes, object>(XslTransformation.XsltInput.XslModes.XsltFile, xslPath)); #if FEATURE_COMPILED_XSL Compile(xslPath.ItemSpec, xslCompiledPath.ItemSpec); #endif engine = new MockEngine(); List<bool> results = new List<bool>(); } /// <summary> /// Clean ups the test files /// </summary> /// <param name="dir">The directory for temp files.</param> private void CleanUp(string dir) { try { FileUtilities.DeleteWithoutTrailingBackslash(dir, true); } catch { } } #region Compiler #pragma warning disable 0618 // XmlReaderSettings.ProhibitDtd is obsolete #if FEATURE_COMPILED_XSL /// <summary> /// Compiles given stylesheets into an assembly. /// </summary> private void Compile(string inputFile, string outputFile) { const string CompiledQueryName = "xslt"; string outputDir = Path.GetDirectoryName(outputFile) + Path.DirectorySeparatorChar; XsltSettings xsltSettings = new XsltSettings(true, true); XmlUrlResolver xmlResolver = new XmlUrlResolver(); XmlReaderSettings readerSettings = new XmlReaderSettings(); AssemblyBuilder asmBldr; readerSettings.ProhibitDtd = false; readerSettings.XmlResolver = xmlResolver; string scriptAsmPathPrefix = outputDir + Path.GetFileNameWithoutExtension(outputFile) + ".script"; // Create assembly and module builders AssemblyName asmName = new AssemblyName(); asmName.Name = CompiledQueryName; asmBldr = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Save, outputDir); // Add custom attribute to assembly marking it as security transparent so that Assert will not be allowed // and link demands will be converted to full demands. asmBldr.SetCustomAttribute(new CustomAttributeBuilder(typeof(System.Security.SecurityTransparentAttribute).GetConstructor(Type.EmptyTypes), new object[] { })); // Mark the assembly with GeneratedCodeAttribute to improve profiling experience asmBldr.SetCustomAttribute(new CustomAttributeBuilder(typeof(GeneratedCodeAttribute).GetConstructor(new Type[] { typeof(string), typeof(string) }), new object[] { "XsltCompiler", "2.0.0.0" })); ModuleBuilder modBldr = asmBldr.DefineDynamicModule(Path.GetFileName(outputFile), Path.GetFileName(outputFile), true); string sourceUri = inputFile; string className = Path.GetFileNameWithoutExtension(inputFile); string scriptAsmId = ""; // Always use the .dll extension; otherwise Fusion won't be able to locate this dependency string scriptAsmPath = scriptAsmPathPrefix + scriptAsmId + ".dll"; // Create TypeBuilder and compile the stylesheet into it TypeBuilder typeBldr = modBldr.DefineType(CompiledQueryName, TypeAttributes.Public | TypeAttributes.Abstract | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit); CompilerErrorCollection errors = null; try { using (XmlReader reader = XmlReader.Create(sourceUri, readerSettings)) { errors = XslCompiledTransform.CompileToType( reader, xsltSettings, xmlResolver, false, typeBldr, scriptAsmPath ); } } catch (Exception e) { Assert.True(false, "Compiler didn't work" + e.ToString()); } asmBldr.Save(Path.GetFileName(outputFile), PortableExecutableKinds.ILOnly, ImageFileMachine.I386); } #endif #pragma warning restore 0618 #if FEATURE_COMPILED_XSL /// <summary> /// Creates a dll that has 2 types in it. /// </summary> /// <param name="outputFile">The dll name.</param> private void CompileDoubleType(string outputFile) { string outputDir = Path.GetDirectoryName(outputFile) + Path.DirectorySeparatorChar; const string CompiledQueryName = "xslt"; AssemblyBuilder asmBldr; // Create assembly and module builders AssemblyName asmName = new AssemblyName(); asmName.Name = "assmname"; asmBldr = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Save, outputDir); ModuleBuilder modBldr = asmBldr.DefineDynamicModule(Path.GetFileName(outputFile), Path.GetFileName(outputFile), true); // Create TypeBuilder and compile the stylesheet into it TypeBuilder typeBldr = modBldr.DefineType(CompiledQueryName, TypeAttributes.Public | TypeAttributes.Abstract | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit); typeBldr.DefineField("x", typeof(int), FieldAttributes.Private); TypeBuilder typeBldr2 = modBldr.DefineType(CompiledQueryName + "2", TypeAttributes.Public | TypeAttributes.Abstract | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit); typeBldr2.DefineField("x", typeof(int), FieldAttributes.Private); typeBldr.CreateType(); typeBldr2.CreateType(); asmBldr.Save(Path.GetFileName(outputFile), PortableExecutableKinds.ILOnly, ImageFileMachine.I386); } #endif #endregion } #endif }
using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.Xml.Serialization; namespace SomeTechie.RoundRobinScheduleGenerator { [XmlType()] public class Tournament { protected List<Division> _divisions; [XmlElement("Divisions", typeof(List<Division>))] public List<Division> Divisions { get { return _divisions; } set { _divisions = value; } } protected int _scheduleVersion = 0; [XmlAttribute("ScheduleVersion")] public int ScheduleVersion { get { return _scheduleVersion; } set { _scheduleVersion = value; } } protected int _numCourts; [XmlAttribute("NumCourts")] public int NumCourts { get { return _numCourts; } set { _numCourts = value; } } protected int _cycles = 1; [XmlAttribute("Cycles")] public int Cycles { get { return _cycles; } set { if (_cycles != value){ // The new value is different if (AutoCalculateNumRobinRounds){ // The number of robin rounds is auto-calculated; regenerate the schedule _courtRounds = null; } _cycles = value; } } } [XmlIgnore()] public bool AutoCalculateNumRobinRounds { get { return _robinRoundsToPlay == -1; } set { RobinRoundsToPlay = -1; } } [XmlIgnore()] public int TotalRobinRounds { get { if(_robinRoundsToPlay > RobinRoundsNeededToFinish * Cycles) return _robinRoundsToPlay; else return RobinRoundsNeededToFinish * Cycles; } } protected int _robinRoundsToPlay = -1; [XmlAttribute("RobinRoundsToPlay")] public int RobinRoundsToPlay { get { return _robinRoundsToPlay == -1 ? TotalRobinRounds : _robinRoundsToPlay; } set { if (_robinRoundsToPlay != value){ // The new value is different if(_robinRoundsToPlay != -1 || value != TotalRobinRounds){ // Either the number of robin rounds didn't used to be auto-calculated, or the new value isn't the auto-calculated value if (_robinRoundsToPlay != TotalRobinRounds || value != -1) { // Either the old value was manually set, or the new value isn't to auto-calculate _courtRounds = null; } } _robinRoundsToPlay = value; } } } protected string _name = "Untitled Tournament"; [XmlAttribute("Name")] public string Name { get { return _name; } set { _name = value; } } protected Dictionary<Division, List<RobinRound>> _robinRoundsForDivision = new Dictionary<Division, List<RobinRound>>(); [XmlIgnore()] protected Dictionary<Division, List<RobinRound>> RobinRoundsForDivision { get { if (_robinRoundsForDivision.Count < Divisions.Count) { foreach (Division division in Divisions) { _robinRoundsForDivision[division] = CalculateRobinRoundsForDivision(division); } } return _robinRoundsForDivision; } } [XmlIgnore()] public int RobinRoundsNeededToFinish { get { int robinRoundsNeededToFinish = 0; //Calculate the number of needed robin rounds (greatest robin round count for any division) foreach (Division division in Divisions) { if (((List<RobinRound>)RobinRoundsForDivision[division]).Count > robinRoundsNeededToFinish) { robinRoundsNeededToFinish = ((List<RobinRound>)RobinRoundsForDivision[division]).Count; } } return robinRoundsNeededToFinish; } } protected ScoreKeeper[] _scoreKeepers; [XmlArray("ScoreKeepers"), XmlArrayItem("ScoreKeeper")] public ScoreKeeper[] ScoreKeepers { get { return _scoreKeepers; } set { _scoreKeepers = value; } } protected List<string> _scoreKeeperAccessCodes; [XmlArray("AccessCodes"), XmlArrayItem("AccessCode")] public List<string> ScoreKeeperAccessCodes { get { return _scoreKeeperAccessCodes; } set { _scoreKeeperAccessCodes = value; } } protected Dictionary<GamePosition, ScoreKeeper> _scoreKeepersAssignment = new Dictionary<GamePosition, ScoreKeeper>(); [XmlIgnore()] public Dictionary<GamePosition, ScoreKeeper> ScoreKeepersAssignment { get { return _scoreKeepersAssignment; } set { _scoreKeepersAssignment = value; } } [XmlArray("ScoreKeepersAssignment"), XmlArrayItem("ScoreKeeperAssignment")] public SerializableKeyValuePair<XmlGamePosition,int>[] XmlScoreKeepersAssignment { get { List<SerializableKeyValuePair<XmlGamePosition, int>> xmlResults = new List<SerializableKeyValuePair<XmlGamePosition, int>>(); GamePosition[] keys = new GamePosition[ScoreKeepersAssignment.Count]; ScoreKeepersAssignment.Keys.CopyTo(keys, 0); ScoreKeeper[] values = new ScoreKeeper[ScoreKeepersAssignment.Count]; ScoreKeepersAssignment.Values.CopyTo(values, 0); for (int i = 0; i < ScoreKeepersAssignment.Count; i++) { xmlResults.Add(new SerializableKeyValuePair<XmlGamePosition, int>(new XmlGamePosition(keys[i].CourtRoundNum, keys[i].CourtNumber), values[i].Id)); } return xmlResults.ToArray(); } set { _scoreKeepersAssignment.Clear(); foreach (SerializableKeyValuePair<XmlGamePosition, int> pair in value) { _scoreKeepersAssignment.Add(GamePosition.GetGamePosition(pair.Key.CourtRoundNum, pair.Key.CourtNumber), getScoreKeeperById(pair.Value)); } } } protected Dictionary<int, Game> _games = new Dictionary<int, Game>(); [XmlIgnore()] public List<Game> Games { get { List<Game> games = new List<Game>(); foreach (CourtRound courtRound in CourtRounds) { games.AddRange(courtRound.Games); } return games; } } [XmlIgnore()] public Dictionary<int, Game> GamesById { get { Dictionary<int, Game> gamesById = new Dictionary<int, Game>(); foreach (Game game in Games) { gamesById.Add(game.Id,game); } return gamesById; } } [XmlArray("Games"),XmlArrayItem("Game")] public Game[] XmlGames { get { return Games.ToArray(); } set { _games.Clear(); foreach (Game game in value) { List<RoundRobinTeamData> teamDatas = new List<RoundRobinTeamData>(); foreach (string teamId in game.XmlTeamsIn) { teamDatas.Add(getTeamDataById(teamId)); } game.TeamDatas = teamDatas; RoundRobinTeamData winningTeamData = getTeamDataById(game.XmlWinningTeamIn); if (winningTeamData != null) { game.WinningTeam = winningTeamData.Team; } foreach (KeyValuePair<string,TeamGameResult> teamResult in game.TeamGameResults) { teamResult.Value.TeamData = getTeamDataById(teamResult.Key); } foreach (RoundRobinTeamData teamData in game.TeamDatas) { if (teamData.XmlPlayedGamesIn.Contains(game.Id)) { teamData.addPlayedGame(game); } } _games.Add(game.Id, game); } } } [XmlIgnore()] public bool IsInProgress { get { bool? isCompleted = null; foreach (Game game in Games) { if (game.IsInProgress) return true; else if(game.IsCompleted) { if (isCompleted == null) isCompleted = IsCompleted; if (isCompleted == false) return true; } } return false; } } [XmlIgnore()] public bool IsCompleted { get { foreach (Game game in Games) { if (!game.IsCompleted) return false; } return true; } } protected List<CourtRound> _courtRounds; [XmlIgnore()] public List<CourtRound> CourtRounds { get { if (_courtRounds == null) { _courtRounds = CalculateCourtRounds(RobinRoundsToPlay); } return _courtRounds; } } [XmlArray("CourtRounds"), XmlArrayItem("CourtRound")] public CourtRound[] XmlCourtRounds { get { return CourtRounds.ToArray(); } set { _courtRounds = new List<CourtRound>(value); foreach (CourtRound CourtRound in _courtRounds) { List<Game> games = new List<Game>(); foreach (int gameId in CourtRound.XmlGamesIn) { games.Add((Game)_games[gameId]); } CourtRound.Games = games; } } } [XmlIgnore()] public CourtRound ActiveCourtRound { get { CourtRound activeCourtRound = null; foreach (CourtRound courtRound in CourtRounds) { if (courtRound.IsActive) { activeCourtRound = courtRound; break; } } return activeCourtRound; } } protected List<RobinRound> _robinRounds; [XmlIgnore()] public List<RobinRound> RobinRounds { get { if (_robinRounds == null) { _courtRounds = CalculateCourtRounds(RobinRoundsToPlay); } return _robinRounds; } } [XmlArray("RobinRounds"),XmlArrayItem("RobinRound")] public RobinRound[] XmlRobinRounds{ get { return RobinRounds.ToArray(); } set { _robinRounds = new List<RobinRound>(value); foreach (RobinRound robinRound in _robinRounds) { List<Game> games = new List<Game>(); foreach (int gameId in robinRound.XmlGamesIn) { games.Add((Game)_games[gameId]); } robinRound.Games = games; } } } public Tournament(List<Division> divisions, int numCourts) { _divisions = divisions; _numCourts = numCourts; } protected Tournament() { } private List<Game> calculatePossibleGames(List<Game> unusedGames, List<Game> courtRoundGames) { List<Team> OccupiedTeams = new List<Team>(); foreach (Game game in courtRoundGames) { OccupiedTeams.AddRange(game.Teams); } return calculatePossibleGames(unusedGames, OccupiedTeams); } private List<Game> calculatePossibleGames(List<Game> unusedGames, List<Team> occupiedTeams) { List<Game> PossibleGames = new List<Game>(); foreach (Game game in unusedGames) { bool isPossibleGame = true; foreach (Team team in game.Teams) { if (occupiedTeams.Contains(team)) { isPossibleGame = false; break; } } if (isPossibleGame) { PossibleGames.Add(game); } } return PossibleGames; } private List<CourtRound> CalculateCourtRounds(int numRobinRounds = -1) { _robinRounds = new List<RobinRound>(); List<CourtRound> CourtRounds = new List<CourtRound>(); resetGameCloneCount(); _scheduleVersion++; List<List<RobinRound>> DivisionsRobinRounds = new List<List<RobinRound>>(); Dictionary<Team, int> TeamsNumberOfHomeGames = new Dictionary<Team, int>(); bool haveRobinRounds = false; foreach (Division division in Divisions) { DivisionsRobinRounds.Add(((List<RobinRound>)RobinRoundsForDivision[division])); if (RobinRoundsForDivision[division].Count > 0) { haveRobinRounds = true; } foreach (Team team in division.Teams) { TeamsNumberOfHomeGames.Add(team, 0); } } if (!haveRobinRounds) { // We don't have any games to work with return CourtRounds; } if (numRobinRounds < 1) numRobinRounds = TotalRobinRounds; int RobinRoundNumber = 0; int CourtRoundNumber = 0; List<Game> RobinRoundUsedGames = null; List<Game> RobinRoundUnusedGames = null; //Keep track of what teams we have used for each court round List<List<Team>> CourtRoundsUsedTeams = new List<List<Team>>(); bool completedAllCourtRounds = false; //To help convert team to index List<Team> teams = new List<Team>(); foreach (Division division in Divisions) { teams.AddRange(division.Teams); } //To help put teams on different courts Dictionary<int, Dictionary<int, int>> timesOnCourtByTeam = new Dictionary<int, Dictionary<int, int>>(); foreach(Team team in teams) { Dictionary<int, int> timesOnCourt = new Dictionary<int, int>(); for (int i = 0; i <= NumCourts; i++) { timesOnCourt.Add(i, 0); } timesOnCourtByTeam.Add(team.NumId, timesOnCourt); } while (!completedAllCourtRounds) { CourtRoundsUsedTeams.Add(new List<Team>()); Dictionary<int,List<Game>> CourtRoundGamesByDivision = new Dictionary<int,List<Game>>(); //Populate CourtRoundGamesByDivision initial values foreach (Division division in Divisions) { CourtRoundGamesByDivision.Add(division.NumId, new List<Game>()); } for (int i = 0; i < this.NumCourts; i++) { if (RobinRoundUnusedGames == null) { RobinRoundUnusedGames = new List<Game>(); foreach (List<RobinRound> DivisionRobinRounds in DivisionsRobinRounds) { if (DivisionRobinRounds.Count < 1) continue; int DivisionRobinRoundIndex = RobinRoundNumber % DivisionRobinRounds.Count; RobinRoundUnusedGames.AddRange(DivisionRobinRounds[DivisionRobinRoundIndex].Games); } RobinRoundUsedGames = new List<Game>(); } List<Game> PossibleGames = calculatePossibleGames(RobinRoundUnusedGames, CourtRoundsUsedTeams[CourtRoundNumber]); if (PossibleGames.Count <= 0) { break; } double GamesSectionLength = PossibleGames.Count / NumCourts; Game PickedGame = PossibleGames[(int)Math.Floor(GamesSectionLength * i)]; Game ClonedGame; if (TeamsNumberOfHomeGames[PickedGame.Team1] <= TeamsNumberOfHomeGames[PickedGame.Team2]) { ClonedGame = getGame(PickedGame.Team1Data, PickedGame.Team2Data); } else { ClonedGame = getGame(PickedGame.Team2Data, PickedGame.Team1Data); } TeamsNumberOfHomeGames[ClonedGame.Team1]++; ClonedGame.CourtRoundNum = CourtRoundNumber + 1; ClonedGame.RobinRoundNum = RobinRoundNumber + 1; ClonedGame.ScheduleVersion = _scheduleVersion; CourtRoundGamesByDivision[ClonedGame.Division.NumId].Add(ClonedGame); CourtRoundsUsedTeams[CourtRoundNumber].AddRange(PickedGame.Teams); RobinRoundUsedGames.Add(ClonedGame); RobinRoundUnusedGames.Remove(PickedGame); if (RobinRoundUnusedGames.Count <= 0) { RobinRoundUnusedGames = null; _robinRounds.Add(new RobinRound(RobinRoundUsedGames, RobinRoundNumber + 1)); RobinRoundNumber++; if (RobinRoundNumber >= numRobinRounds) { completedAllCourtRounds = true; break; } } } List<Game> CourtRoundGamesSchedule = new List<Game>(); foreach (KeyValuePair<int, List<Game>> CourtRoundGamesForDivision in CourtRoundGamesByDivision) { // Keep track of the games we have left to schedule List<Game> GamesToSchedule = new List<Game>(CourtRoundGamesForDivision.Value); // Start scheduling games while (GamesToSchedule.Count > 0) { int CourtId = CourtRoundGamesSchedule.Count; int CourtNumber = CourtId + 1; Game PickedGame = null; int pickedGameTeamsNumberSum = 0; int lowestTimesOnCourtSum = int.MaxValue; if (GamesToSchedule.Count == 0) { PickedGame = GamesToSchedule[0]; } else { // Find the game with the teams that have been on this court the least foreach (Game game in GamesToSchedule) { int timesOnCourtSum = 0; int teamsNumberSum = 0; // Find out how many times each of the two teams has been on each court foreach (Team team in game.Teams) { timesOnCourtSum += timesOnCourtByTeam[team.NumId][CourtId]; teamsNumberSum+=team.Number; } if (timesOnCourtSum < lowestTimesOnCourtSum || (timesOnCourtSum == lowestTimesOnCourtSum && teamsNumberSum < pickedGameTeamsNumberSum)) { PickedGame = game; lowestTimesOnCourtSum = timesOnCourtSum; pickedGameTeamsNumberSum = teamsNumberSum; } } } // Add this game to the list of scheduled games CourtRoundGamesSchedule.Add(PickedGame); // Remove this game from the list of games left to schedule GamesToSchedule.Remove(PickedGame); PickedGame.CourtNumber = CourtNumber; // Keep track of which court the teams were placed on foreach (Team team in PickedGame.Teams) { timesOnCourtByTeam[team.NumId][CourtId] += 1; } } } CourtRounds.Add(new CourtRound(CourtRoundGamesSchedule, CourtRoundNumber + 1)); CourtRoundNumber++; } return CourtRounds; } protected Dictionary<string, List<Game>> gameClones = new Dictionary<string, List<Game>>(); protected Dictionary<string, int> gameCloneCount = new Dictionary<string, int>(); /*if (TeamsNumberOfHomeGames[firstTeamData.Team] <= TeamsNumberOfHomeGames[secondTeamData.Team]) { game = new Game(firstTeamData, secondTeamData); } else { game = new Game(secondTeamData, firstTeamData); } TeamsNumberOfHomeGames[game.Team1Data.Team]++; */ protected Game getGame(RoundRobinTeamData team1Data, RoundRobinTeamData team2Data) { string vsID = Game.CalculateVsId(team1Data.Team, team2Data.Team); if (!gameCloneCount.ContainsKey(vsID)) { gameCloneCount[vsID] = -1; } gameCloneCount[vsID]++; int index = gameCloneCount[vsID]; if (!gameClones.ContainsKey(vsID)) { gameClones.Add(vsID, new List<Game>()); } List<Game> clones = gameClones[vsID]; Game clone; if (clones.Count <= index) { clone = new Game(team1Data, team2Data); clones.Add(clone); } else { clone = clones[index]; } return clone; } [XmlArray("GameCloneLists"), XmlArrayItem("GameCloneList")] public SerializableKeyValuePair<string,int[]>[] XmlCloneList { get { List<SerializableKeyValuePair<string, int[]>> cloneLists = new List<SerializableKeyValuePair<string, int[]>>(); foreach(KeyValuePair<string,List<Game>> clones in gameClones){ List<int> cloneList = new List<int>(); foreach(Game game in clones.Value) { cloneList.Add(game.Id); } cloneLists.Add(new SerializableKeyValuePair<string, int[]>(clones.Key, cloneList.ToArray())); } return cloneLists.ToArray(); } set { foreach (SerializableKeyValuePair<string, int[]> cloneList in value) { if (cloneList.Value != null) { List<Game> clones = new List<Game>(); foreach (int gameId in cloneList.Value) { if (_games.ContainsKey(gameId)) { clones.Add(_games[gameId]); } } gameClones[cloneList.Key] = clones; } } } } protected void resetGameCloneCount(){ gameCloneCount.Clear(); } protected List<RobinRound> CalculateRobinRoundsForDivision(Division division, bool includeByeGames = false) { if (division.Teams.Count < 2) return new List<RobinRound>(); List<RoundRobinTeamData> TeamDatas = new List<RoundRobinTeamData>(); TeamDatas.AddRange(division.RoundRobinDatas); if (TeamDatas.Count % 2 == 1) { TeamDatas.Add(new RoundRobinTeamData(new ByeTeam())); } int numTeams = TeamDatas.Count; int numDays = (numTeams - 1); int halfSize = numTeams / 2; RoundRobinTeamData Team1Data = TeamDatas[0]; TeamDatas.RemoveAt(0); int TeamsSize = TeamDatas.Count; List<RobinRound> robinRounds = new List<RobinRound>(); for (int robinRoundNum = 0; robinRoundNum < numDays; robinRoundNum++) { List<Game> robinRoundGames = new List<Game>(); int teamIdx = robinRoundNum % TeamsSize; for (int idx = 0; idx < halfSize; idx++) { RoundRobinTeamData firstTeamData; if (idx == 0) { firstTeamData = Team1Data; } else { firstTeamData = TeamDatas[(robinRoundNum + idx) % TeamsSize]; } RoundRobinTeamData secondTeamData; if (idx == 0) { secondTeamData = TeamDatas[teamIdx]; } else { secondTeamData = TeamDatas[(robinRoundNum + TeamsSize - idx) % TeamsSize]; } if (!includeByeGames && !firstTeamData.IsBye && !secondTeamData.IsBye) { Game game = new Game(firstTeamData, secondTeamData); robinRoundGames.Add(game); } } robinRounds.Add(new RobinRound(robinRoundGames, robinRoundNum)); } return robinRounds; } public Dictionary<Division, List<Team>> CalculateSeedingByDivisions() { Dictionary<Division, List<Team>> seeedingForDivision = new Dictionary<Division, List<Team>>(); foreach (Division division in Divisions) { seeedingForDivision[division] = CalculateSeedingForDivision(division); } return seeedingForDivision; } protected List<Team> CalculateSeedingForDivision(Division division) { List<RoundRobinTeamData> teamDatas = new List<RoundRobinTeamData>(division.RoundRobinDatas); Comparison<RoundRobinTeamData> CompareTeams = delegate(RoundRobinTeamData x, RoundRobinTeamData y) { if (y.ScheduleVersion != ScheduleVersion) { y.resetStatistics(); } if (x.ScheduleVersion != ScheduleVersion) { x.resetStatistics(); } int compareValue = y.PercentGamesWon.CompareTo(x.PercentGamesWon); if (compareValue == 0) { compareValue = y.AverageScore.CompareTo(x.AverageScore); } if (compareValue == 0) { compareValue = x.Team.Number.CompareTo(y.Team.Number); } return compareValue; }; teamDatas.Sort(CompareTeams); List<Team> teams = new List<Team>(); foreach(RoundRobinTeamData teamData in teamDatas){ teams.Add(teamData.Team); } return teams; } public RoundRobinTeamData getTeamDataById(string teamId) { if (string.IsNullOrEmpty(teamId) || teamId.Length < 2) { return null; } string teamDivisionAbbreviation = teamId.Substring(0, 1); int teamIndex = int.Parse(teamId.Substring(1)) - 1; foreach (Division division in Divisions) { if (division.Abbreviation != teamDivisionAbbreviation) continue; return division.RoundRobinDatas[teamIndex]; } return null; } public RoundRobinTeamData getTeamDataByNumId(int teamNumId) { foreach (Division division in Divisions) { foreach (RoundRobinTeamData roundRobinData in division.RoundRobinDatas) { if (roundRobinData.Team.NumId == teamNumId) return roundRobinData; } } return null; } public ScoreKeeper getScoreKeeperById(int scoreKeeperId) { foreach (ScoreKeeper scoreKeeper in ScoreKeepers) { if (scoreKeeper.Id == scoreKeeperId) return scoreKeeper; } return null; } public Game getGame(int courtRoundNumber, int courtNumber) { if (courtRoundNumber > 0 && this.CourtRounds.Count >= courtRoundNumber) { CourtRound courtRound = this.CourtRounds[courtRoundNumber - 1]; if (courtNumber > 0 && courtRound.numGames >= courtNumber) { return courtRound.Games[courtNumber - 1]; } } return null; } public void incrementScheduleVersion() { _scheduleVersion++; foreach (Game game in Games) { game.ScheduleVersion++; } } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Projection // Description: The basic module for MapWindow version 6.0 // ******************************************************************************************************** // // The original content was ported from the C language from the 4.6 version of Proj4 libraries. // Frank Warmerdam has released the full content of that version under the MIT license which is // recognized as being approximately equivalent to public domain. The original work was done // mostly by Gerald Evenden. The latest versions of the C libraries can be obtained here: // http://trac.osgeo.org/proj/ // // The Initial Developer of this Original Code is Ted Dunsford. Created 8/12/2009 11:39:36 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // Name | Date | Comment // --------------------|------------|------------------------------------------------------------ // Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL // ******************************************************************************************************** using System; namespace DotSpatial.Projections.Transforms { public class AzimuthalEquidistant : EllipticalTransform { #region Private Variables private const double TOL = 1E-14; private double _cosph0; private double[] _en; private double _g; private double _he; private bool _isGuam; private double _m1; private Modes _mode; private double _mp; private double _n1; private double _sinph0; #endregion #region Constructors /// <summary> /// Creates a new instance of AzimuthalEquidistant /// </summary> public AzimuthalEquidistant() { Proj4Name = "aeqd"; Name = "Azimuthal_Equidistant"; } #endregion #region Methods /// <summary> /// Initializes the transform using the parameters from the specified coordinate system information /// </summary> /// <param name="projInfo">A ProjectionInfo class contains all the standard and custom parameters needed to initialize this transform</param> protected override void OnInit(ProjectionInfo projInfo) { Phi0 = projInfo.Phi0; if (Math.Abs(Math.Abs(Phi0) - HALF_PI) < EPS10) { _mode = Phi0 < 0 ? Modes.SouthPole : Modes.NorthPole; _sinph0 = Phi0 < 0 ? -1 : 1; _cosph0 = 0; } else if (Math.Abs(Phi0) < EPS10) { _mode = Modes.Equitorial; _sinph0 = 0; _cosph0 = 1; } else { _mode = Modes.Oblique; _sinph0 = Math.Sin(Phi0); _cosph0 = Math.Cos(Phi0); } if (Es == 0) return; _en = Proj.Enfn(Es); if (projInfo.guam.HasValue && projInfo.guam.Value) { _m1 = Proj.Mlfn(Phi0, _sinph0, _cosph0, _en); _isGuam = true; } else { switch (_mode) { case Modes.NorthPole: _mp = Proj.Mlfn(HALF_PI, 1, 0, _en); break; case Modes.SouthPole: _mp = Proj.Mlfn(-HALF_PI, -1, 0, _en); break; case Modes.Equitorial: case Modes.Oblique: _n1 = 1 / Math.Sqrt(1 - Es * _sinph0 * _sinph0); _g = _sinph0 * (_he = E / Math.Sqrt(OneEs)); _he *= _cosph0; break; } } } /// <inheritdoc /> protected override void SphericalForward(double[] lp, double[] xy, int startIndex, int numPoints) { for (int i = startIndex; i < startIndex + numPoints; i++) { int phi = i * 2 + PHI; int lam = i * 2 + LAMBDA; int x = i * 2 + X; int y = i * 2 + Y; double sinphi = Math.Sin(lp[phi]); double cosphi = Math.Cos(lp[phi]); double coslam = Math.Cos(lp[lam]); switch (_mode) { case Modes.Equitorial: case Modes.Oblique: if (_mode == Modes.Equitorial) { xy[y] = cosphi * coslam; } else { xy[y] = _sinph0 * sinphi + _cosph0 * cosphi * coslam; } if (Math.Abs(Math.Abs(xy[y]) - 1) < TOL) { if (xy[y] < 0) { xy[x] = double.NaN; xy[y] = double.NaN; continue; //throw new ProjectionException(20); } xy[x] = xy[y] = 0; } else { xy[y] = Math.Acos(xy[y]); xy[y] /= Math.Sin(xy[y]); xy[x] = xy[y] * cosphi * Math.Sin(lp[lam]); xy[y] *= (_mode == Modes.Equitorial) ? sinphi : _cosph0 * sinphi - _sinph0 * cosphi * coslam; } break; case Modes.NorthPole: case Modes.SouthPole: if (_mode == Modes.NorthPole) { lp[phi] = -lp[phi]; coslam = -coslam; } if (Math.Abs(lp[phi] - HALF_PI) < EPS10) { xy[x] = double.NaN; xy[y] = double.NaN; continue; //throw new ProjectionException(20); } xy[x] = (xy[y] = (HALF_PI + lp[phi])) * Math.Sin(lp[lam]); xy[y] *= coslam; break; } } } /// <inheritdoc /> protected override void EllipticalForward(double[] lp, double[] xy, int startIndex, int numPoints) { if (_isGuam) { GuamForward(lp, xy, startIndex, numPoints); return; } for (int i = startIndex; i < startIndex + numPoints; i++) { int phi = i * 2 + PHI; int lam = i * 2 + LAMBDA; int x = i * 2 + X; int y = i * 2 + Y; double coslam = Math.Cos(lp[lam]); double cosphi = Math.Cos(lp[phi]); double sinphi = Math.Sin(lp[phi]); switch (_mode) { case Modes.NorthPole: case Modes.SouthPole: if (_mode == Modes.NorthPole) coslam = -coslam; double rho; xy[x] = (rho = Math.Abs(_mp - Proj.Mlfn(lp[phi], sinphi, cosphi, _en))) * Math.Sin(lp[lam]); xy[y] = rho * coslam; break; case Modes.Equitorial: case Modes.Oblique: if (Math.Abs(lp[lam]) < EPS10 && Math.Abs(lp[phi] - Phi0) < EPS10) { xy[x] = xy[y] = 0; break; } double t = Math.Atan2(OneEs * sinphi + Es * _n1 * _sinph0 * Math.Sqrt(1 - Es * sinphi * sinphi), cosphi); double ct = Math.Cos(t); double st = Math.Sin(t); double az = Math.Atan2(Math.Sin(lp[lam]) * ct, _cosph0 * st - _sinph0 * coslam * ct); double cA = Math.Cos(az); double sA = Math.Sin(az); double s = Math.Asin(Math.Abs(sA) < TOL ? (_cosph0 * st - _sinph0 * coslam * ct) / cA : Math.Sin(lp[lam]) * ct / sA); double h = _he * cA; double h2 = h * h; double c = _n1 * s * (1 + s * s * (-h2 * (1 - h2) / 6 + s * (_g * h * (1 - 2 * h2 * h2) / 8 + s * ((h2 * (4 - 7 * h2) - 3 * _g * _g * (1 - 7 * h2)) / 120 - s * _g * h / 48)))); xy[x] = c * sA; xy[y] = c * cA; break; } } } private void GuamForward(double[] lp, double[] xy, int startIndex, int numPoints) { for (int i = startIndex; i < startIndex + numPoints; i++) { int phi = i * 2 + PHI; int lam = i * 2 + LAMBDA; int x = i * 2 + X; int y = i * 2 + Y; double cosphi = Math.Cos(lp[phi]); double sinphi = Math.Sin(lp[phi]); double t = 1 / Math.Sqrt(1 - Es * sinphi * sinphi); xy[x] = lp[lam] * cosphi * t; xy[y] = Proj.Mlfn(lp[phi], sinphi, cosphi, _en) - _m1 + .5 * lp[lam] * lp[lam] * cosphi * sinphi * t; } } /// <inheritdoc /> protected override void SphericalInverse(double[] xy, double[] lp, int startIndex, int numPoints) { for (int i = startIndex; i < startIndex + numPoints; i++) { int phi = i * 2 + PHI; int lam = i * 2 + LAMBDA; int x = i * 2 + X; int y = i * 2 + Y; double cRh; if ((cRh = Proj.Hypot(xy[x], xy[y])) > Math.PI) { if (cRh - EPS10 > Math.PI) { lp[phi] = double.NaN; lp[lam] = double.NaN; continue; //throw new ProjectionException(20); } cRh = Math.PI; } else if (cRh < EPS10) { lp[phi] = Phi0; lp[lam] = 0; return; } if (_mode == Modes.Oblique || _mode == Modes.Equitorial) { double sinc = Math.Sin(cRh); double cosc = Math.Cos(cRh); if (_mode == Modes.Equitorial) { lp[phi] = Proj.Aasin(xy[y] * sinc / cRh); xy[x] *= sinc; xy[y] = cosc * cRh; } else { lp[phi] = Proj.Aasin(cosc * _sinph0 + xy[y] * sinc * _cosph0 / cRh); xy[y] = (cosc - _sinph0 * Math.Sin(lp[phi])) * cRh; xy[x] *= sinc * _cosph0; } lp[lam] = xy[y] == 0 ? 0 : Math.Atan2(xy[x], xy[y]); } else if (_mode == Modes.NorthPole) { lp[phi] = HALF_PI - cRh; lp[lam] = Math.Atan2(xy[x], -xy[y]); } else { lp[phi] = cRh - HALF_PI; lp[lam] = Math.Atan2(xy[x], xy[y]); } } } /// <inheritdoc /> protected override void EllipticalInverse(double[] xy, double[] lp, int startIndex, int numPoints) { if (_isGuam) { GuamInverse(xy, lp, startIndex, numPoints); } for (int i = startIndex; i < startIndex + numPoints; i++) { int phi = i * 2 + PHI; int lam = i * 2 + LAMBDA; int x = i * 2 + X; int y = i * 2 + Y; double c; if ((c = Proj.Hypot(xy[x], xy[y])) < EPS10) { lp[phi] = Phi0; lp[lam] = 0; return; } if (_mode == Modes.Oblique || _mode == Modes.Equitorial) { double az; double cosAz = Math.Cos(az = Math.Atan2(xy[x], xy[y])); double t = _cosph0 * cosAz; double b = Es * t / OneEs; double a = -b * t; b *= 3 * (1 - a) * _sinph0; double d = c / _n1; double e = d * (1 - d * d * (a * (1 + a) / 6 + b * (1 + 3 * a) * d / 24)); double f = 1 - e * e * (a / 2 + b * e / 6); double psi = Proj.Aasin(_sinph0 * Math.Cos(e) + t * Math.Sin(e)); lp[lam] = Proj.Aasin(Math.Sin(az) * Math.Sin(e) / Math.Cos(psi)); if ((t = Math.Abs(psi)) < EPS10) lp[phi] = 0; else if (Math.Abs(t - HALF_PI) < 0) lp[phi] = HALF_PI; else { lp[phi] = Math.Atan((1 - Es * f * _sinph0 / Math.Sin(psi)) * Math.Tan(psi) / OneEs); } } else { /* Polar */ lp[phi] = Proj.InvMlfn(_mode == Modes.NorthPole ? _mp - c : _mp + c, Es, _en); lp[lam] = Math.Atan2(xy[x], _mode == Modes.NorthPole ? -xy[y] : xy[y]); } } } private void GuamInverse(double[] xy, double[] lp, int startIndex, int numPoints) { for (int i = startIndex; i < startIndex + numPoints; i++) { int phi = i * 2 + PHI; int lam = i * 2 + LAMBDA; int x = i * 2 + X; int y = i * 2 + Y; double t = 0; int j; double x2 = 0.5 * xy[x] * xy[x]; lp[phi] = Phi0; for (j = 0; j < 3; ++j) { t = E * Math.Sin(lp[phi]); lp[phi] = Proj.InvMlfn(_m1 + xy[y] - x2 * Math.Tan(lp[phi]) * (t = Math.Sqrt(1 - t * t)), Es, _en); } lp[lam] = xy[x] * t / Math.Cos(lp[phi]); } } #endregion } }
namespace AutoMapper { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using Impl; using Internal; public class TypeMapFactory : ITypeMapFactory { private readonly Internal.IDictionary<Type, TypeInfo> _typeInfos = PlatformAdapter.Resolve<IDictionaryFactory>().CreateDictionary<Type, TypeInfo>(); public TypeMap CreateTypeMap(Type sourceType, Type destinationType, IMappingOptions options, MemberList memberList) { var sourceTypeInfo = GetTypeInfo(sourceType, options); var destTypeInfo = GetTypeInfo(destinationType, options.ShouldMapProperty, options.ShouldMapField, new MethodInfo[0]); var typeMap = new TypeMap(sourceTypeInfo, destTypeInfo, memberList); foreach (var destProperty in destTypeInfo.PublicWriteAccessors) { var members = new LinkedList<MemberInfo>(); if (MapDestinationPropertyToSource(members, sourceTypeInfo, destProperty.Name, options)) { var resolvers = members.Select(mi => mi.ToMemberGetter()); var destPropertyAccessor = destProperty.ToMemberAccessor(); typeMap.AddPropertyMap(destPropertyAccessor, resolvers.Cast<IValueResolver>()); } } if (!destinationType.IsAbstract() && destinationType.IsClass()) { foreach (var destCtor in destTypeInfo.Constructors.OrderByDescending(ci => ci.GetParameters().Length)) { if (MapDestinationCtorToSource(typeMap, destCtor, sourceTypeInfo, options)) { break; } } } return typeMap; } private bool MapDestinationCtorToSource(TypeMap typeMap, ConstructorInfo destCtor, TypeInfo sourceTypeInfo, IMappingOptions options) { var parameters = new List<ConstructorParameterMap>(); var ctorParameters = destCtor.GetParameters(); if (ctorParameters.Length == 0 || !options.ConstructorMappingEnabled) return false; foreach (var parameter in ctorParameters) { var members = new LinkedList<MemberInfo>(); var canResolve = MapDestinationPropertyToSource(members, sourceTypeInfo, parameter.Name, options); var resolvers = members.Select(mi => mi.ToMemberGetter()); var param = new ConstructorParameterMap(parameter, resolvers.ToArray(), canResolve); parameters.Add(param); } typeMap.AddConstructorMap(destCtor, parameters); return true; } private TypeInfo GetTypeInfo(Type type, IMappingOptions mappingOptions) { return GetTypeInfo(type, mappingOptions.ShouldMapProperty, mappingOptions.ShouldMapField, mappingOptions.SourceExtensionMethods); } private TypeInfo GetTypeInfo(Type type, Func<PropertyInfo, bool> shouldMapProperty, Func<FieldInfo, bool> shouldMapField, IEnumerable<MethodInfo> extensionMethodsToSearch) { return _typeInfos.GetOrAdd(type, t => new TypeInfo(type, shouldMapProperty, shouldMapField, extensionMethodsToSearch)); } private bool MapDestinationPropertyToSource(LinkedList<MemberInfo> resolvers, TypeInfo sourceType, string nameToSearch, IMappingOptions mappingOptions) { if (string.IsNullOrEmpty(nameToSearch)) return true; var sourceProperties = sourceType.PublicReadAccessors; var sourceNoArgMethods = sourceType.PublicNoArgMethods; var sourceNoArgExtensionMethods = sourceType.PublicNoArgExtensionMethods; MemberInfo resolver = FindTypeMember(sourceProperties, sourceNoArgMethods, sourceNoArgExtensionMethods, nameToSearch, mappingOptions); bool foundMatch = resolver != null; if (foundMatch) { resolvers.AddLast(resolver); } else { string[] matches = mappingOptions.DestinationMemberNamingConvention.SplittingExpression .Matches(nameToSearch) .Cast<Match>() .Select(m => m.Value) .ToArray(); for (int i = 1; (i <= matches.Length) && (!foundMatch); i++) { NameSnippet snippet = CreateNameSnippet(matches, i, mappingOptions); var valueResolver = FindTypeMember(sourceProperties, sourceNoArgMethods, sourceNoArgExtensionMethods, snippet.First, mappingOptions); if (valueResolver != null) { resolvers.AddLast(valueResolver); foundMatch = MapDestinationPropertyToSource(resolvers, GetTypeInfo(valueResolver.GetMemberType(), mappingOptions), snippet.Second, mappingOptions); if (!foundMatch) { resolvers.RemoveLast(); } } } } return foundMatch; } private static MemberInfo FindTypeMember(IEnumerable<MemberInfo> modelProperties, IEnumerable<MethodInfo> getMethods, IEnumerable<MethodInfo> getExtensionMethods, string nameToSearch, IMappingOptions mappingOptions) { MemberInfo pi = modelProperties.FirstOrDefault(prop => NameMatches(prop.Name, nameToSearch, mappingOptions)); if (pi != null) return pi; MethodInfo mi = getMethods.FirstOrDefault(m => NameMatches(m.Name, nameToSearch, mappingOptions)); if (mi != null) return mi; mi = getExtensionMethods.FirstOrDefault(m => NameMatches(m.Name, nameToSearch, mappingOptions)); if (mi != null) return mi; return null; } private static bool NameMatches(string memberName, string nameToMatch, IMappingOptions mappingOptions) { var possibleSourceNames = PossibleNames(memberName, mappingOptions.Aliases, mappingOptions.MemberNameReplacers, mappingOptions.Prefixes, mappingOptions.Postfixes); var possibleDestNames = PossibleNames(nameToMatch, mappingOptions.Aliases, mappingOptions.MemberNameReplacers, mappingOptions.DestinationPrefixes, mappingOptions.DestinationPostfixes); var all = from sourceName in possibleSourceNames from destName in possibleDestNames select new {sourceName, destName}; return all.Any(pair => String.Compare(pair.sourceName, pair.destName, StringComparison.OrdinalIgnoreCase) == 0); } private static IEnumerable<string> PossibleNames(string memberName, IEnumerable<AliasedMember> aliases, IEnumerable<MemberNameReplacer> memberNameReplacers, IEnumerable<string> prefixes, IEnumerable<string> postfixes) { if (string.IsNullOrEmpty(memberName)) yield break; yield return memberName; foreach ( var alias in aliases.Where(alias => String.Equals(memberName, alias.Member, StringComparison.Ordinal))) { yield return alias.Alias; } if (memberNameReplacers.Any()) { string aliasName = memberName; foreach (var nameReplacer in memberNameReplacers) { aliasName = aliasName.Replace(nameReplacer.OriginalValue, nameReplacer.NewValue); } yield return aliasName; } foreach (var prefix in prefixes.Where(prefix => memberName.StartsWith(prefix, StringComparison.Ordinal))) { var withoutPrefix = memberName.Substring(prefix.Length); yield return withoutPrefix; foreach ( var postfix in postfixes.Where(postfix => withoutPrefix.EndsWith(postfix, StringComparison.Ordinal)) ) { yield return withoutPrefix.Remove(withoutPrefix.Length - postfix.Length); } } foreach (var postfix in postfixes.Where(postfix => memberName.EndsWith(postfix, StringComparison.Ordinal))) { yield return memberName.Remove(memberName.Length - postfix.Length); } } private NameSnippet CreateNameSnippet(IEnumerable<string> matches, int i, IMappingOptions mappingOptions) { return new NameSnippet { First = String.Join(mappingOptions.SourceMemberNamingConvention.SeparatorCharacter, matches.Take(i).ToArray()), Second = String.Join(mappingOptions.SourceMemberNamingConvention.SeparatorCharacter, matches.Skip(i).ToArray()) }; } private class NameSnippet { public string First { get; set; } public string Second { get; set; } } } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; namespace Amazon.ElasticMapReduce.Model { /// <summary> /// <para>Configuration defining a new instance group.</para> /// </summary> public class InstanceGroupConfig { private string name; private string market; private string instanceRole; private string bidPrice; private string instanceType; private int? instanceCount; /// <summary> /// Friendly name given to the instance group. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>0 - 256</description> /// </item> /// <item> /// <term>Pattern</term> /// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description> /// </item> /// </list> /// </para> /// </summary> public string Name { get { return this.name; } set { this.name = value; } } /// <summary> /// Sets the Name property /// </summary> /// <param name="name">The value to set for the Name property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public InstanceGroupConfig WithName(string name) { this.name = name; return this; } // Check to see if Name property is set internal bool IsSetName() { return this.name != null; } /// <summary> /// Market type of the Amazon EC2 instances used to create a cluster node. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Allowed Values</term> /// <description>ON_DEMAND, SPOT</description> /// </item> /// </list> /// </para> /// </summary> public string Market { get { return this.market; } set { this.market = value; } } /// <summary> /// Sets the Market property /// </summary> /// <param name="market">The value to set for the Market property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public InstanceGroupConfig WithMarket(string market) { this.market = market; return this; } // Check to see if Market property is set internal bool IsSetMarket() { return this.market != null; } /// <summary> /// The role of the instance group in the cluster. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Allowed Values</term> /// <description>MASTER, CORE, TASK</description> /// </item> /// </list> /// </para> /// </summary> public string InstanceRole { get { return this.instanceRole; } set { this.instanceRole = value; } } /// <summary> /// Sets the InstanceRole property /// </summary> /// <param name="instanceRole">The value to set for the InstanceRole property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public InstanceGroupConfig WithInstanceRole(string instanceRole) { this.instanceRole = instanceRole; return this; } // Check to see if InstanceRole property is set internal bool IsSetInstanceRole() { return this.instanceRole != null; } /// <summary> /// Bid price for each Amazon EC2 instance in the instance group when launching nodes as Spot Instances, expressed in USD. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>0 - 256</description> /// </item> /// <item> /// <term>Pattern</term> /// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description> /// </item> /// </list> /// </para> /// </summary> public string BidPrice { get { return this.bidPrice; } set { this.bidPrice = value; } } /// <summary> /// Sets the BidPrice property /// </summary> /// <param name="bidPrice">The value to set for the BidPrice property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public InstanceGroupConfig WithBidPrice(string bidPrice) { this.bidPrice = bidPrice; return this; } // Check to see if BidPrice property is set internal bool IsSetBidPrice() { return this.bidPrice != null; } /// <summary> /// The Amazon EC2 instance type for all instances in the instance group. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 256</description> /// </item> /// <item> /// <term>Pattern</term> /// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description> /// </item> /// </list> /// </para> /// </summary> public string InstanceType { get { return this.instanceType; } set { this.instanceType = value; } } /// <summary> /// Sets the InstanceType property /// </summary> /// <param name="instanceType">The value to set for the InstanceType property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public InstanceGroupConfig WithInstanceType(string instanceType) { this.instanceType = instanceType; return this; } // Check to see if InstanceType property is set internal bool IsSetInstanceType() { return this.instanceType != null; } /// <summary> /// Target number of instances for the instance group. /// /// </summary> public int InstanceCount { get { return this.instanceCount ?? default(int); } set { this.instanceCount = value; } } /// <summary> /// Sets the InstanceCount property /// </summary> /// <param name="instanceCount">The value to set for the InstanceCount property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public InstanceGroupConfig WithInstanceCount(int instanceCount) { this.instanceCount = instanceCount; return this; } // Check to see if InstanceCount property is set internal bool IsSetInstanceCount() { return this.instanceCount.HasValue; } } }
using System; using System.Collections.Generic; using Csla; using ParentLoad.DataAccess; using ParentLoad.DataAccess.ERCLevel; namespace ParentLoad.Business.ERCLevel { /// <summary> /// B01_ContinentColl (editable root list).<br/> /// This is a generated base class of <see cref="B01_ContinentColl"/> business object. /// </summary> /// <remarks> /// The items of the collection are <see cref="B02_Continent"/> objects. /// </remarks> [Serializable] public partial class B01_ContinentColl : BusinessListBase<B01_ContinentColl, B02_Continent> { #region Collection Business Methods /// <summary> /// Removes a <see cref="B02_Continent"/> item from the collection. /// </summary> /// <param name="continent_ID">The Continent_ID of the item to be removed.</param> public void Remove(int continent_ID) { foreach (var b02_Continent in this) { if (b02_Continent.Continent_ID == continent_ID) { Remove(b02_Continent); break; } } } /// <summary> /// Determines whether a <see cref="B02_Continent"/> item is in the collection. /// </summary> /// <param name="continent_ID">The Continent_ID of the item to search for.</param> /// <returns><c>true</c> if the B02_Continent is a collection item; otherwise, <c>false</c>.</returns> public bool Contains(int continent_ID) { foreach (var b02_Continent in this) { if (b02_Continent.Continent_ID == continent_ID) { return true; } } return false; } /// <summary> /// Determines whether a <see cref="B02_Continent"/> item is in the collection's DeletedList. /// </summary> /// <param name="continent_ID">The Continent_ID of the item to search for.</param> /// <returns><c>true</c> if the B02_Continent is a deleted collection item; otherwise, <c>false</c>.</returns> public bool ContainsDeleted(int continent_ID) { foreach (var b02_Continent in DeletedList) { if (b02_Continent.Continent_ID == continent_ID) { return true; } } return false; } #endregion #region Find Methods /// <summary> /// Finds a <see cref="B02_Continent"/> item of the <see cref="B01_ContinentColl"/> collection, based on item key properties. /// </summary> /// <param name="continent_ID">The Continent_ID.</param> /// <returns>A <see cref="B02_Continent"/> object.</returns> public B02_Continent FindB02_ContinentByParentProperties(int continent_ID) { for (var i = 0; i < this.Count; i++) { if (this[i].Continent_ID.Equals(continent_ID)) { return this[i]; } } return null; } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="B01_ContinentColl"/> collection. /// </summary> /// <returns>A reference to the created <see cref="B01_ContinentColl"/> collection.</returns> public static B01_ContinentColl NewB01_ContinentColl() { return DataPortal.Create<B01_ContinentColl>(); } /// <summary> /// Factory method. Loads a <see cref="B01_ContinentColl"/> collection. /// </summary> /// <returns>A reference to the fetched <see cref="B01_ContinentColl"/> collection.</returns> public static B01_ContinentColl GetB01_ContinentColl() { return DataPortal.Fetch<B01_ContinentColl>(); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="B01_ContinentColl"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public B01_ContinentColl() { // Use factory methods and do not use direct creation. var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; AllowNew = true; AllowEdit = true; AllowRemove = true; RaiseListChangedEvents = rlce; } #endregion #region Data Access /// <summary> /// Loads a <see cref="B01_ContinentColl"/> collection from the database. /// </summary> protected void DataPortal_Fetch() { var args = new DataPortalHookArgs(); OnFetchPre(args); using (var dalManager = DalFactoryParentLoad.GetManager()) { var dal = dalManager.GetProvider<IB01_ContinentCollDal>(); var data = dal.Fetch(); Fetch(data); LoadCollection(dal); } OnFetchPost(args); } private void LoadCollection(IB01_ContinentCollDal dal) { if (this.Count > 0) this[0].FetchChildren(dal); } /// <summary> /// Loads all <see cref="B01_ContinentColl"/> collection items from the given list of B02_ContinentDto. /// </summary> /// <param name="data">The list of <see cref="B02_ContinentDto"/>.</param> private void Fetch(List<B02_ContinentDto> data) { var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; foreach (var dto in data) { Add(B02_Continent.GetB02_Continent(dto)); } RaiseListChangedEvents = rlce; } /// <summary> /// Updates in the database all changes made to the <see cref="B01_ContinentColl"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Update() { using (var dalManager = DalFactoryParentLoad.GetManager()) { base.Child_Update(); } } #endregion #region DataPortal Hooks /// <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); #endregion } }
#if !DISABLE_REACTIVEUI using ReactiveUI; #else using System.Windows.Threading; using System.Threading; #endif using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Reactive; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reactive.Linq; namespace GitHub.Collections { /// <summary> /// TrackingCollection is a specialization of ObservableCollection that gets items from /// an observable sequence and updates its contents in such a way that two updates to /// the same object (as defined by an Equals call) will result in one object on /// the list being updated (as opposed to having two different instances of the object /// added to the list). /// It is always sorted, either via the supplied comparer or using the default comparer /// for T /// </summary> /// <typeparam name="T"></typeparam> public class TrackingCollection<T> : ObservableCollection<T>, ITrackingCollection<T>, IDisposable where T : class, ICopyable<T>, IComparable<T> { enum TheAction { None, Move, Add, Insert, Remove } bool isChanging; readonly CompositeDisposable disposables = new CompositeDisposable(); IObservable<T> source; IObservable<T> sourceQueue; Func<T, T, int> comparer; Func<T, int, IList<T>, bool> filter; readonly IScheduler scheduler; ConcurrentQueue<ActionData> queue; readonly List<T> original = new List<T>(); #if DEBUG public IList<T> DebugInternalList => original; #endif // lookup optimizations // for speeding up IndexOf in the unfiltered list readonly Dictionary<T, int> sortedIndexCache = new Dictionary<T, int>(); // for speeding up IndexOf in the filtered list readonly Dictionary<T, int> filteredIndexCache = new Dictionary<T, int>(); TimeSpan delay; TimeSpan requestedDelay; readonly TimeSpan fuzziness; public TimeSpan ProcessingDelay { get { return requestedDelay; } set { requestedDelay = value; delay = value; } } public TrackingCollection(Func<T, T, int> comparer = null, Func<T, int, IList<T>, bool> filter = null, IScheduler scheduler = null) { queue = new ConcurrentQueue<ActionData>(); ProcessingDelay = TimeSpan.FromMilliseconds(10); fuzziness = TimeSpan.FromMilliseconds(1); #if DISABLE_REACTIVEUI this.scheduler = GetScheduler(scheduler); #else this.scheduler = scheduler ?? RxApp.MainThreadScheduler; #endif this.comparer = comparer ?? Comparer<T>.Default.Compare; this.filter = filter; } public TrackingCollection(IObservable<T> source, Func<T, T, int> comparer = null, Func<T, int, IList<T>, bool> filter = null, IScheduler scheduler = null) : this(comparer, filter, scheduler) { Listen(source); } /// <summary> /// Sets up an observable as source for the collection. /// </summary> /// <param name="obs"></param> /// <returns>An observable that will return all the items that are /// fed via the original observer, for further processing by user code /// if desired</returns> public IObservable<T> Listen(IObservable<T> obs) { if (disposed) throw new ObjectDisposedException("TrackingCollection"); sourceQueue = obs .Do(data => queue.Enqueue(new ActionData(data))); source = Observable .Generate(StartQueue(), i => !disposed, i => i + 1, i => GetFromQueue(), i => delay ) .Where(data => data.Item != null) .ObserveOn(scheduler) .Select(x => ProcessItem(x, original)) // if we're removing an item that doesn't exist, ignore it .Where(data => !(data.TheAction == TheAction.Remove && data.OldPosition < 0)) .Select(SortedNone) .Select(SortedAdd) .Select(SortedInsert) .Select(SortedMove) .Select(SortedRemove) .Select(CheckFilter) .Select(FilteredAdd) .Select(CalculateIndexes) .Select(FilteredNone) .Select(FilteredInsert) .Select(FilteredMove) .Select(FilteredRemove) .TimeInterval() .Select(UpdateProcessingDelay) .Select(data => data.Item) .Publish() .RefCount(); return source; } /// <summary> /// Set a new comparer for the existing data. This will cause the /// collection to be resorted and refiltered. /// </summary> /// <param name="theComparer">The comparer method for sorting, or null if not sorting</param> public void SetComparer(Func<T, T, int> theComparer) { if (disposed) throw new ObjectDisposedException("TrackingCollection"); SetAndRecalculateSort(theComparer); SetAndRecalculateFilter(filter); } /// <summary> /// Set a new filter. This will cause the collection to be filtered /// </summary> /// <param name="theFilter">The new filter, or null to not have any filtering</param> public void SetFilter(Func<T, int, IList<T>, bool> theFilter) { if (disposed) throw new ObjectDisposedException("TrackingCollection"); SetAndRecalculateFilter(theFilter); } public IDisposable Subscribe() { if (source == null) throw new InvalidOperationException("No source observable has been set. Call Listen or pass an observable to the constructor"); if (disposed) throw new ObjectDisposedException("TrackingCollection"); disposables.Add(source.Subscribe()); return this; } public IDisposable Subscribe(Action<T> onNext, Action onCompleted) { if (source == null) throw new InvalidOperationException("No source observable has been set. Call Listen or pass an observable to the constructor"); if (disposed) throw new ObjectDisposedException("TrackingCollection"); disposables.Add(source.Subscribe(onNext, onCompleted)); return this; } public void AddItem(T item) { if (disposed) throw new ObjectDisposedException("TrackingCollection"); queue.Enqueue(new ActionData(item)); } public void RemoveItem(T item) { if (disposed) throw new ObjectDisposedException("TrackingCollection"); queue.Enqueue(new ActionData(TheAction.Remove, item)); } void SetAndRecalculateSort(Func<T, T, int> theComparer) { comparer = theComparer ?? Comparer<T>.Default.Compare; RecalculateSort(original, 0, original.Count); } void RecalculateSort(List<T> list, int start, int end) { list.Sort(start, end, new LambdaComparer<T>(comparer)); } void SetAndRecalculateFilter(Func<T, int, IList<T>, bool> newFilter) { ClearItems(); filter = newFilter; RecalculateFilter(original, 0, 0, original.Count, true); } #region Source pipeline processing ActionData CheckFilter(ActionData data) { var isIncluded = true; if (data.TheAction == TheAction.Remove) isIncluded = false; else if (filter != null) isIncluded = filter(data.Item, data.Position, this); return new ActionData(data, isIncluded); } int StartQueue() { disposables.Add(sourceQueue.Subscribe()); return 0; } ActionData GetFromQueue() { try { ActionData d = ActionData.Default; if (queue?.TryDequeue(out d) ?? false) return d; } catch { } return ActionData.Default; } ActionData ProcessItem(ActionData data, List<T> list) { ActionData ret; T item = data.Item; var idx = GetIndexUnfiltered(item); if (data.TheAction == TheAction.Remove) return new ActionData(TheAction.Remove, original, item, null, idx - 1, idx); if (idx >= 0) { var old = list[idx]; var comparison = comparer(item, old); // no sorting to be done, just replacing the element in-place if (comparison == 0) ret = new ActionData(TheAction.None, list, item, null, idx, idx); else // element has moved, save the original object, because we want to update its contents and move it // but not overwrite the instance. ret = new ActionData(TheAction.Move, list, item, old, comparison, idx); } // the element doesn't exist yet // figure out whether we're larger than the last element or smaller than the first or // if we have to place the new item somewhere in the middle else if (list.Count > 0) { if (comparer(list[0], item) >= 0) ret = new ActionData(TheAction.Insert, list, item, null, 0, -1); else if (comparer(list[list.Count - 1], item) <= 0) ret = new ActionData(TheAction.Add, list, item, null, list.Count, -1); // this happens if the original observable is not sorted, or it's sorting order doesn't // match the comparer that has been set else { idx = BinarySearch(list, item, comparer); if (idx < 0) idx = ~idx; ret = new ActionData(TheAction.Insert, list, item, null, idx, -1); } } else ret = new ActionData(TheAction.Add, list, item, null, list.Count, -1); return ret; } ActionData SortedNone(ActionData data) { if (data.TheAction != TheAction.None) return data; data.List[data.OldPosition].CopyFrom(data.Item); return data; } ActionData SortedAdd(ActionData data) { if (data.TheAction != TheAction.Add) return data; data.List.Add(data.Item); return data; } ActionData SortedInsert(ActionData data) { if (data.TheAction != TheAction.Insert) return data; data.List.Insert(data.Position, data.Item); UpdateIndexCache(data.Position, data.List.Count, data.List, sortedIndexCache); return data; } ActionData SortedMove(ActionData data) { if (data.TheAction != TheAction.Move) return data; data.OldItem.CopyFrom(data.Item); var pos = FindNewPositionForItem(data.OldPosition, data.Position < 0, data.List, comparer, sortedIndexCache); // the old item is the one moving around return new ActionData(data, pos); } ActionData SortedRemove(ActionData data) { if (data.TheAction != TheAction.Remove) return data; // unfiltered list update sortedIndexCache.Remove(data.Item); UpdateIndexCache(data.List.Count - 1, data.OldPosition, data.List, sortedIndexCache); original.Remove(data.Item); return data; } ActionData FilteredAdd(ActionData data) { if (data.TheAction != TheAction.Add) return data; if (data.IsIncluded) InternalAddItem(data.Item); return data; } ActionData CalculateIndexes(ActionData data) { var index = GetIndexFiltered(data.Item); var indexPivot = GetLiveListPivot(data.Position, data.List); return new ActionData(data, index, indexPivot); } ActionData FilteredNone(ActionData data) { if (data.TheAction != TheAction.None) return data; // nothing has changed as far as the live list is concerned if ((data.IsIncluded && data.Index >= 0) || !data.IsIncluded && data.Index < 0) return data; // wasn't on the live list, but it is now if (data.IsIncluded && data.Index < 0) InsertAndRecalculate(data.List, data.Item, data.IndexPivot, data.Position, false); // was on the live list, it's not anymore else RemoveAndRecalculate(data.List, data.Item, data.IndexPivot, data.Position); return data; } ActionData FilteredInsert(ActionData data) { if (data.TheAction != TheAction.Insert) return data; if (data.IsIncluded) InsertAndRecalculate(data.List, data.Item, data.IndexPivot, data.Position, false); // need to recalculate the filter because inserting an object (even if it's not itself visible) // can change visibility of other items after it else RecalculateFilter(data.List, data.IndexPivot, data.Position, data.List.Count); return data; } /// <summary> /// Checks if the object being moved affects the filtered list in any way and update /// the list accordingly /// </summary> /// <param name="data"></param> /// <returns></returns> ActionData FilteredMove(ActionData data) { if (data.TheAction != TheAction.Move) return data; var start = data.OldPosition < data.Position ? data.OldPosition : data.Position; var end = data.Position > data.OldPosition ? data.Position : data.OldPosition; // if there's no filter, the filtered list is equal to the unfiltered list, just move if (filter == null) { MoveAndRecalculate(data.List, data.Index, data.IndexPivot, start, end); return data; } var filteredListChanged = false; var startPosition = Int32.MaxValue; // check if the filtered list is affected indirectly by the move (eg., if the filter involves position of items, // moving an item outside the bounds of the filter can affect the items being currently shown/hidden) if (Count > 0) { startPosition = GetIndexUnfiltered(this[0]); var endPosition = GetIndexUnfiltered(this[Count - 1]); // true if the filtered list has been indirectly affected by this objects' move filteredListChanged = (!filter(this[0], startPosition, this) || !filter(this[Count - 1], endPosition, this)); } // the move caused the object to not be visible in the live list anymore, so remove if (!data.IsIncluded && data.Index >= 0) RemoveAndRecalculate(data.List, data.Item, filteredListChanged ? 0 : (data.Position < data.OldPosition ? data.IndexPivot : data.Index), filteredListChanged ? startPosition : start); // the move caused the object to become visible in the live list, insert it // and recalculate all the other things on the live list from the start position else if (data.IsIncluded && data.Index < 0) { start = startPosition < start ? startPosition : start; InsertAndRecalculate(data.List, data.Item, data.IndexPivot, start, filteredListChanged); } // move the object and recalculate the filter between the bounds of the move else if (data.IsIncluded) MoveAndRecalculate(data.List, data.Index, data.IndexPivot, start, end); // recalculate the filter for every item, there's no way of telling what changed else if (filteredListChanged) RecalculateFilter(data.List, 0, 0, data.List.Count); return data; } /// <summary> /// Checks if the object being moved affects the filtered list in any way and update /// the list accordingly /// </summary> /// <param name="data"></param> /// <returns></returns> ActionData FilteredRemove(ActionData data) { if (data.TheAction != TheAction.Remove) return data; var filteredListChanged = false; var startPosition = Int32.MaxValue; // check if the filtered list is affected indirectly by the move (eg., if the filter involves position of items, // removing an item outside the bounds of the filter can affect the items being currently shown/hidden) if (filter != null && Count > 0) { startPosition = GetIndexUnfiltered(this[0]); var endPosition = GetIndexUnfiltered(this[Count - 1]); // true if the filtered list has been indirectly affected by this objects' removal filteredListChanged = (!filter(this[0], startPosition, this) || !filter(this[Count - 1], endPosition, this)); } // remove the object if it was visible in the first place if (data.Index >= 0) RemoveAndRecalculate(data.List, data.Item, filteredListChanged ? 0 : data.IndexPivot, filteredListChanged ? startPosition : data.Position); // recalculate the filter for every item, there's no way of telling what changed else if (filteredListChanged) RecalculateFilter(data.List, 0, 0, data.List.Count); return data; } /// <summary> /// Compensate time between items by time taken in processing them /// so that the average time between an item being processed /// is +- the requested processing delay. /// </summary> ActionData UpdateProcessingDelay(TimeInterval<ActionData> data) { if (requestedDelay == TimeSpan.Zero) return data.Value; var time = data.Interval; if (time > requestedDelay + fuzziness) delay -= time - requestedDelay; else if (time < requestedDelay + fuzziness) delay += requestedDelay - time; delay = delay < TimeSpan.Zero ? TimeSpan.Zero : delay; return data.Value; } #endregion /// <summary> /// Insert an object into the live list at liveListCurrentIndex and recalculate /// positions for all objects from the position /// </summary> /// <param name="list">The unfiltered, sorted list of items</param> /// <param name="item"></param> /// <param name="index"></param> /// <param name="position">Index of the unfiltered, sorted list to start reevaluating the filtered list</param> /// <param name="rescanAll">Whether the whole filtered list needs to be reevaluated</param> void InsertAndRecalculate(IList<T> list, T item, int index, int position, bool rescanAll) { InternalInsertItem(item, index); if (rescanAll) index = 0; // reevaluate filter from the start of the filtered list else { // if the item in position is different from the item we're inserting, // that means that this insertion might require some filter reevaluation of items // before the one we're inserting. We need to figure out if the item in position // is in the filtered list, and if it is, then that's where we need to start // reevaluating the filter. If it isn't, then there's no need to reevaluate from // there var needToBacktrack = false; if (!Equals(item, list[position])) { var idx = GetIndexFiltered(list[position]); if (idx >= 0) { needToBacktrack = true; index = idx; } } if (!needToBacktrack) { index++; position++; } } RecalculateFilter(list, index, position, list.Count); } /// <summary> /// Remove an object from the live list at index and recalculate positions /// for all objects after that /// </summary> /// <param name="list">The unfiltered, sorted list of items</param> /// <param name="item"></param> /// <param name="index">The index in the live list</param> /// <param name="position">The position in the sorted, unfiltered list</param> void RemoveAndRecalculate(IList<T> list, T item, int index, int position) { InternalRemoveItem(item); RecalculateFilter(list, index, position, list.Count); } /// <summary> /// Move an object in the live list and recalculate positions /// for all objects between the bounds of the affected indexes /// </summary> /// <param name="list">The unfiltered, sorted list of items</param> /// <param name="from">Index in the live list where the object is</param> /// <param name="to">Index in the live list where the object is going to be</param> /// <param name="start">Index in the unfiltered, sorted list to start reevaluating the filter</param> /// <param name="end">Index in the unfiltered, sorted list to end reevaluating the filter</param> void MoveAndRecalculate(IList<T> list, int from, int to, int start, int end) { if (start > end) throw new ArgumentOutOfRangeException(nameof(start), "Start cannot be bigger than end, evaluation of the filter goes forward."); InternalMoveItem(from, to); start++; RecalculateFilter(list, (from < to ? from : to) + 1, start, end); } /// <summary> /// Go through the list of objects and adjust their "visibility" in the live list /// (by removing/inserting as needed). /// </summary> /// <param name="list">The unfiltered, sorted list of items</param> /// <param name="index">Index in the live list corresponding to the start index of the object list</param> /// <param name="start">Start index of the object list</param> /// <param name="end">End index of the object list</param> /// <param name="force">If there's no filter set, this method does nothing. Pass true to force a reevaluation /// of the whole list regardless of filter.</param> void RecalculateFilter(IList<T> list, int index, int start, int end, bool force = false) { if (filter == null && !force) return; for (int i = start; i < end; i++) { var item = list[i]; var idx = GetIndexFiltered(item); var isIncluded = filter != null ? filter(item, i, this) : true; // element is included if (isIncluded) { // element wasn't included before if (idx < 0) { if (index == Count) InternalAddItem(item); else InternalInsertItem(item, index); } index++; } // element is not included and was before else if (idx >= 0) InternalRemoveItem(item); } } /// <summary> /// Get the index in the live list of an object at position. /// This will scan back to the beginning of the live list looking for /// the closest left neighbour and return the position after that. /// </summary> /// <param name="position">The index of an object in the unfiltered, sorted list that we want to map to the filtered live list</param> /// <param name="list">The unfiltered, sorted list of items</param> /// <returns></returns> int GetLiveListPivot(int position, IList<T> list) { var index = -1; if (position > 0) { for (int i = position - 1; i >= 0; i--) { index = GetIndexFiltered(list[i]); if (index >= 0) { // found an element to the left of what we want, so now we know the index where to start // manipulating the list index++; break; } } } // there was no element to the left of the one we want, start at the beginning of the live list if (index < 0) index = 0; return index; } /// <summary> /// Adds an item to the filtered list /// </summary> void InternalAddItem(T item) { isChanging = true; Add(item); } /// <summary> /// Inserts an item into the filtered list /// </summary> void InternalInsertItem(T item, int position) { isChanging = true; Insert(position, item); } protected override void InsertItem(int index, T item) { if (!isChanging) throw new InvalidOperationException("Collection cannot be changed manually."); isChanging = false; filteredIndexCache.Add(item, index); UpdateIndexCache(index, Count, Items, filteredIndexCache); base.InsertItem(index, item); } /// <summary> /// Removes an item from the filtered list /// </summary> void InternalRemoveItem(T item) { int idx; // this only happens if the cache is lazy, which is not the case at this time if (!filteredIndexCache.TryGetValue(item, out idx)) { Debug.Assert(false); return; } isChanging = true; RemoveItem(idx); } protected override void RemoveItem(int index) { if (!isChanging) throw new InvalidOperationException("Items cannot be removed from the collection except via RemoveItem(T)."); isChanging = false; filteredIndexCache.Remove(this[index]); UpdateIndexCache(Count - 1, index, Items, filteredIndexCache); base.RemoveItem(index); } /// <summary> /// Moves an item in the filtered list /// </summary> void InternalMoveItem(int positionFrom, int positionTo) { isChanging = true; positionTo = positionFrom < positionTo ? positionTo - 1 : positionTo; Move(positionFrom, positionTo); } protected override void MoveItem(int oldIndex, int newIndex) { if (!isChanging) throw new InvalidOperationException("Collection cannot be changed manually."); isChanging = false; if (oldIndex != newIndex) { UpdateIndexCache(newIndex, oldIndex, Items, filteredIndexCache); filteredIndexCache[this[oldIndex]] = newIndex; } base.MoveItem(oldIndex, newIndex); } protected override void ClearItems() { filteredIndexCache.Clear(); base.ClearItems(); } /// <summary> /// The filtered list always has a cache filled up with /// all the items that are visible. /// </summary> int GetIndexFiltered(T item) { int idx; if (filteredIndexCache.TryGetValue(item, out idx)) return idx; return -1; } /// <summary> /// The unfiltered has a lazy cache that gets filled /// up when something is looked up. /// </summary> /// <param name="item"></param> /// <returns></returns> int GetIndexUnfiltered(T item) { int ret; if (!sortedIndexCache.TryGetValue(item, out ret)) { ret = original.IndexOf(item); if (ret >= 0) sortedIndexCache.Add(item, ret); } return ret; } /// <summary> /// When items get moved/inserted/deleted, update the indexes in the cache. /// If start &lt; end, we're inserting an item and want to shift all the indexes /// between start and end to the right (+1) /// If start &gt; end, we're removing an item and want to shift all /// indexes to the left (-1). /// </summary> static void UpdateIndexCache(int start, int end, IList<T> list, Dictionary<T, int> indexCache) { var change = end < start ? -1 : 1; for (int i = start; i != end; i += change) if (indexCache.ContainsKey(list[i])) indexCache[list[i]] += change; } static int FindNewPositionForItem(int idx, bool lower, IList<T> list, Func<T, T, int> comparer, Dictionary<T, int> indexCache) { var i = idx; if (lower) // replacing element has lower sorting order, find the correct spot towards the beginning for (var pos = i - 1; i > 0 && comparer(list[i], list[pos]) < 0; i--, pos--) { Swap(list, i, pos); SwapIndex(list, i, 1, indexCache); } else // replacing element has higher sorting order, find the correct spot towards the end for (var pos = i + 1; i < list.Count - 1 && comparer(list[i], list[pos]) > 0; i++, pos++) { Swap(list, i, pos); SwapIndex(list, i, -1, indexCache); } indexCache[list[i]] = i; return i; } /// <summary> /// Swap two elements /// </summary> static void Swap(IList<T> list, int left, int right) { var l = list[left]; list[left] = list[right]; list[right] = l; } static void SwapIndex(IList<T> list, int pos, int change, Dictionary<T, int> cache) { if (cache.ContainsKey(list[pos])) cache[list[pos]] += change; } static int BinarySearch(List<T> list, T item, Func<T, T, int> comparer) { return list.BinarySearch(item, new LambdaComparer<T>(comparer)); } #if DISABLE_REACTIVEUI static IScheduler GetScheduler(IScheduler scheduler) { Dispatcher d = null; if (scheduler == null) d = Dispatcher.FromThread(Thread.CurrentThread); return scheduler ?? (d != null ? new DispatcherScheduler(d) : null as IScheduler) ?? CurrentThreadScheduler.Instance; } #endif bool disposed = false; void Dispose(bool disposing) { if (disposing) { if (!disposed) { disposed = true; queue = null; disposables.Dispose(); } } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } struct ActionData { public static readonly ActionData Default = new ActionData(null); readonly public TheAction TheAction; readonly public int Position; readonly public int OldPosition; readonly public int Index; readonly public int IndexPivot; readonly public bool IsIncluded; readonly public T Item; readonly public T OldItem; readonly public List<T> List; public ActionData(ActionData other, int index, int indexPivot) : this(other.TheAction, other.List, other.Item, other.OldItem, other.Position, other.OldPosition, index, indexPivot, other.IsIncluded) { } public ActionData(ActionData other, int position) : this(other.TheAction, other.List, other.Item, other.OldItem, position, other.OldPosition, other.Index, other.IndexPivot, other.IsIncluded) { } public ActionData(ActionData other, bool isIncluded) : this(other.TheAction, other.List, other.Item, other.OldItem, other.Position, other.OldPosition, other.Index, other.IndexPivot, isIncluded) { } public ActionData(TheAction action, List<T> list, T item, T oldItem, int position, int oldPosition) : this(action, list, item, oldItem, position, oldPosition, -1, -1, false) { } public ActionData(T item) : this(TheAction.None, item) { } public ActionData(TheAction action, T item) : this(action, null, item, null, -1, -1, -1, -1, false) { } public ActionData(TheAction action, List<T> list, T item, T oldItem, int position, int oldPosition, int index, int indexPivot, bool isIncluded) { TheAction = action; Item = item; OldItem = oldItem; Position = position; OldPosition = oldPosition; List = list; Index = index; IndexPivot = indexPivot; IsIncluded = isIncluded; } } } }
/* * Copyright (c) 2008, openmetaverse.org, http://opensimulator.org/ * All rights reserved. * * - Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Neither the name of the openmetaverse.org nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Threading; using System.Collections.Generic; namespace OpenSim.Framework { /// <summary> /// A double dictionary that is thread abort safe. /// </summary> /// <remarks> /// This adapts OpenMetaverse.DoubleDictionary to be thread-abort safe by acquiring ReaderWriterLockSlim within /// a finally section (which can't be interrupted by Thread.Abort()). /// </remarks> public class DoubleDictionaryThreadAbortSafe<TKey1, TKey2, TValue> { Dictionary<TKey1, TValue> Dictionary1; Dictionary<TKey2, TValue> Dictionary2; ReaderWriterLockSlim rwLock = new ReaderWriterLockSlim(); public DoubleDictionaryThreadAbortSafe() { Dictionary1 = new Dictionary<TKey1,TValue>(); Dictionary2 = new Dictionary<TKey2,TValue>(); } public DoubleDictionaryThreadAbortSafe(int capacity) { Dictionary1 = new Dictionary<TKey1, TValue>(capacity); Dictionary2 = new Dictionary<TKey2, TValue>(capacity); } public void Add(TKey1 key1, TKey2 key2, TValue value) { bool gotLock = false; try { // Avoid an asynchronous Thread.Abort() from possibly never existing an acquired lock by placing // the acquision inside the main try. The inner finally block is needed because thread aborts cannot // interrupt code in these blocks (hence gotLock is guaranteed to be set correctly). try {} finally { rwLock.EnterWriteLock(); gotLock = true; } if (Dictionary1.ContainsKey(key1)) { if (!Dictionary2.ContainsKey(key2)) throw new ArgumentException("key1 exists in the dictionary but not key2"); } else if (Dictionary2.ContainsKey(key2)) { if (!Dictionary1.ContainsKey(key1)) throw new ArgumentException("key2 exists in the dictionary but not key1"); } Dictionary1[key1] = value; Dictionary2[key2] = value; } finally { if (gotLock) rwLock.ExitWriteLock(); } } public bool Remove(TKey1 key1, TKey2 key2) { bool success; bool gotLock = false; try { // Avoid an asynchronous Thread.Abort() from possibly never existing an acquired lock by placing // the acquision inside the main try. The inner finally block is needed because thread aborts cannot // interrupt code in these blocks (hence gotLock is guaranteed to be set correctly). try {} finally { rwLock.EnterWriteLock(); gotLock = true; } Dictionary1.Remove(key1); success = Dictionary2.Remove(key2); } finally { if (gotLock) rwLock.ExitWriteLock(); } return success; } public bool Remove(TKey1 key1) { bool found = false; bool gotLock = false; try { // Avoid an asynchronous Thread.Abort() from possibly never existing an acquired lock by placing // the acquision inside the main try. The inner finally block is needed because thread aborts cannot // interrupt code in these blocks (hence gotLock is guaranteed to be set correctly). try {} finally { rwLock.EnterWriteLock(); gotLock = true; } // This is an O(n) operation! TValue value; if (Dictionary1.TryGetValue(key1, out value)) { foreach (KeyValuePair<TKey2, TValue> kvp in Dictionary2) { if (kvp.Value.Equals(value)) { Dictionary1.Remove(key1); Dictionary2.Remove(kvp.Key); found = true; break; } } } } finally { if (gotLock) rwLock.ExitWriteLock(); } return found; } public bool Remove(TKey2 key2) { bool found = false; bool gotLock = false; try { // Avoid an asynchronous Thread.Abort() from possibly never existing an acquired lock by placing // the acquision inside the main try. The inner finally block is needed because thread aborts cannot // interrupt code in these blocks (hence gotLock is guaranteed to be set correctly). try {} finally { rwLock.EnterWriteLock(); gotLock = true; } // This is an O(n) operation! TValue value; if (Dictionary2.TryGetValue(key2, out value)) { foreach (KeyValuePair<TKey1, TValue> kvp in Dictionary1) { if (kvp.Value.Equals(value)) { Dictionary2.Remove(key2); Dictionary1.Remove(kvp.Key); found = true; break; } } } } finally { if (gotLock) rwLock.ExitWriteLock(); } return found; } public void Clear() { bool gotLock = false; try { // Avoid an asynchronous Thread.Abort() from possibly never existing an acquired lock by placing // the acquision inside the main try. The inner finally block is needed because thread aborts cannot // interrupt code in these blocks (hence gotLock is guaranteed to be set correctly). try {} finally { rwLock.EnterWriteLock(); gotLock = true; } Dictionary1.Clear(); Dictionary2.Clear(); } finally { if (gotLock) rwLock.ExitWriteLock(); } } public int Count { get { return Dictionary1.Count; } } public bool ContainsKey(TKey1 key) { return Dictionary1.ContainsKey(key); } public bool ContainsKey(TKey2 key) { return Dictionary2.ContainsKey(key); } public bool TryGetValue(TKey1 key, out TValue value) { bool success; bool gotLock = false; try { // Avoid an asynchronous Thread.Abort() from possibly never existing an acquired lock by placing // the acquision inside the main try. The inner finally block is needed because thread aborts cannot // interrupt code in these blocks (hence gotLock is guaranteed to be set correctly). try {} finally { rwLock.EnterReadLock(); gotLock = true; } success = Dictionary1.TryGetValue(key, out value); } finally { if (gotLock) rwLock.ExitReadLock(); } return success; } public bool TryGetValue(TKey2 key, out TValue value) { bool success; bool gotLock = false; try { // Avoid an asynchronous Thread.Abort() from possibly never existing an acquired lock by placing // the acquision inside the main try. The inner finally block is needed because thread aborts cannot // interrupt code in these blocks (hence gotLock is guaranteed to be set correctly). try {} finally { rwLock.EnterReadLock(); gotLock = true; } success = Dictionary2.TryGetValue(key, out value); } finally { if (gotLock) rwLock.ExitReadLock(); } return success; } public void ForEach(Action<TValue> action) { bool gotLock = false; try { // Avoid an asynchronous Thread.Abort() from possibly never existing an acquired lock by placing // the acquision inside the main try. The inner finally block is needed because thread aborts cannot // interrupt code in these blocks (hence gotLock is guaranteed to be set correctly). try {} finally { rwLock.EnterReadLock(); gotLock = true; } foreach (TValue value in Dictionary1.Values) action(value); } finally { if (gotLock) rwLock.ExitReadLock(); } } public void ForEach(Action<KeyValuePair<TKey1, TValue>> action) { bool gotLock = false; try { // Avoid an asynchronous Thread.Abort() from possibly never existing an acquired lock by placing // the acquision inside the main try. The inner finally block is needed because thread aborts cannot // interrupt code in these blocks (hence gotLock is guaranteed to be set correctly). try {} finally { rwLock.EnterReadLock(); gotLock = true; } foreach (KeyValuePair<TKey1, TValue> entry in Dictionary1) action(entry); } finally { if (gotLock) rwLock.ExitReadLock(); } } public void ForEach(Action<KeyValuePair<TKey2, TValue>> action) { bool gotLock = false; try { // Avoid an asynchronous Thread.Abort() from possibly never existing an acquired lock by placing // the acquision inside the main try. The inner finally block is needed because thread aborts cannot // interrupt code in these blocks (hence gotLock is guaranteed to be set correctly). try {} finally { rwLock.EnterReadLock(); gotLock = true; } foreach (KeyValuePair<TKey2, TValue> entry in Dictionary2) action(entry); } finally { if (gotLock) rwLock.ExitReadLock(); } } public TValue FindValue(Predicate<TValue> predicate) { bool gotLock = false; try { // Avoid an asynchronous Thread.Abort() from possibly never existing an acquired lock by placing // the acquision inside the main try. The inner finally block is needed because thread aborts cannot // interrupt code in these blocks (hence gotLock is guaranteed to be set correctly). try {} finally { rwLock.EnterReadLock(); gotLock = true; } foreach (TValue value in Dictionary1.Values) { if (predicate(value)) return value; } } finally { if (gotLock) rwLock.ExitReadLock(); } return default(TValue); } public IList<TValue> FindAll(Predicate<TValue> predicate) { IList<TValue> list = new List<TValue>(); bool gotLock = false; try { // Avoid an asynchronous Thread.Abort() from possibly never existing an acquired lock by placing // the acquision inside the main try. The inner finally block is needed because thread aborts cannot // interrupt code in these blocks (hence gotLock is guaranteed to be set correctly). try {} finally { rwLock.EnterReadLock(); gotLock = true; } foreach (TValue value in Dictionary1.Values) { if (predicate(value)) list.Add(value); } } finally { if (gotLock) rwLock.ExitReadLock(); } return list; } public int RemoveAll(Predicate<TValue> predicate) { IList<TKey1> list = new List<TKey1>(); bool gotUpgradeableLock = false; try { // Avoid an asynchronous Thread.Abort() from possibly never existing an acquired lock by placing // the acquision inside the main try. The inner finally block is needed because thread aborts cannot // interrupt code in these blocks (hence gotLock is guaranteed to be set correctly). try {} finally { rwLock.EnterUpgradeableReadLock(); gotUpgradeableLock = true; } foreach (KeyValuePair<TKey1, TValue> kvp in Dictionary1) { if (predicate(kvp.Value)) list.Add(kvp.Key); } IList<TKey2> list2 = new List<TKey2>(list.Count); foreach (KeyValuePair<TKey2, TValue> kvp in Dictionary2) { if (predicate(kvp.Value)) list2.Add(kvp.Key); } bool gotWriteLock = false; try { try {} finally { rwLock.EnterUpgradeableReadLock(); gotWriteLock = true; } for (int i = 0; i < list.Count; i++) Dictionary1.Remove(list[i]); for (int i = 0; i < list2.Count; i++) Dictionary2.Remove(list2[i]); } finally { if (gotWriteLock) rwLock.ExitWriteLock(); } } finally { if (gotUpgradeableLock) rwLock.ExitUpgradeableReadLock(); } return list.Count; } } }
// 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; public class BringUpTests { const int Pass = 100; const int Fail = -1; public static int Main() { int result = Pass; if (!TestValueTypeDelegates()) { Console.WriteLine("Failed"); result = Fail; } if (!TestVirtualDelegates()) { Console.WriteLine("Failed"); result = Fail; } if (!TestInterfaceDelegates()) { Console.WriteLine("Failed"); result = Fail; } if (!TestStaticOpenClosedDelegates()) { Console.WriteLine("Failed"); result = Fail; } if (!TestMulticastDelegates()) { Console.WriteLine("Failed"); result = Fail; } return result; } public static bool TestValueTypeDelegates() { Console.Write("Testing delegates to value types..."); { TestValueType t = new TestValueType { X = 123 }; Func<string, string> d = t.GiveX; string result = d("MyPrefix"); if (result != "MyPrefix123") return false; } { object t = new TestValueType { X = 456 }; Func<string> d = t.ToString; string result = d(); if (result != "456") return false; } { Func<int, TestValueType> d = TestValueType.MakeValueType; TestValueType result = d(789); if (result.X != 789) return false; } Console.WriteLine("OK"); return true; } public static bool TestVirtualDelegates() { Console.Write("Testing delegates to virtual methods..."); { Mid t = new Mid(); if (t.GetBaseDo()() != "Base") return false; if (t.GetDerivedDo()() != "Mid") return false; } { Mid t = new Derived(); if (t.GetBaseDo()() != "Base") return false; if (t.GetDerivedDo()() != "Derived") return false; } Console.WriteLine("OK"); return true; } public static bool TestInterfaceDelegates() { Console.Write("Testing delegates to interface methods..."); { IFoo t = new ClassWithIFoo("Class"); Func<int, string> d = t.DoFoo; if (d(987) != "Class987") return false; } { IFoo t = new StructWithIFoo("Struct"); Func<int, string> d = t.DoFoo; if (d(654) != "Struct654") return false; } Console.WriteLine("OK"); return true; } public static bool TestStaticOpenClosedDelegates() { Console.Write("Testing static open and closed delegates..."); { Func<string, string, string> d = ExtensionClass.Combine; if (d("Hello", "World") != "HelloWorld") return false; } { Func<string, string> d = "Hi".Combine; if (d("There") != "HiThere") return false; } Console.WriteLine("OK"); return true; } public static bool TestMulticastDelegates() { Console.Write("Testing multicast delegates..."); { ClassThatMutates t = new ClassThatMutates(); Action d = t.AddOne; d(); if (t.State != 1) return false; t.State = 0; d += t.AddTwo; d(); if (t.State != 3) return false; t.State = 0; d += t.AddOne; d(); if (t.State != 4) return false; } Console.WriteLine("OK"); return true; } struct TestValueType { public int X; public string GiveX(string prefix) { return prefix + X.ToString(); } public static TestValueType MakeValueType(int value) { return new TestValueType { X = value }; } public override string ToString() { return X.ToString(); } } class Base { public virtual string Do() { return "Base"; } } class Mid : Base { public override string Do() { return "Mid"; } public Func<string> GetBaseDo() { return base.Do; } public Func<string> GetDerivedDo() { return Do; } } class Derived : Mid { public override string Do() { return "Derived"; } } interface IFoo { string DoFoo(int x); } class ClassWithIFoo : IFoo { string _prefix; public ClassWithIFoo(string prefix) { _prefix = prefix; } public string DoFoo(int x) { return _prefix + x.ToString(); } } struct StructWithIFoo : IFoo { string _prefix; public StructWithIFoo(string prefix) { _prefix = prefix; } public string DoFoo(int x) { return _prefix + x.ToString(); } } class ClassThatMutates { public int State; public void AddOne() { State++; } public void AddTwo() { State += 2; } } } static class ExtensionClass { public static string Combine(this string s1, string s2) { return s1 + s2; } }
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; using CslaGenerator; using CslaGenerator.Metadata; using CodeSmith.Engine; using System.Collections.Generic; namespace CslaGenerator.Util { /// <summary> /// Summary description for CslaTemplateHelper. /// </summary> public class CslaTemplateHelper : CodeTemplate { public CslaTemplateHelper() { } private CslaGeneratorUnit _CurrentUnit; public CslaGeneratorUnit CurrentUnit { get { return _CurrentUnit; } set { _CurrentUnit = value; } } public CslaPropertyMode PropertyMode { get { var pm = _CurrentUnit.GenerationParams.PropertyMode; if (pm == CslaPropertyMode.Default) switch (_CurrentUnit.GenerationParams.TargetFramework) { case TargetFramework.CSLA10: case TargetFramework.CSLA20: return CslaPropertyMode.Standard; default: return CslaPropertyMode.Managed; } return pm; } } protected int _indentLevel = 0; [Browsable(false)] public int IndentLevel { get { return _indentLevel; } set { _indentLevel = value; } } private bool _DataSetLoadingScheme; public bool DataSetLoadingScheme { get { return _DataSetLoadingScheme; } set { _DataSetLoadingScheme = value; } } protected int _resultSetCount = 0; public string FormatFieldName(string name) { return CurrentUnit.Params.FieldNamePrefix + FormatCamel(name); } public string FormatDelegateName(string name) { return CurrentUnit.Params.DelegateNamePrefix + FormatCamel(name); } public string FormatCamel(string name) { if (name.Length == 2) return name.ToLower(); if (name.Length > 0) { StringBuilder sb = new StringBuilder(); sb.Append(Char.ToLower(name[0])); if (name.Length > 1) sb.Append(name.Substring(1)); return sb.ToString(); } return String.Empty; } public virtual string LoadProperty(ValueProperty prop, string value) { if (PropertyMode == CslaPropertyMode.Managed) return String.Format("LoadProperty({0}, {1});", FormatManaged(prop.Name), value); else return String.Format("{0} = {1};", FormatFieldName(prop.Name), value); } public virtual string ReadProperty(ValueProperty prop) { if (PropertyMode == CslaPropertyMode.Managed) return String.Format("ReadProperty({0})", FormatManaged(prop.Name)); else return FormatFieldName(prop.Name); } public virtual string GetAttributesString(string[] attributes) { if (attributes == null || attributes.Length == 0) return string.Empty; return "[" + string.Join(", ", attributes) + "]"; } public string FormatPascal(string name) { if (name.Length > 0) { StringBuilder sb = new StringBuilder(); sb.Append(Char.ToUpper(name[0])); if (name.Length > 1) sb.Append(name.Substring(1)); return sb.ToString(); } return String.Empty; } public string FormatManaged(string name) { if (name.Length > 0) { return FormatPascal(name) + "Property"; } return String.Empty; } public virtual string GetInitValue(TypeCodeEx typeCode) { if (typeCode == TypeCodeEx.Int16 || typeCode == TypeCodeEx.Int32 || typeCode == TypeCodeEx.Int64 || typeCode == TypeCodeEx.Double || typeCode == TypeCodeEx.Decimal || typeCode == TypeCodeEx.Single) { return "0"; } else if (typeCode == TypeCodeEx.String) { return "String.Empty"; } else if (typeCode == TypeCodeEx.Boolean) { return "false"; } else if (typeCode == TypeCodeEx.Byte) { return "0"; } else if (typeCode == TypeCodeEx.Object) { return "null"; } else if (typeCode == TypeCodeEx.Guid) { return "Guid.Empty"; } else if (typeCode == TypeCodeEx.SmartDate) { return "new SmartDate(true)"; } else if (typeCode == TypeCodeEx.DateTime) { return "DateTime.Now"; } else if (typeCode == TypeCodeEx.Char) { return "Char.MinValue"; } else if (typeCode == TypeCodeEx.ByteArray) { return "new Byte[] {}"; } else { return String.Empty; } } public virtual string GetInitValue(ValueProperty prop) { if (AllowNull(prop) && prop.PropertyType != TypeCodeEx.SmartDate) return "null"; else return GetInitValue(prop.PropertyType); } public virtual string GetReaderAssignmentStatement(ValueProperty prop) { return GetReaderAssignmentStatement(prop,false); } public virtual string GetReaderAssignmentStatement(ValueProperty prop, bool Structure) { string statement; if (Structure) statement = "nfo." + prop.Name + " = "; else statement = FormatFieldName(prop.Name) + " = "; statement += GetDataReaderStatement(prop) + ";"; return statement; } public virtual string GetDataReaderStatement(ValueProperty prop) { bool nullable = AllowNull(prop); string statement = string.Empty; if (nullable) { if (TypeHelper.IsNullableType(prop.PropertyType)) statement += string.Format("!dr.IsDBNull(\"{0}\") ? new {1}(", prop.ParameterName, GetDataType(prop)); else statement += string.Format("!dr.IsDBNull(\"{0}\") ? ", prop.ParameterName); } statement += "dr."; if (prop.DbBindColumn.ColumnOriginType == ColumnOriginType.None) statement += GetReaderMethod(prop.PropertyType); else statement += GetReaderMethod(GetDbType(prop.DbBindColumn), prop.PropertyType); statement += "(\"" + prop.ParameterName + "\""; if (prop.PropertyType == TypeCodeEx.SmartDate) statement += ", true"; statement += ")"; if (nullable) { if (TypeHelper.IsNullableType(prop.PropertyType)) statement += ")"; statement += " : null"; } if (prop.PropertyType == TypeCodeEx.ByteArray) statement = "(" + statement + ") as Byte[]"; return statement; } public bool AllowNull(Property prop) { return (GeneratorController.Current.CurrentUnit.GenerationParams.NullableSupport && prop.Nullable && prop.PropertyType != TypeCodeEx.SmartDate); } public virtual string GetParameterSet(Property prop, bool Criteria) { bool nullable = AllowNull(prop); string propName; propName = (Criteria) ? "crit." + FormatPascal(prop.Name) : FormatFieldName(prop.Name); if (nullable && prop.PropertyType != TypeCodeEx.SmartDate) { if (TypeHelper.IsNullableType(prop.PropertyType)) return string.Format("{0} == null ? (object)DBNull.Value : {0}.Value", propName); else return string.Format("{0} == null ? (object)DBNull.Value : {0}", propName); } switch (prop.PropertyType) { case Metadata.TypeCodeEx.SmartDate: return propName + ".DBValue"; case Metadata.TypeCodeEx.Guid: return propName + ".Equals(Guid.Empty) ? (object)DBNull.Value : " + propName; default: return propName; } } public virtual string GetParameterSet(Property prop) { return GetParameterSet(prop,false); } protected DbType GetDbType(DbBindColumn prop) { if (prop.NativeType == "real") return DbType.Single; return prop.DataType; } //public string GetParamInstanciation() public virtual string GetDataType(Property prop) { string type = GetDataType(prop.PropertyType); if (this.AllowNull(prop)) { if (TypeHelper.IsNullableType(prop.PropertyType)) type += "?"; } return type; } protected virtual string GetDataType(TypeCodeEx type) { if (type == TypeCodeEx.ByteArray) return "Byte[]"; return type.ToString(); } protected internal string GetReaderMethod(DbType dataType, TypeCodeEx propertyType) { switch (dataType) { case DbType.Byte: return "GetByte"; case DbType.Int16: return "GetInt16"; case DbType.Int32: return "GetInt32"; case DbType.Int64: return "GetInt64"; case DbType.AnsiStringFixedLength: return "GetChar"; case DbType.AnsiString: return "GetString"; case DbType.String: return "GetString"; case DbType.StringFixedLength: return "GetString"; case DbType.Boolean: return "GetBoolean"; case DbType.Guid: return "GetGuid"; case DbType.Currency: return "GetDecimal"; case DbType.Decimal: return "GetDecimal"; case DbType.DateTime: case DbType.Date: return (propertyType == TypeCodeEx.SmartDate) ? "GetSmartDate" : "GetDateTime"; case DbType.Binary: return "GetValue"; case DbType.Single: return "GetFloat"; case DbType.Double: return "GetDouble"; default: return "GetValue"; } } public string GetReaderMethod(TypeCodeEx dataType) { switch (dataType) { case TypeCodeEx.Byte: return "GetByte"; case TypeCodeEx.Int16: return "GetInt16"; case TypeCodeEx.Int32: return "GetInt32"; case TypeCodeEx.Int64: return "GetInt64"; case TypeCodeEx.String: return "GetString"; case TypeCodeEx.Boolean: return "GetBoolean"; case TypeCodeEx.Guid: return "GetGuid"; case TypeCodeEx.Decimal: return "GetDecimal"; case TypeCodeEx.SmartDate: return "GetSmartDate"; case TypeCodeEx.DateTime: return "GetDateTime"; case TypeCodeEx.ByteArray: return "GetValue"; case TypeCodeEx.Single: return "GetFloat"; case TypeCodeEx.Double: return "GetDouble"; case TypeCodeEx.Char: return "GetChar"; default: return "GetValue"; } } /// <summary> /// This one is only used for casting values that coume OUT of db command parameters (commonly identity keys). /// </summary> /// <param name="dataType"></param> /// <returns></returns> protected internal virtual string GetLanguageVariableType(DbType dataType) { switch (dataType) { case DbType.AnsiString: return "string"; case DbType.AnsiStringFixedLength: return "string"; case DbType.Binary: return "byte[]"; case DbType.Boolean: return "bool"; case DbType.Byte: return "byte"; case DbType.Currency: return "decimal"; case DbType.Date: case DbType.DateTime: return "DateTime"; case DbType.Decimal: return "decimal"; case DbType.Double: return "double"; case DbType.Guid: return "Guid"; case DbType.Int16: return "short"; case DbType.Int32: return "int"; case DbType.Int64: return "long"; case DbType.Object: return "object"; case DbType.SByte: return "sbyte"; case DbType.Single: return "float"; case DbType.String: return "string"; case DbType.StringFixedLength: return "string"; case DbType.Time: return "TimeSpan"; case DbType.UInt16: return "ushort"; case DbType.UInt32: return "uint"; case DbType.UInt64: return "ulong"; case DbType.VarNumeric: return "decimal"; default: return "__UNKNOWN__" + dataType.ToString(); } } public string GetRelationStrings(CslaObjectInfo info) { if (IsCollectionType(info.ObjectType)) info = FindChildInfo(info,info.ItemType); StringBuilder sb = new StringBuilder(); foreach (ChildProperty child in info.ChildProperties) if (!child.LazyLoad) { sb.Append(GetRelationString(info,child)); sb.Append(Environment.NewLine); CslaObjectInfo grandchildInfo = FindChildInfo(info,child.Name); if (grandchildInfo != null) sb.Append(GetRelationStrings(grandchildInfo)); } foreach (ChildProperty child in info.InheritedChildProperties) if (!child.LazyLoad) { sb.Append(GetRelationString(info,child)); sb.Append(Environment.NewLine); CslaObjectInfo grandchildInfo = FindChildInfo(info,child.Name); if (grandchildInfo != null) sb.Append(GetRelationStrings(grandchildInfo)); } foreach (ChildProperty child in info.ChildCollectionProperties) if (!child.LazyLoad) { sb.Append(GetRelationString(info,child)); sb.Append(Environment.NewLine); CslaObjectInfo grandchildInfo = FindChildInfo(info,child.Name); if (grandchildInfo != null) sb.Append(GetRelationStrings(grandchildInfo)); } foreach (ChildProperty child in info.InheritedChildCollectionProperties) if (!child.LazyLoad) { sb.Append(GetRelationString(info,child)); sb.Append(Environment.NewLine); CslaObjectInfo grandchildInfo = FindChildInfo(info,child.Name); if (grandchildInfo != null) sb.Append(GetRelationStrings(grandchildInfo)); } return sb.ToString(); } public virtual string GetRelationString(CslaObjectInfo info, ChildProperty child) { string indent = new string('\t', _indentLevel); StringBuilder sb = new StringBuilder(); CslaObjectInfo childInfo = FindChildInfo(info,child.TypeName); string joinColumn = String.Empty; if (child.LoadParameters.Count > 0) { if (IsCollectionType(childInfo.ObjectType)) { joinColumn = child.LoadParameters[0].Property.Name; childInfo = FindChildInfo(info,childInfo.ItemType); } if (joinColumn == String.Empty) { joinColumn = child.LoadParameters[0].Property.Name; } } sb.Append(indent); sb.Append("ds.Relations.Add(\""); sb.Append(info.ObjectName); sb.Append(childInfo.ObjectName); sb.Append("\", ds.Tables["); sb.Append(_resultSetCount.ToString()); sb.Append("].Columns[\""); sb.Append(joinColumn); sb.Append("\"], ds.Tables["); sb.Append((_resultSetCount + 1).ToString()); sb.Append("].Columns[\""); sb.Append(joinColumn); sb.Append("\"], false);"); _resultSetCount++; return sb.ToString(); } public virtual string GetXmlCommentString(string xmlComment) { string indent = new string('\t', _indentLevel); // add leading indent and comment sign xmlComment = indent + "/// " + xmlComment; return Regex.Replace(xmlComment, "\n", "\n" + indent + "/// ", RegexOptions.Multiline); } public virtual string GetUsingStatementsString(CslaObjectInfo info) { string[] usingNamespaces = GetNamespaces(info); string result = String.Empty; foreach (string namespaceName in usingNamespaces) result += "using " + namespaceName + ";" + Environment.NewLine; foreach (ValueProperty p in info.ValueProperties) { if (p.PropertyType == TypeCodeEx.ByteArray && AllowNull(p)) result += "using System.Linq; //Added for byte[] helpers" + Environment.NewLine; } return(result); } // Helper funcion for GetUsingStatementString method protected string[] GetNamespaces(CslaObjectInfo info) { List<string> usingList = new List<string>(); foreach (ChildProperty prop in info.ChildProperties) if (prop.TypeName != info.ObjectName) { CslaObjectInfo childInfo = FindChildInfo(info, prop.TypeName); if (childInfo != null) if (!usingList.Contains(childInfo.ObjectNamespace) && childInfo.ObjectNamespace != info.ObjectNamespace) usingList.Add (childInfo.ObjectNamespace); } foreach (ChildProperty prop in info.InheritedChildProperties) if (prop.TypeName != info.ObjectName) { CslaObjectInfo childInfo = FindChildInfo(info, prop.TypeName); if (childInfo != null) if (!usingList.Contains(childInfo.ObjectNamespace) && childInfo.ObjectNamespace != info.ObjectNamespace) usingList.Add (childInfo.ObjectNamespace); } foreach (ChildProperty prop in info.ChildCollectionProperties) if (prop.TypeName != info.ObjectName) { CslaObjectInfo childInfo = FindChildInfo(info, prop.TypeName); if (childInfo != null) if (!usingList.Contains(childInfo.ObjectNamespace) && childInfo.ObjectNamespace != info.ObjectNamespace) usingList.Add (childInfo.ObjectNamespace); } foreach (ChildProperty prop in info.InheritedChildCollectionProperties) if (prop.TypeName != info.ObjectName) { CslaObjectInfo childInfo = FindChildInfo(info, prop.TypeName); if (childInfo != null) if (!usingList.Contains(childInfo.ObjectNamespace) && childInfo.ObjectNamespace != info.ObjectNamespace) usingList.Add (childInfo.ObjectNamespace); } if (info.ItemType != String.Empty) { CslaObjectInfo childInfo = FindChildInfo(info, info.ItemType); if (childInfo != null) if (!usingList.Contains(childInfo.ObjectNamespace) && childInfo.ObjectNamespace != info.ObjectNamespace) usingList.Add (childInfo.ObjectNamespace); } if (info.ParentType != String.Empty) { CslaObjectInfo parentInfo = FindChildInfo(info, info.ParentType); if (parentInfo != null) if (!usingList.Contains(parentInfo.ObjectNamespace) && parentInfo.ObjectNamespace != info.ObjectNamespace) usingList.Add (parentInfo.ObjectNamespace); } //string[] usingNamespaces = new string[usingList.Count]; //usingList.CopyTo(0, usingNamespaces, 0, usingList.Count); //Array.Sort(usingNamespaces, new CaseInsensitiveComparer()); if (usingList.Contains(string.Empty)) usingList.Remove(string.Empty); usingList.Sort(string.Compare); return usingList.ToArray(); } public bool LoadsChildren(CslaObjectInfo info) { if (IsCollectionType(info.ObjectType)) info = FindChildInfo(info,info.ItemType); foreach (ChildProperty child in info.ChildProperties) if (!child.LazyLoad) { return true; } foreach (ChildProperty child in info.ChildCollectionProperties) if (!child.LazyLoad) { return true; } foreach (ChildProperty child in info.InheritedChildProperties) if (!child.LazyLoad) { return true; } foreach (ChildProperty child in info.InheritedChildCollectionProperties) if (!child.LazyLoad) { return true; } return false; } public bool IsCollectionType(CslaObjectType cslaType) { if (cslaType == CslaObjectType.EditableChildCollection || cslaType == CslaObjectType.EditableRootCollection || cslaType == CslaObjectType.ReadOnlyCollection) return true; return false; } public bool IsEditableType(CslaObjectType cslaType) { if (cslaType == CslaObjectType.EditableChild || cslaType == CslaObjectType.EditableChildCollection || cslaType == CslaObjectType.EditableRoot || cslaType == CslaObjectType.EditableRootCollection || cslaType == CslaObjectType.EditableSwitchable) return true; return false; } public bool IsReadOnlyType(CslaObjectType cslaType) { if (cslaType == CslaObjectType.ReadOnlyCollection || cslaType == CslaObjectType.ReadOnlyObject) return true; return false; } public bool IsChildType(CslaObjectType cslaType) { if (cslaType == CslaObjectType.EditableChild || cslaType == CslaObjectType.EditableChildCollection) return true; return false; } public CslaObjectInfo FindChildInfo(CslaObjectInfo info, string name) { return info.Parent.CslaObjects.Find(name); } public CslaObjectInfo[] GetChildItems(CslaObjectInfo info) { List<CslaObjectInfo> list = new List<CslaObjectInfo>(); foreach (ChildProperty cp in info.GetAllChildProperties()) { CslaObjectInfo ci = FindChildInfo(info, cp.TypeName); if (ci != null) { if (IsCollectionType(ci.ObjectType)) { ci = FindChildInfo(info, ci.ItemType); } if (ci != null) list.Add(ci); } } return list.ToArray(); } public string[] GetAllChildItemsInHierarchy(CslaObjectInfo info) { List<String> list = new List<String>(); foreach (CslaObjectInfo obj in GetChildItems(info)) { list.Add(obj.ObjectName); list.AddRange(GetAllChildItemsInHierarchy(obj)); } return list.ToArray(); } public void Message(string msg) { MessageBox.Show(msg, "CSLA Generator"); } public void Message(string msg, string caption) { MessageBox.Show(msg, caption, MessageBoxButtons.OK, MessageBoxIcon.Warning); } protected internal string ParseNativeType(string nType) { try { object value = Enum.Parse(typeof(SqlDbType), nType, true); return value.ToString(); } catch { return string.Empty; } } public string GetNativeType(ValueProperty prop) { string nativeType=null; if (!string.IsNullOrEmpty(prop.DbBindColumn.NativeType)) nativeType = ParseNativeType(prop.DbBindColumn.NativeType); if (string.IsNullOrEmpty(nativeType)) { CslaGenerator.Controls.OutputWindow.Current.AddOutputInfo(string.Format("{0}: Unable to parse database native type from DbBindColumn, infering type from property type.", prop.PropertyType)); nativeType = TypeHelper.GetSqlDbType(prop.PropertyType).ToString(); } return nativeType; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Newtonsoft.Json; using TM.Data.Pluralsight.Json; using TM.Shared; namespace TM.Data.Pluralsight { internal interface IPluralsightDataService : IDisposable { Task<Author> GetAuthorAsync(string urlName); Task<string> GetCourseShortDescriptionAsync(string urlName); Task<ICollection<Module>> GetCourseToCAsync(string urlName); Task<Specializations> GetCourseSpecializationsAsync(string courseUrlName); Task<Dictionary<string, Specializations>> GetCourseSpecializationsContainerAsync(); } internal abstract class DataServiceBase : IPluralsightDataService { protected const string TrainingProviderName = "pluralsight"; protected const string AuthorsArchiveNamePrefix = "pluralsight_authors - "; protected const string CoursesArchiveNamePrefix = "pluralsight_courses - "; protected const string CoursesToCArchiveNamePrefix = "pluralsight_coursesToC - "; protected const string CourseSpecializationsArchiveNamePrefix = "pluralsight_specializations - "; protected const string DateTimeFormatPattern = "yyyy.MM.dd [HH-mm.ss]"; protected const string ArchiveFileExtension = ".json"; protected Dictionary<string, string> AuthorCoursesContainer; protected readonly IFileSystemProxy FileSystemProxy; protected DataServiceBase(IFileSystemProxy fileSystemProxy) { FileSystemProxy = fileSystemProxy; AuthorCoursesContainer = new Dictionary<string, string>(); } #region Authors protected internal abstract Task<string> GetAuthorJsonDataAsync(string urlName); protected abstract void UpdateAuthorsArchive(string urlName, string jsonData); public async Task<Author> GetAuthorAsync(string urlName) { var author = new Author(); var jsonData = await GetAuthorJsonDataAsync(urlName); UpdateAuthorCoursesDictionary(jsonData); UpdateAuthorsArchive(urlName, jsonData); var jsonObject = JsonConvert.DeserializeObject<JsonAuthorInfo>(jsonData); // Name author.FirstName = jsonObject.firstName.Trim(); author.LastName = jsonObject.fullName .Replace(jsonObject.firstName, string.Empty).Trim(); // Author.Bio if (!string.IsNullOrWhiteSpace(jsonObject.longBio)) { author.Bio = jsonObject.longBio.Trim(); } // Social.FacebookLink author.Social.FacebookLink = string.IsNullOrWhiteSpace(jsonObject.optionalFacebookUrl) ? null : jsonObject.optionalFacebookUrl; // Social.TwitterLink author.Social.TwitterLink = string.IsNullOrWhiteSpace(jsonObject.optionalTwitterUrl) ? null : jsonObject.optionalTwitterUrl; // Social.LinkedInLink author.Social.LinkedInLink = string.IsNullOrWhiteSpace(jsonObject.optionalLinkedInUrl) ? null : jsonObject.optionalLinkedInUrl; // Social.RssLink author.Social.RssLink = string.IsNullOrWhiteSpace(jsonObject.optionalRssUrl) ? null : jsonObject.optionalRssUrl; // Badge.ImageSiteUrl and Badge.ImageName if (!string.IsNullOrWhiteSpace(jsonObject.optionalBadgeImageUrl)) { var badgeImageSiteUrl = new Uri(jsonObject.optionalBadgeImageUrl); author.Badge.ImageSiteUrl = badgeImageSiteUrl.Scheme == Uri.UriSchemeFile ? new UriBuilder(badgeImageSiteUrl) { Scheme = "http" }.ToString() : badgeImageSiteUrl.ToString(); author.Badge.ImageName = badgeImageSiteUrl.Segments.Last().EndsWith("/", StringComparison.Ordinal) ? null : badgeImageSiteUrl.Segments.Last(); } // Badge.Link if (!string.IsNullOrWhiteSpace(jsonObject.optionalBadgeLink)) { var badgeLinkUri = new Uri(jsonObject.optionalBadgeLink); author.Badge.Link = badgeLinkUri.Scheme == Uri.UriSchemeFile ? new UriBuilder(badgeLinkUri) { Scheme = "http" }.ToString() : badgeLinkUri.ToString(); } // Badge.HoverText author.Badge.HoverText = string.IsNullOrWhiteSpace(jsonObject.optionalBadgeHoverText) ? null : jsonObject.optionalBadgeHoverText; // Avatar.SiteUrl and Avatar.Name if (!string.IsNullOrWhiteSpace(jsonObject.largeImageUrl)) { var avatarSiteUri = new Uri(jsonObject.largeImageUrl); author.Avatar.SiteUrl = avatarSiteUri.Scheme == Uri.UriSchemeFile ? new UriBuilder(avatarSiteUri) { Scheme = "http" }.ToString() : avatarSiteUri.ToString(); author.Avatar.Name = avatarSiteUri.Segments.Last().EndsWith("/", StringComparison.Ordinal) ? null : avatarSiteUri.Segments.Last(); } return author; } protected void UpdateAuthorCoursesDictionary(string jsonAuthor) { var jsonObject = JsonConvert.DeserializeObject<JsonAuthorCourses>(jsonAuthor); foreach (var course in jsonObject.courses) { var courseString = JsonConvert.SerializeObject(course, Formatting.Indented); AuthorCoursesContainer[course.name] = courseString; } } #endregion #region Courses protected internal abstract Task<string> GetCourseJsonDataAsync(string urlName); protected abstract void UpdateCourseArchive(string urlName, string jsonData); public async Task<string> GetCourseShortDescriptionAsync(string urlName) { string shortDescription; string authorCourseJsonString; if (AuthorCoursesContainer.TryGetValue(urlName, out authorCourseJsonString)) { var jsonObject = JsonConvert.DeserializeObject<JsonAuthorCourse>(authorCourseJsonString); shortDescription = string.IsNullOrWhiteSpace(jsonObject.shortDescription) ? null : jsonObject.shortDescription.Trim(); } else { var jsonData = await GetCourseJsonDataAsync(urlName); UpdateCourseArchive(urlName, jsonData); var jsonObject = JsonConvert.DeserializeObject<JsonCourseInfo>(jsonData); shortDescription = string.IsNullOrWhiteSpace(jsonObject.shortDescription) ? null : jsonObject.shortDescription.Trim(); } return shortDescription; } #endregion #region Courses table of contents protected internal abstract Task<string> GetCourseToCJsonDataAsync(string urlName); protected abstract void UpdateCourseToCArchive(string urlName, string jsonData); public async Task<ICollection<Module>> GetCourseToCAsync(string urlName) { var jsonData = await GetCourseToCJsonDataAsync(urlName); UpdateCourseToCArchive(urlName, jsonData); var jsonObject = JsonConvert.DeserializeObject<List<JsonModule>>(jsonData); var modules = jsonObject.Select((chapter, capterIndex) => new Module { Description = chapter.description, Ordinal = Convert.ToByte(capterIndex + 1), Title = chapter.title, Duration = TimeSpan.Parse(chapter.duration), Topics = chapter.clips.Select((topic, topicIndex) => new Topic { Title = topic.title, Ordinal = Convert.ToByte(topicIndex + 1), Duration = TimeSpan.Parse(topic.duration) }).ToList() }).ToList(); return modules; } #endregion #region Courses Specialization protected abstract Task<Dictionary<string, Specializations>> InitializeCourseSpecializationContainerAsync(); public async Task<Dictionary<string, Specializations>> GetCourseSpecializationsContainerAsync() { var container = await InitializeCourseSpecializationContainerAsync(); return container; } protected abstract Task<Dictionary<string, Specializations>> GetInstanceOfCourseSpecializationsContainerAsync(); public async Task<Specializations> GetCourseSpecializationsAsync(string courseUrlName) { var specializationsContainer = await GetInstanceOfCourseSpecializationsContainerAsync(); Specializations specializations; if (specializationsContainer.TryGetValue(courseUrlName, out specializations)) { return specializations; } return Specializations.None; } #endregion #region IDisposable Implementation private bool _disposed; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { AuthorCoursesContainer = null; _disposed = true; } #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 gax = Google.Api.Gax; using gcrv = Google.Cloud.ResourceSettings.V1; using sys = System; namespace Google.Cloud.ResourceSettings.V1 { /// <summary>Resource name for the <c>Setting</c> resource.</summary> public sealed partial class SettingName : gax::IResourceName, sys::IEquatable<SettingName> { /// <summary>The possible contents of <see cref="SettingName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project_number}/settings/{setting_name}</c>. /// </summary> ProjectNumberSettingName = 1, /// <summary>A resource name with pattern <c>folders/{folder}/settings/{setting_name}</c>.</summary> FolderSettingName = 2, /// <summary> /// A resource name with pattern <c>organizations/{organization}/settings/{setting_name}</c>. /// </summary> OrganizationSettingName = 3, } private static gax::PathTemplate s_projectNumberSettingName = new gax::PathTemplate("projects/{project_number}/settings/{setting_name}"); private static gax::PathTemplate s_folderSettingName = new gax::PathTemplate("folders/{folder}/settings/{setting_name}"); private static gax::PathTemplate s_organizationSettingName = new gax::PathTemplate("organizations/{organization}/settings/{setting_name}"); /// <summary>Creates a <see cref="SettingName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="SettingName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static SettingName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new SettingName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="SettingName"/> with the pattern <c>projects/{project_number}/settings/{setting_name}</c> /// . /// </summary> /// <param name="projectNumberId">The <c>ProjectNumber</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="settingNameId">The <c>SettingName</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="SettingName"/> constructed from the provided ids.</returns> public static SettingName FromProjectNumberSettingName(string projectNumberId, string settingNameId) => new SettingName(ResourceNameType.ProjectNumberSettingName, projectNumberId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectNumberId, nameof(projectNumberId)), settingNameId: gax::GaxPreconditions.CheckNotNullOrEmpty(settingNameId, nameof(settingNameId))); /// <summary> /// Creates a <see cref="SettingName"/> with the pattern <c>folders/{folder}/settings/{setting_name}</c>. /// </summary> /// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="settingNameId">The <c>SettingName</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="SettingName"/> constructed from the provided ids.</returns> public static SettingName FromFolderSettingName(string folderId, string settingNameId) => new SettingName(ResourceNameType.FolderSettingName, folderId: gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), settingNameId: gax::GaxPreconditions.CheckNotNullOrEmpty(settingNameId, nameof(settingNameId))); /// <summary> /// Creates a <see cref="SettingName"/> with the pattern <c>organizations/{organization}/settings/{setting_name}</c> /// . /// </summary> /// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="settingNameId">The <c>SettingName</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="SettingName"/> constructed from the provided ids.</returns> public static SettingName FromOrganizationSettingName(string organizationId, string settingNameId) => new SettingName(ResourceNameType.OrganizationSettingName, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), settingNameId: gax::GaxPreconditions.CheckNotNullOrEmpty(settingNameId, nameof(settingNameId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="SettingName"/> with pattern /// <c>projects/{project_number}/settings/{setting_name}</c>. /// </summary> /// <param name="projectNumberId">The <c>ProjectNumber</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="settingNameId">The <c>SettingName</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SettingName"/> with pattern /// <c>projects/{project_number}/settings/{setting_name}</c>. /// </returns> public static string Format(string projectNumberId, string settingNameId) => FormatProjectNumberSettingName(projectNumberId, settingNameId); /// <summary> /// Formats the IDs into the string representation of this <see cref="SettingName"/> with pattern /// <c>projects/{project_number}/settings/{setting_name}</c>. /// </summary> /// <param name="projectNumberId">The <c>ProjectNumber</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="settingNameId">The <c>SettingName</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SettingName"/> with pattern /// <c>projects/{project_number}/settings/{setting_name}</c>. /// </returns> public static string FormatProjectNumberSettingName(string projectNumberId, string settingNameId) => s_projectNumberSettingName.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectNumberId, nameof(projectNumberId)), gax::GaxPreconditions.CheckNotNullOrEmpty(settingNameId, nameof(settingNameId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="SettingName"/> with pattern /// <c>folders/{folder}/settings/{setting_name}</c>. /// </summary> /// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="settingNameId">The <c>SettingName</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SettingName"/> with pattern /// <c>folders/{folder}/settings/{setting_name}</c>. /// </returns> public static string FormatFolderSettingName(string folderId, string settingNameId) => s_folderSettingName.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), gax::GaxPreconditions.CheckNotNullOrEmpty(settingNameId, nameof(settingNameId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="SettingName"/> with pattern /// <c>organizations/{organization}/settings/{setting_name}</c>. /// </summary> /// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="settingNameId">The <c>SettingName</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SettingName"/> with pattern /// <c>organizations/{organization}/settings/{setting_name}</c>. /// </returns> public static string FormatOrganizationSettingName(string organizationId, string settingNameId) => s_organizationSettingName.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(settingNameId, nameof(settingNameId))); /// <summary>Parses the given resource name string into a new <see cref="SettingName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project_number}/settings/{setting_name}</c></description></item> /// <item><description><c>folders/{folder}/settings/{setting_name}</c></description></item> /// <item><description><c>organizations/{organization}/settings/{setting_name}</c></description></item> /// </list> /// </remarks> /// <param name="settingName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="SettingName"/> if successful.</returns> public static SettingName Parse(string settingName) => Parse(settingName, false); /// <summary> /// Parses the given resource name string into a new <see cref="SettingName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project_number}/settings/{setting_name}</c></description></item> /// <item><description><c>folders/{folder}/settings/{setting_name}</c></description></item> /// <item><description><c>organizations/{organization}/settings/{setting_name}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="settingName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="SettingName"/> if successful.</returns> public static SettingName Parse(string settingName, bool allowUnparsed) => TryParse(settingName, allowUnparsed, out SettingName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="SettingName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project_number}/settings/{setting_name}</c></description></item> /// <item><description><c>folders/{folder}/settings/{setting_name}</c></description></item> /// <item><description><c>organizations/{organization}/settings/{setting_name}</c></description></item> /// </list> /// </remarks> /// <param name="settingName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="SettingName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string settingName, out SettingName result) => TryParse(settingName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="SettingName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project_number}/settings/{setting_name}</c></description></item> /// <item><description><c>folders/{folder}/settings/{setting_name}</c></description></item> /// <item><description><c>organizations/{organization}/settings/{setting_name}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="settingName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="SettingName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string settingName, bool allowUnparsed, out SettingName result) { gax::GaxPreconditions.CheckNotNull(settingName, nameof(settingName)); gax::TemplatedResourceName resourceName; if (s_projectNumberSettingName.TryParseName(settingName, out resourceName)) { result = FromProjectNumberSettingName(resourceName[0], resourceName[1]); return true; } if (s_folderSettingName.TryParseName(settingName, out resourceName)) { result = FromFolderSettingName(resourceName[0], resourceName[1]); return true; } if (s_organizationSettingName.TryParseName(settingName, out resourceName)) { result = FromOrganizationSettingName(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(settingName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private SettingName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string folderId = null, string organizationId = null, string projectNumberId = null, string settingNameId = null) { Type = type; UnparsedResource = unparsedResourceName; FolderId = folderId; OrganizationId = organizationId; ProjectNumberId = projectNumberId; SettingNameId = settingNameId; } /// <summary> /// Constructs a new instance of a <see cref="SettingName"/> class from the component parts of pattern /// <c>projects/{project_number}/settings/{setting_name}</c> /// </summary> /// <param name="projectNumberId">The <c>ProjectNumber</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="settingNameId">The <c>SettingName</c> ID. Must not be <c>null</c> or empty.</param> public SettingName(string projectNumberId, string settingNameId) : this(ResourceNameType.ProjectNumberSettingName, projectNumberId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectNumberId, nameof(projectNumberId)), settingNameId: gax::GaxPreconditions.CheckNotNullOrEmpty(settingNameId, nameof(settingNameId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Folder</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string FolderId { get; } /// <summary> /// The <c>Organization</c> ID. May be <c>null</c>, depending on which resource name is contained by this /// instance. /// </summary> public string OrganizationId { get; } /// <summary> /// The <c>ProjectNumber</c> ID. May be <c>null</c>, depending on which resource name is contained by this /// instance. /// </summary> public string ProjectNumberId { get; } /// <summary> /// The <c>SettingName</c> ID. May be <c>null</c>, depending on which resource name is contained by this /// instance. /// </summary> public string SettingNameId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectNumberSettingName: return s_projectNumberSettingName.Expand(ProjectNumberId, SettingNameId); case ResourceNameType.FolderSettingName: return s_folderSettingName.Expand(FolderId, SettingNameId); case ResourceNameType.OrganizationSettingName: return s_organizationSettingName.Expand(OrganizationId, SettingNameId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as SettingName); /// <inheritdoc/> public bool Equals(SettingName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(SettingName a, SettingName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(SettingName a, SettingName b) => !(a == b); } public partial class Setting { /// <summary> /// <see cref="gcrv::SettingName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcrv::SettingName SettingName { get => string.IsNullOrEmpty(Name) ? null : gcrv::SettingName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListSettingsRequest { /// <summary> /// <see cref="gax::IResourceName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gax::IResourceName ParentAsResourceName { get => string.IsNullOrEmpty(Parent) ? null : gax::UnparsedResourceName.Parse(Parent); set => Parent = value?.ToString() ?? ""; } } public partial class GetSettingRequest { /// <summary> /// <see cref="gcrv::SettingName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcrv::SettingName SettingName { get => string.IsNullOrEmpty(Name) ? null : gcrv::SettingName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Globalization; using System.Runtime; using System.Runtime.Serialization; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; namespace System.IdentityModel.Claims { // Examples: // ClaimType ResourceValue ResourceRight // --------------- ---------------- ------------------ // "File" "boot.ini" "Read" // "HairColor" "Brown" "PossessProperty" // "UserName" "Mary" "PossessProperty" // "Service" "MailService" "Access" // "Operation" "ReadMail" "Invoke" // ClaimType: // DESC: The type of resource for which rights are granted // XrML: ClaimSet/Resource // SAML: SamlAttributeStatement/Attribute/@Name/..., SamlAuthorizationDecisionStatement/Action/@Namespace/... // ResourceValue: // DESC: Value identifying the resource for which rights are granted // XrML: ClaimSet/Resource/... // SAML: SamlAttributeStatement/Attribute/..., SamlAuthorizationDecisionStatement/@Resource/... // Right: // DESC: Rights expressed about a resource // XRML: ClaimSet/Right // SAML: SamlAttributeStatement (aka. "PossessProperty") or, SamlAuthorizationDecisionStatement/Action/... [DataContract(Namespace = XsiConstants.Namespace)] public class Claim { private static Claim s_system; [DataMember(Name = "ClaimType")] private string _claimType; [DataMember(Name = "Resource")] private object _resource; [DataMember(Name = "Right")] private string _right; private IEqualityComparer<Claim> _comparer; private Claim(string claimType, object resource, string right, IEqualityComparer<Claim> comparer) { if (claimType == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("claimType"); if (claimType.Length <= 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("claimType", SRServiceModel.ArgumentCannotBeEmptyString); if (right == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("right"); if (right.Length <= 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("right", SRServiceModel.ArgumentCannotBeEmptyString); _claimType = claimType; _resource = resource; _right = right; _comparer = comparer; } public Claim(string claimType, object resource, string right) : this(claimType, resource, right, null) { } public static IEqualityComparer<Claim> DefaultComparer { get { return EqualityComparer<Claim>.Default; } } public static Claim System { get { if (s_system == null) s_system = new Claim(ClaimTypes.System, XsiConstants.System, Rights.Identity); return s_system; } } public object Resource { get { return _resource; } } public string ClaimType { get { return _claimType; } } public string Right { get { return _right; } } // Turn key claims public static Claim CreateDnsClaim(string dns) { if (dns == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("dns"); return new Claim(ClaimTypes.Dns, dns, Rights.PossessProperty, ClaimComparer.Dns); } public static Claim CreateHashClaim(byte[] hash) { if (hash == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("hash"); return new Claim(ClaimTypes.Hash, SecurityUtils.CloneBuffer(hash), Rights.PossessProperty, ClaimComparer.Hash); } public static Claim CreateNameClaim(string name) { if (name == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("name"); return new Claim(ClaimTypes.Name, name, Rights.PossessProperty); } public static Claim CreateSpnClaim(string spn) { if (spn == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("spn"); return new Claim(ClaimTypes.Spn, spn, Rights.PossessProperty); } public static Claim CreateThumbprintClaim(byte[] thumbprint) { if (thumbprint == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("thumbprint"); return new Claim(ClaimTypes.Thumbprint, SecurityUtils.CloneBuffer(thumbprint), Rights.PossessProperty, ClaimComparer.Thumbprint); } #if SUPPORTS_WINDOWSIDENTITY || !disabled public static Claim CreateUpnClaim(string upn) { if (upn == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("upn"); return new Claim(ClaimTypes.Upn, upn, Rights.PossessProperty, ClaimComparer.Upn); } #endif // SUPPORTS_WINDOWSIDENTITY public static Claim CreateUriClaim(Uri uri) { if (uri == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("uri"); return new Claim(ClaimTypes.Uri, uri, Rights.PossessProperty); } #if SUPPORTS_WINDOWSIDENTITY // NegotiateStream public static Claim CreateWindowsSidClaim(SecurityIdentifier sid) { if (sid == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("sid"); return new Claim(ClaimTypes.Sid, sid, Rights.PossessProperty); } #endif // SUPPORTS_WINDOWSIDENTITY public static Claim CreateX500DistinguishedNameClaim(X500DistinguishedName x500DistinguishedName) { if (x500DistinguishedName == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("x500DistinguishedName"); return new Claim(ClaimTypes.X500DistinguishedName, x500DistinguishedName, Rights.PossessProperty, ClaimComparer.X500DistinguishedName); } public override bool Equals(object obj) { if (_comparer == null) _comparer = ClaimComparer.GetComparer(_claimType); return _comparer.Equals(this, obj as Claim); } public override int GetHashCode() { if (_comparer == null) _comparer = ClaimComparer.GetComparer(_claimType); return _comparer.GetHashCode(this); } public override string ToString() { return string.Format(CultureInfo.CurrentCulture, "{0}: {1}", _right, _claimType); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using MvcApplication6.Areas.HelpPage.Models; namespace MvcApplication6.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
namespace Ioke.Lang { using Ioke.Lang.Util; using System.Collections; using System.Collections.Generic; using System.Text; public class InternalBehavior { public static void Init(IokeObject obj) { Runtime runtime = obj.runtime; obj.Kind = "DefaultBehavior Internal"; obj.RegisterMethod(runtime.NewNativeMethod("expects one 'strange' argument. creates a new instance of Text with the given Java String backing it.", new NativeMethod("internal:createText", DefaultArgumentsDefinition .builder() .WithRequiredPositionalUnevaluated("text") .Arguments, (method, context, message, on, outer) => { outer.ArgumentsDefinition.CheckArgumentCount(context, message, on); object o = Message.GetArguments(message)[0]; bool cache = true; if(o is IokeObject) { cache = false; o = Message.GetEvaluatedArgument(o, context); } if(o is string) { string s = (string)o; object value = runtime.NewText(new StringUtils().ReplaceEscapes(s)); if(cache) { Message.CacheValue(message, value); } return value; } else { return IokeObject.ConvertToText(o, message, context, true); } }))); obj.RegisterMethod(runtime.NewNativeMethod("expects one 'strange' argument. creates a new instance of Number that represents the number found in the strange argument.", new NativeMethod("internal:createNumber", DefaultArgumentsDefinition .builder() .WithRequiredPositionalUnevaluated("number") .Arguments, (method, context, message, on, outer) => { outer.ArgumentsDefinition.CheckArgumentCount(context, message, on); object o = Message.GetArguments(message)[0]; bool cache = true; if(o is IokeObject) { cache = false; o = Message.GetEvaluatedArgument(o, context); } object value = null; if(o is string) { value = runtime.NewNumber((string)o); } else if(o is int) { value = runtime.NewNumber((int)o); } if(cache) { Message.CacheValue(message, value); } return value; }))); obj.RegisterMethod(runtime.NewNativeMethod("takes zero or more arguments, calls asText on non-text arguments, and then concatenates them and returns the result.", new NativeMethod("internal:concatenateText", DefaultArgumentsDefinition.builder() .WithRest("textSegments") .Arguments, (method, context, message, on, outer) => { var args = new SaneArrayList(); outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, args, new SaneDictionary<string, object>()); StringBuilder sb = new StringBuilder(); foreach(object o in args) { if(o is IokeObject) { if(IokeObject.dataOf(o) is Text) { sb.Append(Text.GetText(o)); } else { sb.Append(Text.GetText(((Message)IokeObject.dataOf(context.runtime.asText)).SendTo(context.runtime.asText, context, o))); } } else { sb.Append(o); } } return context.runtime.NewText(sb.ToString()); }))); obj.RegisterMethod(runtime.NewNativeMethod("takes one or more arguments. it expects the last argument to be a text of flags, while the rest of the arguments are either texts or regexps or nil. if text, it will be inserted verbatim into the result regexp. if regexp it will be inserted into a group that make sure the flags of the regexp is preserved. if nil, nothing will be inserted.", new NativeMethod("internal:compositeRegexp", DefaultArgumentsDefinition.builder() .WithRest("regexpSegments") .Arguments, (method, context, message, on, outer) => { var args = new SaneArrayList(); outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, args, new SaneDictionary<string, object>()); StringBuilder sb = new StringBuilder(); if((IokeObject.dataOf(on) is Text) || (IokeObject.dataOf(on) is Regexp)) { AddObject(on, sb, context); } int size = args.Count; foreach(object o in ArrayList.Adapter(args).GetRange(0, size-1)) { AddObject(o, sb, context); } object f = args[size-1]; string flags = null; if(f is string) { flags = (string)f; } else if(IokeObject.dataOf(f) is Text) { flags = Text.GetText(f); } else if(IokeObject.dataOf(f) is Regexp) { sb.Append(Regexp.GetPattern(f)); flags = Regexp.GetFlags(f); } return context.runtime.NewRegexp(sb.ToString(), flags, context, message); }))); obj.RegisterMethod(runtime.NewNativeMethod("expects two 'strange' arguments. creates a new mimic of Regexp with the given Java String backing it.", new NativeMethod("internal:createRegexp", DefaultArgumentsDefinition.builder() .WithRequiredPositionalUnevaluated("regexp") .WithRequiredPositionalUnevaluated("flags") .Arguments, (method, context, message, on, outer) => { outer.ArgumentsDefinition.CheckArgumentCount(context, message, on); object o = Message.GetArguments(message)[0]; object o2 = Message.GetArguments(message)[1]; if(o is IokeObject) { o = Message.GetEvaluatedArgument(o, context); } if(o2 is IokeObject) { o2 = Message.GetEvaluatedArgument(o2, context); } if(o is string) { string s = (string)o; return runtime.NewRegexp(new StringUtils().ReplaceRegexpEscapes(s), (string)o2, context, message); } else { return IokeObject.ConvertToRegexp(o, message, context); } }))); obj.RegisterMethod(runtime.NewNativeMethod("expects one 'strange' argument. creates a new instance of Decimal that represents the number found in the strange argument.", new NativeMethod("internal:createDecimal", DefaultArgumentsDefinition.builder() .WithRequiredPositionalUnevaluated("decimal") .Arguments, (method, context, message, on, outer) => { outer.ArgumentsDefinition.CheckArgumentCount(context, message, on); object o = Message.GetArguments(message)[0]; bool cache = true; if(o is IokeObject) { cache = false; o = Message.GetEvaluatedArgument(o, context); } object value = runtime.NewDecimal((string)o); if(cache) { Message.CacheValue(message, value); } return value; }))); } private static void AddRegexp(object o, StringBuilder sb) { string f = Regexp.GetFlags(o); string nflags = ""; if(f.IndexOf("i") == -1) { nflags += "i"; } if(f.IndexOf("x") == -1) { nflags += "x"; } if(f.IndexOf("m") == -1) { nflags += "m"; } if(f.IndexOf("u") == -1) { nflags += "u"; } if(f.IndexOf("s") == -1) { nflags += "s"; } if(nflags.Length > 0) { nflags = "-" + nflags; } sb.Append("(?").Append(f).Append(nflags).Append(":").Append(Regexp.GetPattern(o)).Append(")"); } private static void AddText(object o, StringBuilder sb) { sb.Append(Text.GetText(o)); } public static void AddObject(object o, StringBuilder sb, IokeObject context) { if(o != null) { if(o is string) { sb.Append(o); } else if(IokeObject.dataOf(o) is Text) { AddText(o, sb); } else if(IokeObject.dataOf(o) is Regexp) { AddRegexp(o, sb); } else { AddText(((Message)IokeObject.dataOf(context.runtime.asText)).SendTo(context.runtime.asText, context, o), sb); } } } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Reactive.Linq; using System.Threading.Tasks; using Avalonia.Controls.Platform; using Avalonia.Input; using Avalonia.Layout; using Avalonia.Media; using Avalonia.Platform; using Avalonia.Styling; using System.Collections.Generic; namespace Avalonia.Controls { /// <summary> /// Determines how a <see cref="Window"/> will size itself to fit its content. /// </summary> public enum SizeToContent { /// <summary> /// The window will not automatically size itself to fit its content. /// </summary> Manual, /// <summary> /// The window will size itself horizontally to fit its content. /// </summary> Width, /// <summary> /// The window will size itself vertically to fit its content. /// </summary> Height, /// <summary> /// The window will size itself horizontally and vertically to fit its content. /// </summary> WidthAndHeight, } /// <summary> /// A top-level window. /// </summary> public class Window : TopLevel, IStyleable, IFocusScope, ILayoutRoot, INameScope { private static IList<Window> s_windows = new List<Window>(); /// <summary> /// Retrieves an enumeration of all Windows in the currently running application. /// </summary> public static IList<Window> OpenWindows => s_windows; /// <summary> /// Defines the <see cref="SizeToContent"/> property. /// </summary> public static readonly StyledProperty<SizeToContent> SizeToContentProperty = AvaloniaProperty.Register<Window, SizeToContent>(nameof(SizeToContent)); /// <summary> /// Enables of disables system window decorations (title bar, buttons, etc) /// </summary> public static readonly StyledProperty<bool> HasSystemDecorationsProperty = AvaloniaProperty.Register<Window, bool>(nameof(HasSystemDecorations), true); /// <summary> /// Defines the <see cref="Title"/> property. /// </summary> public static readonly StyledProperty<string> TitleProperty = AvaloniaProperty.Register<Window, string>(nameof(Title), "Window"); /// <summary> /// Defines the <see cref="Icon"/> property. /// </summary> public static readonly StyledProperty<WindowIcon> IconProperty = AvaloniaProperty.Register<Window, WindowIcon>(nameof(Icon)); private readonly NameScope _nameScope = new NameScope(); private object _dialogResult; private readonly Size _maxPlatformClientSize; /// <summary> /// Initializes static members of the <see cref="Window"/> class. /// </summary> static Window() { BackgroundProperty.OverrideDefaultValue(typeof(Window), Brushes.White); TitleProperty.Changed.AddClassHandler<Window>((s, e) => s.PlatformImpl.SetTitle((string)e.NewValue)); HasSystemDecorationsProperty.Changed.AddClassHandler<Window>( (s, e) => s.PlatformImpl.SetSystemDecorations((bool) e.NewValue)); IconProperty.Changed.AddClassHandler<Window>((s, e) => s.PlatformImpl.SetIcon(((WindowIcon)e.NewValue).PlatformImpl)); } /// <summary> /// Initializes a new instance of the <see cref="Window"/> class. /// </summary> public Window() : this(PlatformManager.CreateWindow()) { } /// <summary> /// Initializes a new instance of the <see cref="Window"/> class. /// </summary> /// <param name="impl">The window implementation.</param> public Window(IWindowImpl impl) : base(impl) { _maxPlatformClientSize = this.PlatformImpl.MaxClientSize; } /// <inheritdoc/> event EventHandler<NameScopeEventArgs> INameScope.Registered { add { _nameScope.Registered += value; } remove { _nameScope.Registered -= value; } } /// <inheritdoc/> event EventHandler<NameScopeEventArgs> INameScope.Unregistered { add { _nameScope.Unregistered += value; } remove { _nameScope.Unregistered -= value; } } /// <summary> /// Gets the platform-specific window implementation. /// </summary> public new IWindowImpl PlatformImpl => (IWindowImpl)base.PlatformImpl; /// <summary> /// Gets or sets a value indicating how the window will size itself to fit its content. /// </summary> public SizeToContent SizeToContent { get { return GetValue(SizeToContentProperty); } set { SetValue(SizeToContentProperty, value); } } /// <summary> /// Gets or sets the title of the window. /// </summary> public string Title { get { return GetValue(TitleProperty); } set { SetValue(TitleProperty, value); } } /// <summary> /// Enables of disables system window decorations (title bar, buttons, etc) /// </summary> /// public bool HasSystemDecorations { get { return GetValue(HasSystemDecorationsProperty); } set { SetValue(HasSystemDecorationsProperty, value); } } /// <summary> /// Gets or sets the minimized/maximized state of the window. /// </summary> public WindowState WindowState { get { return this.PlatformImpl.WindowState; } set { this.PlatformImpl.WindowState = value; } } /// <summary> /// Gets or sets the icon of the window. /// </summary> public WindowIcon Icon { get { return GetValue(IconProperty); } set { SetValue(IconProperty, value); } } /// <inheritdoc/> Size ILayoutRoot.MaxClientSize => _maxPlatformClientSize; /// <inheritdoc/> Type IStyleable.StyleKey => typeof(Window); /// <summary> /// Closes the window. /// </summary> public void Close() { s_windows.Remove(this); PlatformImpl.Dispose(); } protected override void HandleApplicationExiting() { base.HandleApplicationExiting(); Close(); } /// <summary> /// Closes a dialog window with the specified result. /// </summary> /// <param name="dialogResult">The dialog result.</param> /// <remarks> /// When the window is shown with the <see cref="ShowDialog{TResult}"/> method, the /// resulting task will produce the <see cref="_dialogResult"/> value when the window /// is closed. /// </remarks> public void Close(object dialogResult) { _dialogResult = dialogResult; Close(); } /// <summary> /// Hides the window but does not close it. /// </summary> public void Hide() { using (BeginAutoSizing()) { PlatformImpl.Hide(); } } /// <summary> /// Shows the window. /// </summary> public void Show() { s_windows.Add(this); EnsureInitialized(); LayoutManager.Instance.ExecuteInitialLayoutPass(this); using (BeginAutoSizing()) { PlatformImpl.Show(); } } /// <summary> /// Shows the window as a dialog. /// </summary> /// <returns> /// A task that can be used to track the lifetime of the dialog. /// </returns> public Task ShowDialog() { return ShowDialog<object>(); } /// <summary> /// Shows the window as a dialog. /// </summary> /// <typeparam name="TResult"> /// The type of the result produced by the dialog. /// </typeparam> /// <returns>. /// A task that can be used to retrive the result of the dialog when it closes. /// </returns> public Task<TResult> ShowDialog<TResult>() { s_windows.Add(this); EnsureInitialized(); LayoutManager.Instance.ExecuteInitialLayoutPass(this); using (BeginAutoSizing()) { var modal = PlatformImpl.ShowDialog(); var result = new TaskCompletionSource<TResult>(); Observable.FromEventPattern(this, nameof(Closed)) .Take(1) .Subscribe(_ => { modal.Dispose(); result.SetResult((TResult)_dialogResult); }); return result.Task; } } /// <inheritdoc/> void INameScope.Register(string name, object element) { _nameScope.Register(name, element); } /// <inheritdoc/> object INameScope.Find(string name) { return _nameScope.Find(name); } /// <inheritdoc/> void INameScope.Unregister(string name) { _nameScope.Unregister(name); } /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { var sizeToContent = SizeToContent; var size = ClientSize; var desired = base.MeasureOverride(availableSize.Constrain(_maxPlatformClientSize)); switch (sizeToContent) { case SizeToContent.Width: size = new Size(desired.Width, ClientSize.Height); break; case SizeToContent.Height: size = new Size(ClientSize.Width, desired.Height); break; case SizeToContent.WidthAndHeight: size = new Size(desired.Width, desired.Height); break; case SizeToContent.Manual: size = ClientSize; break; default: throw new InvalidOperationException("Invalid value for SizeToContent."); } return size; } /// <inheritdoc/> protected override void HandleResized(Size clientSize) { if (!AutoSizing) { SizeToContent = SizeToContent.Manual; } base.HandleResized(clientSize); } private void EnsureInitialized() { if (!this.IsInitialized) { var init = (ISupportInitialize)this; init.BeginInit(); init.EndInit(); } } } } namespace Avalonia { public static class WindowApplicationExtensions { public static void RunWithMainWindow<TWindow>(this Application app) where TWindow : Avalonia.Controls.Window, new() { var window = new TWindow(); window.Show(); app.Run(window); } } }
using UnityEngine; using UnityEditor; using System.IO; using System.Xml; using System.Xml.Serialization; using System.Collections.Generic; namespace PixelCrushers.DialogueSystem { /// <summary> /// This is a base class for custom converter windows. /// </summary> public class AbstractConverterWindow : EditorWindow { /// <summary> /// Gets the source file extension. /// </summary> /// <value>The source file extension (e.g., 'xml' for XML files).</value> public virtual string SourceFileExtension { get { return string.Empty; } } /// <summary> /// Gets the EditorPrefs key to save the converter window's settings under. /// </summary> /// <value>The EditorPrefs key.</value> public virtual string PrefsKey { get { return UndefinedPrefsKey; } } /// <summary> /// An undefined prefs key. /// </summary> private const string UndefinedPrefsKey = "UndefinedConverterKey"; /// <summary> /// This is the base prefs (converter window settings) class. The converter /// window uses an instance of this class, or a subclass if you need /// additional info, to store the user's current settings. /// </summary> [System.Serializable] public class Prefs { /// <summary> /// The source filename. This file gets converted into a dialogue database. /// </summary> public string sourceFilename = string.Empty; /// <summary> /// The output folder in which to create the dialogue database. /// </summary> public string outputFolder = "Assets"; /// <summary> /// The name of the dialogue database. /// </summary> public string databaseFilename = "Dialogue Database"; /// <summary> /// If <c>true</c>, the converter may overwrite the dialogue database /// if it already exists. /// </summary> public bool overwrite = false; /// <summary> /// If <c>true</c> and overwriting, merge assets into the existing database /// instead of replacing it. /// </summary> public bool merge = false; /// <summary> /// The encoding type to use when reading the source file. /// </summary> public EncodingType encodingType = EncodingType.Default; public Prefs() {} /// <summary> /// This method reads prefs from EditorPrefs or creates it if it doesn't exist. /// </summary> /// <param name="key">EditorPrefs key.</param> public static Prefs Load(string key) { WarnIfKeyUndefined(key); string xml = EditorPrefs.GetString(key); Prefs prefs = null; if (!string.IsNullOrEmpty(xml)) { XmlSerializer xmlSerializer = new XmlSerializer(typeof(Prefs)); prefs = xmlSerializer.Deserialize(new StringReader(xml)) as Prefs; } return prefs ?? new Prefs(); } /// <summary> /// This method saves prefs to EditorPrefs. /// </summary> /// <param name="key">Key.</param> /// <param name="prefs">EditorPrefs key.</param> public static void Save(string key, Prefs prefs) { WarnIfKeyUndefined(key); XmlSerializer xmlSerializer = new XmlSerializer(typeof(Prefs)); StringWriter writer = new StringWriter(); xmlSerializer.Serialize(writer, prefs); EditorPrefs.SetString(key, writer.ToString()); } protected static void WarnIfKeyUndefined(string key) { if (string.Equals(key, UndefinedPrefsKey)) { Debug.LogWarning(string.Format("{0}: The converter preferences key hasn't been specified. " + "Check your converter script.", DialogueDebug.Prefix)); } } } /// <summary> /// The prefs for the converter window. /// </summary> protected Prefs prefs = null; /// <summary> /// A reference to the Dialogue System template, used to create new dialogue database /// assets such as Actors, Items, and Conversations. /// </summary> protected Template template = null; /// <summary> /// The current scroll position of the converter window. If the contents of the window /// are larger than the current window size, the user can scroll up and down. /// </summary> protected Vector2 scrollPosition = Vector2.zero; /// <summary> /// The most recent line retrieved through the GetNextSourceLine() method. /// </summary> public string currentSourceLine { get; private set; } /// <summary> /// The line number in the source file of the current source line. /// </summary> public int currentLineNumber { get; private set; } public virtual void OnEnable() { LoadPrefs(); } public virtual void OnDisable() { SavePrefs(); } protected virtual void ClearPrefs() { prefs = new Prefs(); } protected virtual void LoadPrefs() { prefs = Prefs.Load(PrefsKey); } protected virtual void SavePrefs() { Prefs.Save(PrefsKey, prefs); } public virtual void OnGUI() { if (prefs == null) LoadPrefs(); scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition); try { DrawControls(); } finally { EditorGUILayout.EndScrollView(); } } /// <summary> /// Draws the contents of the converter window. You can override this if /// you want to draw more than the "source section" and "destination section". /// </summary> protected virtual void DrawControls() { DrawSourceSection(); DrawDestinationSection(); DrawConversionButtons(); } /// <summary> /// Draws the source section. You can override this if you want to draw more /// than the Source File selection field. /// </summary> protected virtual void DrawSourceSection() { EditorGUILayout.BeginHorizontal(); prefs.sourceFilename = EditorGUILayout.TextField("Source File", prefs.sourceFilename); if (GUILayout.Button("...", EditorStyles.miniButton, GUILayout.Width(22))) { prefs.sourceFilename = EditorUtility.OpenFilePanel("Select Source File", EditorWindowTools.GetDirectoryName(prefs.sourceFilename), SourceFileExtension); GUIUtility.keyboardControl = 0; } EditorGUILayout.EndHorizontal(); } /// <summary> /// Draws the destination section. You can override this if you want to draw /// more than the default controls. /// </summary> protected virtual void DrawDestinationSection() { EditorWindowTools.DrawHorizontalLine(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Save As", EditorStyles.boldLabel); GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); EditorWindowTools.StartIndentedSection(); DrawOutputFolder(); DrawDatabaseFilename(); DrawEncodingPopup(); DrawOverwriteCheckbox(); EditorWindowTools.EndIndentedSection(); } /// <summary> /// Draws the output folder selection field. /// </summary> protected virtual void DrawOutputFolder() { EditorGUILayout.BeginHorizontal(); prefs.outputFolder = EditorGUILayout.TextField("Output Folder", prefs.outputFolder); if (GUILayout.Button("...", EditorStyles.miniButton, GUILayout.Width(22))) { prefs.outputFolder = EditorUtility.SaveFolderPanel("Folder to Save Database", prefs.outputFolder, ""); prefs.outputFolder = "Assets" + prefs.outputFolder.Replace(Application.dataPath, string.Empty); GUIUtility.keyboardControl = 0; } EditorGUILayout.EndHorizontal(); } /// <summary> /// Draws the dialogue database save-to filename. /// </summary> protected virtual void DrawDatabaseFilename() { prefs.databaseFilename = EditorGUILayout.TextField("Database Filename", prefs.databaseFilename); } /// <summary> /// Draws the encoding type popup. /// </summary> protected virtual void DrawEncodingPopup() { prefs.encodingType = (EncodingType) EditorGUILayout.EnumPopup("Encoding", prefs.encodingType, GUILayout.Width(300)); } /// <summary> /// Draws the overwrite checkbox, and merge checkbox if overwrite is ticked. /// </summary> protected virtual void DrawOverwriteCheckbox() { prefs.overwrite = EditorGUILayout.Toggle(new GUIContent("Overwrite", "Overwrite database if it already exists"), prefs.overwrite); if (prefs.overwrite) { prefs.merge = EditorGUILayout.Toggle(new GUIContent("Merge", "Merge into existing database instead of overwriting"), prefs.merge); } } /// <summary> /// Draws the conversion buttons. You can override this to change /// what buttons are drawn. /// </summary> protected virtual void DrawConversionButtons() { EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); DrawClearButton(); DrawConvertButton(); EditorGUILayout.EndHorizontal(); } /// <summary> /// Draws the Clear button that clears the prefs. /// </summary> protected virtual void DrawClearButton() { if (GUILayout.Button("Clear", GUILayout.Width(100))) { ClearPrefs(); } } /// <summary> /// Draws the Convert button that calls Convert(). /// </summary> protected virtual void DrawConvertButton() { var isReady = IsReadyToConvert(); EditorGUI.BeginDisabledGroup(!isReady); try { if (GUILayout.Button("Convert", GUILayout.Width(100))) Convert(); } finally { EditorGUI.EndDisabledGroup(); } } /// <summary> /// Determines whether the window is ready to convert. Override this if you /// need to check more than the source, output folder, and database filename. /// </summary> /// <returns><c>true</c> if this instance is ready to convert; otherwise, <c>false</c>.</returns> protected virtual bool IsReadyToConvert() { return !string.IsNullOrEmpty(prefs.databaseFilename) && !string.IsNullOrEmpty(prefs.outputFolder) && IsSourceAssigned(); } /// <summary> /// Determines whether the source is assigned. Override this if, for /// example, your converter pulls from more than one source file. /// </summary> /// <returns><c>true</c> if this instance is source assigned; otherwise, <c>false</c>.</returns> protected virtual bool IsSourceAssigned() { return !string.IsNullOrEmpty(prefs.sourceFilename); } /// <summary> /// Converts the source into a dialogue database. This method does housekeeping such /// as creating the empty asset and saving it at the end, but the main work is /// done in the CopySourceToDialogueDatabase() method that you must implement. /// </summary> protected virtual void Convert() { DialogueDatabase database = LoadOrCreateDatabase(); if (database == null) { Debug.LogError(string.Format("{0}: Couldn't create asset '{1}'.", DialogueDebug.Prefix, prefs.databaseFilename)); } else { if (template == null) template = TemplateTools.LoadFromEditorPrefs(); CopySourceToDialogueDatabase(database); TouchUpDialogueDatabase(database); EditorUtility.SetDirty(database); AssetDatabase.SaveAssets(); Debug.Log(string.Format("{0}: Created database '{1}' containing {2} actors, {3} conversations, {4} items/quests, {5} variables, and {6} locations.", DialogueDebug.Prefix, prefs.databaseFilename, database.actors.Count, database.conversations.Count, database.items.Count, database.variables.Count, database.locations.Count)); } } /// <summary> /// Loads the dialogue database if it already exists and overwrite is ticked; otherwise creates a new one. /// </summary> /// <returns> /// The database. /// </returns> /// <param name='filename'> /// Asset filename. /// </param> protected virtual DialogueDatabase LoadOrCreateDatabase() { string assetPath = string.Format("{0}/{1}.asset", prefs.outputFolder, prefs.databaseFilename); DialogueDatabase database = null; if (prefs.overwrite) { database = AssetDatabase.LoadAssetAtPath(assetPath, typeof(DialogueDatabase)) as DialogueDatabase; if ((database != null) && !prefs.merge) database.Clear(); } if (database == null) { assetPath = AssetDatabase.GenerateUniqueAssetPath(string.Format("{0}/{1}.asset", prefs.outputFolder, prefs.databaseFilename)); database = ScriptableObject.CreateInstance<DialogueDatabase>(); database.name = prefs.databaseFilename; AssetDatabase.CreateAsset(database, assetPath); } return database; } /// <summary> /// Touches up dialogue database after conversion. This base version sets the START /// dialogue entries' Sequence fields to None(). Override this method if you want to /// do something different. /// </summary> /// <param name="database">Database.</param> protected virtual void TouchUpDialogueDatabase(DialogueDatabase database) { SetStartCutscenesToNone(database); //--- You could add this if you define portraitFolder: FindPortraitTextures(database, portraitFolder); } /// <summary> /// Sets the START dialogue entries' Sequences to None(). /// </summary> /// <param name="database">Database.</param> protected virtual void SetStartCutscenesToNone(DialogueDatabase database) { foreach (var conversation in database.conversations) { SetConversationStartCutsceneToNone(conversation); } } /// <summary> /// Sets a conversation's START entry's Sequence to None(). /// </summary> /// <param name="conversation">Conversation.</param> protected virtual void SetConversationStartCutsceneToNone(Conversation conversation) { DialogueEntry entry = conversation.GetFirstDialogueEntry(); if (entry == null) { Debug.LogWarning(string.Format("{0}: Conversation '{1}' doesn't have a START dialogue entry.", DialogueDebug.Prefix, conversation.Title)); } else { if (string.IsNullOrEmpty(entry.Sequence)) { if (Field.FieldExists(entry.fields, "Sequence")) { entry.Sequence = "None()"; } else { entry.fields.Add(new Field("Sequence", "None()", FieldType.Text)); } } } } /// <summary> /// Finds the actors' portrait textures, given a source portrait folder. /// </summary> /// <param name="database">Database.</param> /// <param name="portraitFolder">Portrait folder.</param> protected virtual void FindPortraitTextures(DialogueDatabase database, string portraitFolder) { foreach (var actor in database.actors) { FindPortraitTexture(actor, portraitFolder); } } /// <summary> /// Finds an actor's portrait texture. /// </summary> /// <param name="actor">Actor.</param> /// <param name="portraitFolder">Portrait folder.</param> protected virtual void FindPortraitTexture(Actor actor, string portraitFolder) { if (actor == null) return; string textureName = actor.TextureName; if (!string.IsNullOrEmpty(textureName)) { string filename = Path.GetFileName(textureName).Replace('\\', '/'); string assetPath = string.Format("{0}/{1}", portraitFolder, filename); Texture2D texture = AssetDatabase.LoadAssetAtPath(assetPath, typeof(Texture2D)) as Texture2D; if (texture == null) { Debug.LogWarning(string.Format("{0}: Can't find portrait texture {1} for {2}.", DialogueDebug.Prefix, assetPath, actor.Name)); } actor.portrait = texture; } } /// <summary> /// Copies the source to the dialogue database. You must implement this. You can /// use the helper methods LoadSourceFile(), IsSourceAtEnd(), PeekNextSourceLine(), /// and GetNextSourceLine(). /// </summary> /// <param name="database">Database.</param> protected virtual void CopySourceToDialogueDatabase(DialogueDatabase database) { } /// <summary> /// The source lines. /// </summary> protected List<string> sourceLines = new List<string>(); /// <summary> /// Loads the source file into memory. /// </summary> protected virtual void LoadSourceFile() { sourceLines.Clear(); var file = new StreamReader(prefs.sourceFilename); string line; while ((line = file.ReadLine()) != null) { sourceLines.Add(line.TrimEnd()); } file.Close(); currentSourceLine = string.Empty; currentLineNumber = 0; } /// <summary> /// Determines whether the source data's memory buffer is at the end. /// </summary> /// <returns><c>true</c> if source at end; otherwise, <c>false</c>.</returns> protected virtual bool IsSourceAtEnd() { return sourceLines.Count == 0; } /// <summary> /// Peeks the next source line without removing it from the buffer. /// </summary> /// <returns>The next source line.</returns> protected virtual string PeekNextSourceLine() { return (sourceLines.Count > 0) ? sourceLines[0] : string.Empty; } /// <summary> /// Gets the next source line and removes it from the buffer. /// </summary> /// <returns>The next source line.</returns> protected virtual string GetNextSourceLine() { if (sourceLines.Count > 0) { string s = sourceLines[0]; sourceLines.RemoveAt(0); currentSourceLine = s; currentLineNumber++; return s; } else { throw new EndOfStreamException("Unexpected end of file in " + prefs.sourceFilename); } } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// User interaction: Tweets. /// </summary> public class UserTweets_Core : TypeCore, IUserInteraction { public UserTweets_Core() { this._TypeId = 282; this._Id = "UserTweets"; this._Schema_Org_Url = "http://schema.org/UserTweets"; string label = ""; GetLabel(out label, "UserTweets", typeof(UserTweets_Core)); this._Label = label; this._Ancestors = new int[]{266,98,277}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{277}; this._Properties = new int[]{67,108,143,229,19,71,82,130,151,158,214,216,218}; } /// <summary> /// A person attending the event. /// </summary> private Attendees_Core attendees; public Attendees_Core Attendees { get { return attendees; } set { attendees = value; SetPropertyInstance(attendees); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// The duration of the item (movie, audio recording, event, etc.) in <a href=\http://en.wikipedia.org/wiki/ISO_8601\ target=\new\>ISO 8601 date format</a>. /// </summary> private Properties.Duration_Core duration; public Properties.Duration_Core Duration { get { return duration; } set { duration = value; SetPropertyInstance(duration); } } /// <summary> /// The end date and time of the event (in <a href=\http://en.wikipedia.org/wiki/ISO_8601\ target=\new\>ISO 8601 date format</a>). /// </summary> private EndDate_Core endDate; public EndDate_Core EndDate { get { return endDate; } set { endDate = value; SetPropertyInstance(endDate); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// The location of the event or organization. /// </summary> private Location_Core location; public Location_Core Location { get { return location; } set { location = value; SetPropertyInstance(location); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// An offer to sell this item\u2014for example, an offer to sell a product, the DVD of a movie, or tickets to an event. /// </summary> private Offers_Core offers; public Offers_Core Offers { get { return offers; } set { offers = value; SetPropertyInstance(offers); } } /// <summary> /// The main performer or performers of the event\u2014for example, a presenter, musician, or actor. /// </summary> private Performers_Core performers; public Performers_Core Performers { get { return performers; } set { performers = value; SetPropertyInstance(performers); } } /// <summary> /// The start date and time of the event (in <a href=\http://en.wikipedia.org/wiki/ISO_8601\ target=\new\>ISO 8601 date format</a>). /// </summary> private StartDate_Core startDate; public StartDate_Core StartDate { get { return startDate; } set { startDate = value; SetPropertyInstance(startDate); } } /// <summary> /// Events that are a part of this event. For example, a conference event includes many presentations, each are subEvents of the conference. /// </summary> private SubEvents_Core subEvents; public SubEvents_Core SubEvents { get { return subEvents; } set { subEvents = value; SetPropertyInstance(subEvents); } } /// <summary> /// An event that this event is a part of. For example, a collection of individual music performances might each have a music festival as their superEvent. /// </summary> private SuperEvent_Core superEvent; public SuperEvent_Core SuperEvent { get { return superEvent; } set { superEvent = value; SetPropertyInstance(superEvent); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace react.net_sample.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using Kitware.VTK; using System; // input file is C:\VTK\Graphics\Testing\Tcl\EnSight6OfficeBin.tcl // output file is AVEnSight6OfficeBin.cs /// <summary> /// The testing class derived from AVEnSight6OfficeBin /// </summary> public class AVEnSight6OfficeBinClass { /// <summary> /// The main entry method called by the CSharp driver /// </summary> /// <param name="argv"></param> public static void AVEnSight6OfficeBin(String [] argv) { //Prefix Content is: "" ren1 = vtkRenderer.New(); renWin = vtkRenderWindow.New(); renWin.AddRenderer((vtkRenderer)ren1); iren = new vtkRenderWindowInteractor(); iren.SetRenderWindow((vtkRenderWindow)renWin); // read data[] //[] reader = new vtkGenericEnSightReader(); // Make sure all algorithms use the composite data pipeline[] cdp = new vtkCompositeDataPipeline(); vtkGenericEnSightReader.SetDefaultExecutivePrototype((vtkExecutive)cdp); //skipping Delete cdp reader.SetCaseFileName((string)"" + (VTK_DATA_ROOT.ToString()) + "/Data/EnSight/office6_bin.case"); reader.Update(); // to add coverage for vtkOnePieceExtentTranslator[] translator = new vtkOnePieceExtentTranslator(); vtkStreamingDemandDrivenPipeline.SetExtentTranslator(reader.GetOutputInformation(0), (vtkExtentTranslator)translator); outline = new vtkStructuredGridOutlineFilter(); outline.SetInputConnection((vtkAlgorithmOutput)reader.GetOutputPort()); mapOutline = new vtkHierarchicalPolyDataMapper(); mapOutline.SetInputConnection((vtkAlgorithmOutput)outline.GetOutputPort()); outlineActor = new vtkActor(); outlineActor.SetMapper((vtkMapper)mapOutline); outlineActor.GetProperty().SetColor((double)0,(double)0,(double)0); // Create source for streamtubes[] streamer = new vtkStreamPoints(); streamer.SetInputConnection((vtkAlgorithmOutput)reader.GetOutputPort()); streamer.SetStartPosition((double)0.1,(double)2.1,(double)0.5); streamer.SetMaximumPropagationTime((double)500); streamer.SetTimeIncrement((double)0.5); streamer.SetIntegrationDirectionToForward(); cone = new vtkConeSource(); cone.SetResolution((int)8); cones = new vtkGlyph3D(); cones.SetInputConnection((vtkAlgorithmOutput)streamer.GetOutputPort()); cones.SetSourceConnection(cone.GetOutputPort()); cones.SetScaleFactor((double)0.9); cones.SetScaleModeToScaleByVector(); mapCones = new vtkHierarchicalPolyDataMapper(); mapCones.SetInputConnection((vtkAlgorithmOutput)cones.GetOutputPort()); mapCones.SetScalarRange((double)((vtkDataSet)reader.GetOutput().GetBlock((uint)0)).GetScalarRange()[0], (double)((vtkDataSet)reader.GetOutput().GetBlock((uint)0)).GetScalarRange()[1]); conesActor = new vtkActor(); conesActor.SetMapper((vtkMapper)mapCones); ren1.AddActor((vtkProp)outlineActor); ren1.AddActor((vtkProp)conesActor); ren1.SetBackground((double)0.4,(double)0.4,(double)0.5); renWin.SetSize((int)300,(int)300); iren.Initialize(); // interact with data[] vtkGenericEnSightReader.SetDefaultExecutivePrototype(null); //deleteAllVTKObjects(); } static string VTK_DATA_ROOT; static int threshold; static vtkRenderer ren1; static vtkRenderWindow renWin; static vtkRenderWindowInteractor iren; static vtkGenericEnSightReader reader; static vtkCompositeDataPipeline cdp; static vtkOnePieceExtentTranslator translator; static vtkStructuredGridOutlineFilter outline; static vtkHierarchicalPolyDataMapper mapOutline; static vtkActor outlineActor; static vtkStreamPoints streamer; static vtkConeSource cone; static vtkGlyph3D cones; static vtkHierarchicalPolyDataMapper mapCones; static vtkActor conesActor; ///<summary> A Get Method for Static Variables </summary> public static string GetVTK_DATA_ROOT() { return VTK_DATA_ROOT; } ///<summary> A Set Method for Static Variables </summary> public static void SetVTK_DATA_ROOT(string toSet) { VTK_DATA_ROOT = toSet; } ///<summary> A Get Method for Static Variables </summary> public static int Getthreshold() { return threshold; } ///<summary> A Set Method for Static Variables </summary> public static void Setthreshold(int toSet) { threshold = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRenderer Getren1() { return ren1; } ///<summary> A Set Method for Static Variables </summary> public static void Setren1(vtkRenderer toSet) { ren1 = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRenderWindow GetrenWin() { return renWin; } ///<summary> A Set Method for Static Variables </summary> public static void SetrenWin(vtkRenderWindow toSet) { renWin = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRenderWindowInteractor Getiren() { return iren; } ///<summary> A Set Method for Static Variables </summary> public static void Setiren(vtkRenderWindowInteractor toSet) { iren = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkGenericEnSightReader Getreader() { return reader; } ///<summary> A Set Method for Static Variables </summary> public static void Setreader(vtkGenericEnSightReader toSet) { reader = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkCompositeDataPipeline Getcdp() { return cdp; } ///<summary> A Set Method for Static Variables </summary> public static void Setcdp(vtkCompositeDataPipeline toSet) { cdp = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkOnePieceExtentTranslator Gettranslator() { return translator; } ///<summary> A Set Method for Static Variables </summary> public static void Settranslator(vtkOnePieceExtentTranslator toSet) { translator = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkStructuredGridOutlineFilter Getoutline() { return outline; } ///<summary> A Set Method for Static Variables </summary> public static void Setoutline(vtkStructuredGridOutlineFilter toSet) { outline = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkHierarchicalPolyDataMapper GetmapOutline() { return mapOutline; } ///<summary> A Set Method for Static Variables </summary> public static void SetmapOutline(vtkHierarchicalPolyDataMapper toSet) { mapOutline = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetoutlineActor() { return outlineActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetoutlineActor(vtkActor toSet) { outlineActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkStreamPoints Getstreamer() { return streamer; } ///<summary> A Set Method for Static Variables </summary> public static void Setstreamer(vtkStreamPoints toSet) { streamer = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkConeSource Getcone() { return cone; } ///<summary> A Set Method for Static Variables </summary> public static void Setcone(vtkConeSource toSet) { cone = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkGlyph3D Getcones() { return cones; } ///<summary> A Set Method for Static Variables </summary> public static void Setcones(vtkGlyph3D toSet) { cones = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkHierarchicalPolyDataMapper GetmapCones() { return mapCones; } ///<summary> A Set Method for Static Variables </summary> public static void SetmapCones(vtkHierarchicalPolyDataMapper toSet) { mapCones = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetconesActor() { return conesActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetconesActor(vtkActor toSet) { conesActor = toSet; } ///<summary>Deletes all static objects created</summary> public static void deleteAllVTKObjects() { //clean up vtk objects if(ren1!= null){ren1.Dispose();} if(renWin!= null){renWin.Dispose();} if(iren!= null){iren.Dispose();} if(reader!= null){reader.Dispose();} if(cdp!= null){cdp.Dispose();} if(translator!= null){translator.Dispose();} if(outline!= null){outline.Dispose();} if(mapOutline!= null){mapOutline.Dispose();} if(outlineActor!= null){outlineActor.Dispose();} if(streamer!= null){streamer.Dispose();} if(cone!= null){cone.Dispose();} if(cones!= null){cones.Dispose();} if(mapCones!= null){mapCones.Dispose();} if(conesActor!= null){conesActor.Dispose();} } } //--- end of script --//
using System; using System.Collections; using System.Collections.Generic; using Game; using Game.Enums; using JetBrains.Annotations; using Mod; using Mod.Exceptions; using Mod.GameSettings; using Mod.Managers; using Mod.Modules; using Photon; using Photon.Enums; using RC; using UnityEngine; // ReSharper disable once CheckNamespace public class FEMALE_TITAN : Photon.MonoBehaviour { private Vector3 abnorma_jump_bite_horizon_v; public int AnkleLHP = 200; private int AnkleLHPMAX = 200; public int AnkleRHP = 200; private int AnkleRHPMAX = 200; private string attackAnimation; private float attackCheckTime; private float attackCheckTimeA; private float attackCheckTimeB; private bool attackChkOnce; public float attackDistance = 13f; private bool attacked; public float attackWait = 1f; private float attention = 10f; public GameObject bottomObject; public float chaseDistance = 80f; private Transform checkHitCapsuleEnd; private Vector3 checkHitCapsuleEndOld; private float checkHitCapsuleR; private Transform checkHitCapsuleStart; public GameObject currentCamera; private Transform currentGrabHand; private float desDeg; private float dieTime; private GameObject eren; private string fxName; private Vector3 fxPosition; private Quaternion fxRotation; private GameObject grabbedTarget; public GameObject grabTF; private float gravity = 120f; private bool grounded; public bool hasDie; private bool hasDieSteam; public bool hasspawn; public GameObject healthLabel; public float healthTime; public string hitAnimation; private bool isAttackMoveByCore; private bool isGrabHandLeft; public float lagMax; public int maxHealth; public float maxVelocityChange = 80f; public static float minusDistance = 99999f; public static GameObject minusDistanceEnemy; public float myDistance; public GameObject myHero; public int NapeArmor = 1000; private bool needFreshCorePosition; private string nextAttackAnimation; private Vector3 oldCorePosition; private float sbtime; public float size; public float speed = 80f; private bool startJump; private string state = "idle"; private int stepSoundPhase = 2; private float tauntTime; private string turnAnimation; private float turnDeg; private GameObject whoHasTauntMe; private void attack(string type) { state = "attack"; attacked = false; if (attackAnimation == type) { attackAnimation = type; playAnimationAt("attack_" + type, 0f); } else { attackAnimation = type; playAnimationAt("attack_" + type, 0f); } startJump = false; attackChkOnce = false; nextAttackAnimation = null; fxName = null; isAttackMoveByCore = false; attackCheckTime = 0f; attackCheckTimeA = 0f; attackCheckTimeB = 0f; fxRotation = Quaternion.Euler(270f, 0f, 0f); string key = type; if (key != null) { int num; Dictionary<string, int> dictionary = new Dictionary<string, int>(17) { {"combo_1", 0}, {"combo_2", 1}, {"combo_3", 2}, {"combo_blind_1", 3}, {"combo_blind_2", 4}, {"combo_blind_3", 5}, {"front", 6}, {"jumpCombo_1", 7}, {"jumpCombo_2", 8}, {"jumpCombo_3", 9}, {"jumpCombo_4", 10}, {"sweep", 11}, {"sweep_back", 12}, {"sweep_front_left", 13}, {"sweep_front_right", 14}, {"sweep_head_b_l", 15}, {"sweep_head_b_r", 16} }; if (dictionary.TryGetValue(key, out num)) { switch (num) { case 0: attackCheckTimeA = 0.63f; attackCheckTimeB = 0.8f; checkHitCapsuleEnd = transform.Find("Amarture/Core/Controller_Body/hip/thigh_R/shin_R/foot_R"); checkHitCapsuleStart = transform.Find("Amarture/Core/Controller_Body/hip/thigh_R"); checkHitCapsuleR = 5f; isAttackMoveByCore = true; nextAttackAnimation = "combo_2"; break; case 1: attackCheckTimeA = 0.27f; attackCheckTimeB = 0.43f; checkHitCapsuleEnd = transform.Find("Amarture/Core/Controller_Body/hip/thigh_L/shin_L/foot_L"); checkHitCapsuleStart = transform.Find("Amarture/Core/Controller_Body/hip/thigh_L"); checkHitCapsuleR = 5f; isAttackMoveByCore = true; nextAttackAnimation = "combo_3"; break; case 2: attackCheckTimeA = 0.15f; attackCheckTimeB = 0.3f; checkHitCapsuleEnd = transform.Find("Amarture/Core/Controller_Body/hip/thigh_R/shin_R/foot_R"); checkHitCapsuleStart = transform.Find("Amarture/Core/Controller_Body/hip/thigh_R"); checkHitCapsuleR = 5f; isAttackMoveByCore = true; break; case 3: isAttackMoveByCore = true; attackCheckTimeA = 0.72f; attackCheckTimeB = 0.83f; checkHitCapsuleStart = transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/shoulder_R/upper_arm_R"); checkHitCapsuleEnd = transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/shoulder_R/upper_arm_R/forearm_R/hand_R/hand_R_001"); checkHitCapsuleR = 4f; nextAttackAnimation = "combo_blind_2"; break; case 4: isAttackMoveByCore = true; attackCheckTimeA = 0.5f; attackCheckTimeB = 0.6f; checkHitCapsuleStart = transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/shoulder_R/upper_arm_R"); checkHitCapsuleEnd = transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/shoulder_R/upper_arm_R/forearm_R/hand_R/hand_R_001"); checkHitCapsuleR = 4f; nextAttackAnimation = "combo_blind_3"; break; case 5: isAttackMoveByCore = true; attackCheckTimeA = 0.2f; attackCheckTimeB = 0.28f; checkHitCapsuleStart = transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/shoulder_R/upper_arm_R"); checkHitCapsuleEnd = transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/shoulder_R/upper_arm_R/forearm_R/hand_R/hand_R_001"); checkHitCapsuleR = 4f; break; case 6: isAttackMoveByCore = true; attackCheckTimeA = 0.44f; attackCheckTimeB = 0.55f; checkHitCapsuleStart = transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/shoulder_R/upper_arm_R"); checkHitCapsuleEnd = transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/shoulder_R/upper_arm_R/forearm_R/hand_R/hand_R_001"); checkHitCapsuleR = 4f; break; case 7: isAttackMoveByCore = false; nextAttackAnimation = "jumpCombo_2"; abnorma_jump_bite_horizon_v = Vector3.zero; break; case 8: isAttackMoveByCore = false; attackCheckTimeA = 0.48f; attackCheckTimeB = 0.7f; checkHitCapsuleStart = transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/shoulder_R/upper_arm_R"); checkHitCapsuleEnd = transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/shoulder_R/upper_arm_R/forearm_R/hand_R/hand_R_001"); checkHitCapsuleR = 4f; nextAttackAnimation = "jumpCombo_3"; break; case 9: isAttackMoveByCore = false; checkHitCapsuleEnd = transform.Find("Amarture/Core/Controller_Body/hip/thigh_L/shin_L/foot_L"); checkHitCapsuleStart = transform.Find("Amarture/Core/Controller_Body/hip/thigh_L"); checkHitCapsuleR = 5f; attackCheckTimeA = 0.22f; attackCheckTimeB = 0.42f; break; case 10: isAttackMoveByCore = false; break; case 11: isAttackMoveByCore = true; attackCheckTimeA = 0.39f; attackCheckTimeB = 0.6f; checkHitCapsuleEnd = transform.Find("Amarture/Core/Controller_Body/hip/thigh_R/shin_R/foot_R"); checkHitCapsuleStart = transform.Find("Amarture/Core/Controller_Body/hip/thigh_R"); checkHitCapsuleR = 5f; break; case 12: isAttackMoveByCore = true; attackCheckTimeA = 0.41f; attackCheckTimeB = 0.48f; checkHitCapsuleStart = transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/shoulder_R/upper_arm_R"); checkHitCapsuleEnd = transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/shoulder_R/upper_arm_R/forearm_R/hand_R/hand_R_001"); checkHitCapsuleR = 4f; break; case 13: isAttackMoveByCore = true; attackCheckTimeA = 0.53f; attackCheckTimeB = 0.63f; checkHitCapsuleStart = transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/shoulder_R/upper_arm_R"); checkHitCapsuleEnd = transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/shoulder_R/upper_arm_R/forearm_R/hand_R/hand_R_001"); checkHitCapsuleR = 4f; break; case 14: isAttackMoveByCore = true; attackCheckTimeA = 0.5f; attackCheckTimeB = 0.62f; checkHitCapsuleStart = transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/shoulder_L/upper_arm_L"); checkHitCapsuleEnd = transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/shoulder_L/upper_arm_L/forearm_L/hand_L/hand_L_001"); checkHitCapsuleR = 4f; break; case 15: isAttackMoveByCore = true; attackCheckTimeA = 0.4f; attackCheckTimeB = 0.51f; checkHitCapsuleStart = transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/shoulder_L/upper_arm_L"); checkHitCapsuleEnd = transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/shoulder_L/upper_arm_L/forearm_L/hand_L/hand_L_001"); checkHitCapsuleR = 4f; break; case 16: isAttackMoveByCore = true; attackCheckTimeA = 0.4f; attackCheckTimeB = 0.51f; checkHitCapsuleStart = transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/shoulder_R/upper_arm_R"); checkHitCapsuleEnd = transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/shoulder_R/upper_arm_R/forearm_R/hand_R/hand_R_001"); checkHitCapsuleR = 4f; break; } } } checkHitCapsuleEndOld = checkHitCapsuleEnd.transform.position; needFreshCorePosition = true; } private bool attackTarget(GameObject target) { int num5; float current = 0f; float f = 0f; Vector3 vector = target.transform.position - transform.position; current = -Mathf.Atan2(vector.z, vector.x) * 57.29578f; f = -Mathf.DeltaAngle(current, gameObject.transform.rotation.eulerAngles.y - 90f); if (eren != null && myDistance < 35f) { attack("combo_1"); return true; } int num3 = 0; string str = string.Empty; ArrayList list = new ArrayList(); if (myDistance < 40f) { if (Mathf.Abs(f) < 90f) { if (f > 0f) { num3 = 1; } else { num3 = 2; } } else if (f > 0f) { num3 = 4; } else { num3 = 3; } float num4 = target.transform.position.y - transform.position.y; if (Mathf.Abs(f) < 90f) { if (num4 > 0f && num4 < 12f && myDistance < 22f) { list.Add("attack_sweep"); } if (num4 >= 55f && num4 < 90f) { list.Add("attack_jumpCombo_1"); } } if (Mathf.Abs(f) < 90f && num4 > 12f && num4 < 40f) { list.Add("attack_combo_1"); } if (Mathf.Abs(f) < 30f) { if (num4 > 0f && num4 < 12f && myDistance > 20f && myDistance < 30f) { list.Add("attack_front"); } if (myDistance < 12f && num4 > 33f && num4 < 51f) { list.Add("grab_up"); } } if (Mathf.Abs(f) > 100f && myDistance < 11f && num4 >= 15f && num4 < 32f) { list.Add("attack_sweep_back"); } num5 = num3; switch (num5) { case 1: if (myDistance >= 11f) { if (myDistance < 20f) { if (num4 >= 12f && num4 < 21f) { list.Add("grab_bottom_right"); } else if (num4 >= 21f && num4 < 32f) { list.Add("grab_mid_right"); } else if (num4 >= 32f && num4 < 47f) { list.Add("grab_up_right"); } } break; } if (num4 >= 21f && num4 < 32f) { list.Add("attack_sweep_front_right"); } break; case 2: if (myDistance >= 11f) { if (myDistance < 20f) { if (num4 >= 12f && num4 < 21f) { list.Add("grab_bottom_left"); } else if (num4 >= 21f && num4 < 32f) { list.Add("grab_mid_left"); } else if (num4 >= 32f && num4 < 47f) { list.Add("grab_up_left"); } } break; } if (num4 >= 21f && num4 < 32f) { list.Add("attack_sweep_front_left"); } break; case 3: if (myDistance >= 11f) { list.Add("turn180"); break; } if (num4 >= 33f && num4 < 51f) { list.Add("attack_sweep_head_b_l"); } break; case 4: if (myDistance >= 11f) { list.Add("turn180"); break; } if (num4 >= 33f && num4 < 51f) { list.Add("attack_sweep_head_b_r"); } break; } } if (list.Count > 0) { str = (string) list[UnityEngine.Random.Range(0, list.Count)]; } else if (UnityEngine.Random.Range(0, 100) < 10) { GameObject[] objArray = GameObject.FindGameObjectsWithTag("Player"); myHero = objArray[UnityEngine.Random.Range(0, objArray.Length)]; attention = UnityEngine.Random.Range(5f, 10f); return true; } string key = str; if (key != null) { Dictionary<string, int> dictionary = new Dictionary<string, int>(17) { {"grab_bottom_left", 0}, {"grab_bottom_right", 1}, {"grab_mid_left", 2}, {"grab_mid_right", 3}, {"grab_up", 4}, {"grab_up_left", 5}, {"grab_up_right", 6}, {"attack_combo_1", 7}, {"attack_front", 8}, {"attack_jumpCombo_1", 9}, {"attack_sweep", 10}, {"attack_sweep_back", 11}, {"attack_sweep_front_left", 12}, {"attack_sweep_front_right", 13}, {"attack_sweep_head_b_l", 14}, {"attack_sweep_head_b_r", 15}, {"turn180", 16} }; if (dictionary.TryGetValue(key, out num5)) { switch (num5) { case 0: grab("bottom_left"); return true; case 1: grab("bottom_right"); return true; case 2: grab("mid_left"); return true; case 3: grab("mid_right"); return true; case 4: grab("up"); return true; case 5: grab("up_left"); return true; case 6: grab("up_right"); return true; case 7: attack("combo_1"); return true; case 8: attack("front"); return true; case 9: attack("jumpCombo_1"); return true; case 10: attack("sweep"); return true; case 11: attack("sweep_back"); return true; case 12: attack("sweep_front_left"); return true; case 13: attack("sweep_front_right"); return true; case 14: attack("sweep_head_b_l"); return true; case 15: attack("sweep_head_b_r"); return true; case 16: turn180(); return true; default: return false; } } } return false; } private void Awake() { rigidbody.freezeRotation = true; rigidbody.useGravity = false; } public void beTauntedBy(GameObject target, float time) { whoHasTauntMe = target; this.tauntTime = time; } private void chase() { state = "chase"; crossFade("run", 0.5f); } private RaycastHit[] checkHitCapsule(Vector3 start, Vector3 end, float r) { return Physics.SphereCastAll(start, r, end - start, Vector3.Distance(start, end)); } private GameObject checkIfHitHand(Transform hand) { foreach (Collider c in Physics.OverlapSphere(hand.GetComponent<SphereCollider>().transform.position, 10.6f)) { if (c.transform.root.CompareTag("Player")) { GameObject go = c.transform.root.gameObject; if (go.GetComponent<TITAN_EREN>() != null) { if (!go.GetComponent<TITAN_EREN>().isHit) go.GetComponent<TITAN_EREN>().hitByTitan(); return go; } if (go.GetComponent<HERO>() != null && !go.GetComponent<HERO>().IsInvincible) return go; } } return null; } private GameObject checkIfHitHead(Transform head, float rad) { float num = rad * 4f; foreach (GameObject obj2 in GameObject.FindGameObjectsWithTag("Player")) { if (obj2.GetComponent<TITAN_EREN>() == null && !obj2.GetComponent<HERO>().IsInvincible) { float num3 = obj2.GetComponent<CapsuleCollider>().height * 0.5f; if (Vector3.Distance(obj2.transform.position + Vector3.up * num3, head.transform.position + Vector3.up * 1.5f * 4f) < num + num3) { return obj2; } } } return null; } private void crossFade(string aniName, float time) { animation.CrossFade(aniName, time); if (IN_GAME_MAIN_CAMERA.GameType == GameType.Multiplayer && PhotonNetwork.isMasterClient) { photonView.RPC(Rpc.CrossFade, PhotonTargets.Others, aniName, time); } } private void eatSet(GameObject grabTarget) { if (!grabTarget.GetComponent<HERO>().IsGrabbed) { GrabToRight(); if (IN_GAME_MAIN_CAMERA.GameType == GameType.Multiplayer && PhotonNetwork.isMasterClient) { grabTarget.GetPhotonView().RPC(Rpc.Grabbed, PhotonTargets.All, photonView.viewID, false); grabTarget.GetPhotonView().RPC(Rpc.PlayAnimation, PhotonTargets.All, "grabbed"); photonView.RPC(Rpc.GrabRight, PhotonTargets.Others); } else { grabTarget.GetComponent<HERO>().grabbed(gameObject, false); grabTarget.GetComponent<HERO>().animation.Play("grabbed"); } } } private void eatSetL(GameObject grabTarget) { if (!grabTarget.GetComponent<HERO>().IsGrabbed) { GrabToLeft(); if (IN_GAME_MAIN_CAMERA.GameType == GameType.Multiplayer && PhotonNetwork.isMasterClient) { grabTarget.GetPhotonView().RPC(Rpc.Grabbed, PhotonTargets.All, photonView.viewID, true); grabTarget.GetPhotonView().RPC(Rpc.PlayAnimation, PhotonTargets.All, "grabbed"); photonView.RPC(Rpc.GrabLeft, PhotonTargets.Others); } else { grabTarget.GetComponent<HERO>().grabbed(gameObject, true); grabTarget.GetComponent<HERO>().animation.Play("grabbed"); } } } public void erenIsHere(GameObject target) { myHero = eren = target; } private void findNearestFacingHero() { GameObject[] objArray = GameObject.FindGameObjectsWithTag("Player"); GameObject obj2 = null; float positiveInfinity = float.PositiveInfinity; Vector3 position = transform.position; float current = 0f; float num3 = 180f; float f = 0f; foreach (GameObject obj3 in objArray) { Vector3 vector2 = obj3.transform.position - position; float sqrMagnitude = vector2.sqrMagnitude; if (sqrMagnitude < positiveInfinity) { Vector3 vector3 = obj3.transform.position - transform.position; current = -Mathf.Atan2(vector3.z, vector3.x) * 57.29578f; f = -Mathf.DeltaAngle(current, gameObject.transform.rotation.eulerAngles.y - 90f); if (Mathf.Abs(f) < num3) { obj2 = obj3; positiveInfinity = sqrMagnitude; } } } if (obj2 != null) { myHero = obj2; tauntTime = 5f; } } private void findNearestHero() { myHero = getNearestHero(); attention = UnityEngine.Random.Range(5f, 10f); } private void FixedUpdate() { if ((!IN_GAME_MAIN_CAMERA.isPausing || IN_GAME_MAIN_CAMERA.GameType != GameType.Singleplayer) && (IN_GAME_MAIN_CAMERA.GameType == GameType.Singleplayer || photonView.isMine)) { if (bottomObject.GetComponent<CheckHitGround>().isGrounded) { grounded = true; bottomObject.GetComponent<CheckHitGround>().isGrounded = false; } else { grounded = false; } if (needFreshCorePosition) { oldCorePosition = transform.position - transform.Find("Amarture/Core").position; needFreshCorePosition = false; } if ((state != "attack" || !isAttackMoveByCore) && state != "hit" && state != "turn180" && state != "anklehurt") { if (state == "chase") { if (myHero == null) { return; } Vector3 vector3 = transform.forward * speed; Vector3 velocity = rigidbody.velocity; Vector3 force = vector3 - velocity; force.y = 0f; rigidbody.AddForce(force, ForceMode.VelocityChange); float current = 0f; Vector3 vector6 = myHero.transform.position - transform.position; current = -Mathf.Atan2(vector6.z, vector6.x) * 57.29578f; float num2 = -Mathf.DeltaAngle(current, gameObject.transform.rotation.eulerAngles.y - 90f); gameObject.transform.rotation = Quaternion.Lerp(gameObject.transform.rotation, Quaternion.Euler(0f, gameObject.transform.rotation.eulerAngles.y + num2, 0f), speed * Time.deltaTime); } else if (grounded && !animation.IsPlaying("attack_jumpCombo_1")) { rigidbody.AddForce(new Vector3(-rigidbody.velocity.x, 0f, -rigidbody.velocity.z), ForceMode.VelocityChange); } } else { Vector3 vector = transform.position - transform.Find("Amarture/Core").position - oldCorePosition; rigidbody.velocity = vector / Time.deltaTime + Vector3.up * rigidbody.velocity.y; oldCorePosition = transform.position - transform.Find("Amarture/Core").position; } rigidbody.AddForce(new Vector3(0f, -gravity * rigidbody.mass, 0f)); } } private void getDown() { state = "anklehurt"; playAnimation("legHurt"); AnkleRHP = AnkleRHPMAX; AnkleLHP = AnkleLHPMAX; needFreshCorePosition = true; } private GameObject getNearestHero() { GameObject[] objArray = GameObject.FindGameObjectsWithTag("Player"); GameObject obj2 = null; float positiveInfinity = float.PositiveInfinity; Vector3 position = transform.position; foreach (GameObject obj3 in objArray) { if ((obj3.GetComponent<HERO>() == null || !obj3.GetComponent<HERO>().HasDied()) && (obj3.GetComponent<TITAN_EREN>() == null || !obj3.GetComponent<TITAN_EREN>().hasDied)) { Vector3 vector2 = obj3.transform.position - position; float sqrMagnitude = vector2.sqrMagnitude; if (sqrMagnitude < positiveInfinity) { obj2 = obj3; positiveInfinity = sqrMagnitude; } } } return obj2; } private float getNearestHeroDistance() { GameObject[] objArray = GameObject.FindGameObjectsWithTag("Player"); float positiveInfinity = float.PositiveInfinity; Vector3 position = transform.position; foreach (GameObject obj2 in objArray) { Vector3 vector2 = obj2.transform.position - position; float magnitude = vector2.magnitude; if (magnitude < positiveInfinity) { positiveInfinity = magnitude; } } return positiveInfinity; } private void grab(string type) { state = "grab"; attacked = false; attackAnimation = type; if (animation.IsPlaying("attack_grab_" + type)) { animation["attack_grab_" + type].normalizedTime = 0f; playAnimation("attack_grab_" + type); } else { crossFade("attack_grab_" + type, 0.1f); } isGrabHandLeft = true; grabbedTarget = null; attackCheckTime = 0f; string key = type; if (key != null) { int num; Dictionary<string, int> dictionary = new Dictionary<string, int>(7) { {"bottom_left", 0}, {"bottom_right", 1}, {"mid_left", 2}, {"mid_right", 3}, {"up", 4}, {"up_left", 5}, {"up_right", 6} }; if (dictionary.TryGetValue(key, out num)) { switch (num) { case 0: attackCheckTimeA = 0.28f; attackCheckTimeB = 0.38f; attackCheckTime = 0.65f; isGrabHandLeft = false; break; case 1: attackCheckTimeA = 0.27f; attackCheckTimeB = 0.37f; attackCheckTime = 0.65f; break; case 2: attackCheckTimeA = 0.27f; attackCheckTimeB = 0.37f; attackCheckTime = 0.65f; isGrabHandLeft = false; break; case 3: attackCheckTimeA = 0.27f; attackCheckTimeB = 0.36f; attackCheckTime = 0.66f; break; case 4: attackCheckTimeA = 0.25f; attackCheckTimeB = 0.32f; attackCheckTime = 0.67f; break; case 5: attackCheckTimeA = 0.26f; attackCheckTimeB = 0.4f; attackCheckTime = 0.66f; break; case 6: attackCheckTimeA = 0.26f; attackCheckTimeB = 0.4f; attackCheckTime = 0.66f; isGrabHandLeft = false; break; } } } if (isGrabHandLeft) { currentGrabHand = transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/shoulder_L/upper_arm_L/forearm_L/hand_L/hand_L_001"); } else { currentGrabHand = transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/shoulder_R/upper_arm_R/forearm_R/hand_R/hand_R_001"); } } [RPC] [UsedImplicitly] public void GrabbedTargetEscape() { grabbedTarget = null; } [RPC] [UsedImplicitly] public void GrabToLeft() { Transform t = this.transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/shoulder_L/upper_arm_L/forearm_L/hand_L/hand_L_001"); grabTF.transform.parent = t; grabTF.transform.parent = t; grabTF.transform.position = t.GetComponent<SphereCollider>().transform.position; grabTF.transform.rotation = t.GetComponent<SphereCollider>().transform.rotation; Transform transform1 = grabTF.transform; transform1.localPosition -= Vector3.right * t.GetComponent<SphereCollider>().radius * 0.3f; Transform transform2 = grabTF.transform; transform2.localPosition -= Vector3.up * t.GetComponent<SphereCollider>().radius * 0.51f; Transform transform3 = grabTF.transform; transform3.localPosition -= Vector3.forward * t.GetComponent<SphereCollider>().radius * 0.3f; grabTF.transform.localRotation = Quaternion.Euler(grabTF.transform.localRotation.eulerAngles.x, grabTF.transform.localRotation.eulerAngles.y + 180f, grabTF.transform.localRotation.eulerAngles.z + 180f); } [RPC] [UsedImplicitly] public void GrabToRight() { Transform t = this.transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/shoulder_R/upper_arm_R/forearm_R/hand_R/hand_R_001"); grabTF.transform.parent = t; grabTF.transform.position = t.GetComponent<SphereCollider>().transform.position; grabTF.transform.rotation = t.GetComponent<SphereCollider>().transform.rotation; Transform transform1 = grabTF.transform; transform1.localPosition -= Vector3.right * t.GetComponent<SphereCollider>().radius * 0.3f; Transform transform2 = grabTF.transform; transform2.localPosition += Vector3.up * t.GetComponent<SphereCollider>().radius * 0.51f; Transform transform3 = grabTF.transform; transform3.localPosition -= Vector3.forward * t.GetComponent<SphereCollider>().radius * 0.3f; grabTF.transform.localRotation = Quaternion.Euler(grabTF.transform.localRotation.eulerAngles.x, grabTF.transform.localRotation.eulerAngles.y + 180f, grabTF.transform.localRotation.eulerAngles.z); } public void hit(int dmg) { NapeArmor -= dmg; if (NapeArmor <= 0) { NapeArmor = 0; } } public void hitAnkleL(int dmg) { if (!hasDie && state != "anklehurt") { AnkleLHP -= dmg; if (AnkleLHP <= 0) { getDown(); } } } [RPC] [UsedImplicitly] public void HitAnkleLRPC(int viewID, int dmg) { if (!hasDie && state != "anklehurt") { PhotonView view = PhotonView.Find(viewID); if (view != null) { if (grabbedTarget != null) { grabbedTarget.GetPhotonView().RPC(Rpc.netUngrabbed, PhotonTargets.All); } Vector3 vector = view.gameObject.transform.position - transform.Find("Amarture/Core/Controller_Body").transform.position; if (vector.magnitude < 20f) { AnkleLHP -= dmg; if (AnkleLHP <= 0) { getDown(); } GameManager.instance.SendKillInfo(false, view.owner.Properties.Name, true, "Female Titan's ankle", dmg); GameManager.instance.photonView.RPC(Rpc.ShowDamage, view.owner, dmg); } } } } public void hitAnkleR(int dmg) { if (!hasDie && state != "anklehurt") { AnkleRHP -= dmg; if (AnkleRHP <= 0) { getDown(); } } } [RPC] [UsedImplicitly] public void HitAnkleRRPC(int viewID, int dmg) { if (!hasDie && state != "anklehurt") { PhotonView view = PhotonView.Find(viewID); if (view != null) { if (grabbedTarget != null) { grabbedTarget.GetPhotonView().RPC(Rpc.netUngrabbed, PhotonTargets.All); } Vector3 vector = view.gameObject.transform.position - transform.Find("Amarture/Core/Controller_Body").transform.position; if (vector.magnitude < 20f) { AnkleRHP -= dmg; if (AnkleRHP <= 0) { getDown(); } GameManager.instance.SendKillInfo(false, view.owner.Properties.Name, true, "Female Titan's ankle", dmg); GameManager.instance.photonView.RPC(Rpc.ShowDamage, view.owner, dmg); } } } } public void hitEye() { if (!hasDie) { justHitEye(); } } [RPC] [UsedImplicitly] public void HitEyeRPC(int viewID) { if (!hasDie) { if (grabbedTarget != null) { grabbedTarget.GetPhotonView().RPC(Rpc.netUngrabbed, PhotonTargets.All); } Transform t = this.transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/neck"); PhotonView view = PhotonView.Find(viewID); if (view != null) { Vector3 vector = view.gameObject.transform.position - t.transform.position; if (vector.magnitude < 20f) { justHitEye(); } } } } private void Idle(float stunTime = 0f) { this.sbtime = stunTime; this.sbtime = Mathf.Max(0.5f, this.sbtime); state = "idle"; crossFade("idle", 0.2f); } private bool IsGrounded() { return bottomObject.GetComponent<CheckHitGround>().isGrounded; } private static void JustEatHero(GameObject target, Transform hand) { switch (IN_GAME_MAIN_CAMERA.GameType) { case GameType.Multiplayer when PhotonNetwork.isMasterClient: if (!target.GetComponent<HERO>().HasDied()) { target.GetComponent<HERO>().markDie(); target.GetComponent<HERO>().photonView.RPC(Rpc.DieRC, PhotonTargets.All, -1, "Female Titan"); } break; case GameType.Singleplayer: target.GetComponent<HERO>().die2(hand); break; } } private void justHitEye() { attack("combo_blind_1"); } private void killPlayer(GameObject hitHero) { if (hitHero != null) { Vector3 position = transform.Find("Amarture/Core/Controller_Body/hip/spine/chest").position; if (IN_GAME_MAIN_CAMERA.GameType == GameType.Singleplayer) { if (!hitHero.GetComponent<HERO>().HasDied()) { hitHero.GetComponent<HERO>().die((hitHero.transform.position - position) * 15f * 4f, false); } } else if (IN_GAME_MAIN_CAMERA.GameType == GameType.Multiplayer && PhotonNetwork.isMasterClient && !hitHero.GetComponent<HERO>().HasDied()) { hitHero.GetComponent<HERO>().markDie(); hitHero.GetComponent<HERO>().photonView.RPC(Rpc.Die, PhotonTargets.All, (hitHero.transform.position - position) * 15f * 4f, false, -1, "Female Titan", true); } } } [RPC] [UsedImplicitly] public void LabelRPC(int health, int titanMaxHealth, PhotonMessageInfo info) { if (titanMaxHealth <= 0) throw new NotAllowedException(nameof(LabelRPC), info); if (health < 0) { if (healthLabel != null) { Destroy(healthLabel); } } else { if (healthLabel == null) { healthLabel = (GameObject) Instantiate(Resources.Load("UI/LabelNameOverHead")); healthLabel.name = "LabelNameOverHead"; healthLabel.transform.parent = transform; healthLabel.transform.localPosition = new Vector3(0f, 52f, 0f); float a = 4f; if (size > 0f && size < 1f) { a = 4f / size; a = Mathf.Min(a, 15f); } healthLabel.transform.localScale = new Vector3(a, a, a); } float percentage = health / (float)titanMaxHealth; string str = "[7FFF00]"; if (percentage < 0.75f && percentage >= 0.5f) str = "[f2b50f]"; else if (percentage < 0.5f && percentage >= 0.25f) str = "[ff8100]"; else if (percentage < 0.25f) str = "[ff3333]"; healthLabel.GetComponent<UILabel>().text = str + Convert.ToString(health); } } public void DoLateUpdate() { if (!IN_GAME_MAIN_CAMERA.isPausing || IN_GAME_MAIN_CAMERA.GameType != GameType.Singleplayer) { if (animation.IsPlaying("run")) { if (animation["run"].normalizedTime % 1f > 0.1f && animation["run"].normalizedTime % 1f < 0.6f && stepSoundPhase == 2) { stepSoundPhase = 1; Transform t = this.transform.Find("snd_titan_foot"); t.GetComponent<AudioSource>().Stop(); t.GetComponent<AudioSource>().Play(); } if (animation["run"].normalizedTime % 1f > 0.6f && stepSoundPhase == 1) { stepSoundPhase = 2; Transform transform2 = transform.Find("snd_titan_foot"); transform2.GetComponent<AudioSource>().Stop(); transform2.GetComponent<AudioSource>().Play(); } } updateLabel(); healthTime -= Time.deltaTime; } } public void loadskin() { if (!ModuleManager.Enabled(nameof(ModuleEnableSkins))) return; photonView.RPC(Rpc.LoadSkin, PhotonTargets.AllBuffered, GameManager.settings.TitanSkin.Annie); } public IEnumerator loadskinE(string url) { while (!hasspawn) { yield return null; } bool mipmap = GameManager.settings.UseMipmap; bool iteratorVariable1 = false; foreach (Renderer iteratorVariable4 in GetComponentsInChildren<Renderer>()) { if (!GameManager.linkHash[2].ContainsKey(url)) { WWW link = new WWW(url); yield return link; Texture2D iteratorVariable6 = RCextensions.LoadImageRC(link, mipmap, 1000000); link.Dispose(); if (!GameManager.linkHash[2].ContainsKey(url)) { iteratorVariable1 = true; iteratorVariable4.material.mainTexture = iteratorVariable6; GameManager.linkHash[2].Add(url, iteratorVariable4.material); iteratorVariable4.material = (Material)GameManager.linkHash[2][url]; } else { iteratorVariable4.material = (Material)GameManager.linkHash[2][url]; } } else { iteratorVariable4.material = (Material)GameManager.linkHash[2][url]; } } if (iteratorVariable1) { GameManager.instance.UnloadAssets(); } } [RPC] [UsedImplicitly] public void LoadskinRPC(string url) { Shelter.LogBoth("LOADING {0} SKIN", nameof(FEMALE_TITAN)); Shelter.LogBoth("{0}: {1}", nameof(url), url); if (ModuleManager.Enabled(nameof(ModuleEnableSkins)) || !Utility.IsValidImageUrl(url)) { StartCoroutine(loadskinE(url)); } } [RPC] [UsedImplicitly] private void NetCrossFade(string aniName, float time) { animation.CrossFade(aniName, time); } [RPC] [UsedImplicitly] public void NetDie() { if (!hasDie) { hasDie = true; crossFade("die", 0.05f); } } [RPC] [UsedImplicitly] private void NetPlayAnimation(string aniName) { animation.Play(aniName); } [RPC] [UsedImplicitly] private void NetPlayAnimationAt(string aniName, float normalizedTime) { animation.Play(aniName); animation[aniName].normalizedTime = normalizedTime; } private void OnDestroy() { if (GameObject.Find("MultiplayerManager") != null) { GameManager.instance.FemaleTitans.Remove(this); } } private void playAnimation(string aniName) { animation.Play(aniName); if (IN_GAME_MAIN_CAMERA.GameType == GameType.Multiplayer && PhotonNetwork.isMasterClient) { photonView.RPC(Rpc.PlayAnimation, PhotonTargets.Others, aniName); } } private void playAnimationAt(string aniName, float normalizedTime) { animation.Play(aniName); animation[aniName].normalizedTime = normalizedTime; if (IN_GAME_MAIN_CAMERA.GameType == GameType.Multiplayer && PhotonNetwork.isMasterClient) { photonView.RPC(Rpc.PlayAnimationAt, PhotonTargets.Others, aniName, normalizedTime); } } private void playSound(string sndname) { PlaysoundRPC(sndname); if (Network.peerType == NetworkPeerType.Server) { photonView.RPC(Rpc.PlaySound, PhotonTargets.Others, sndname); } } [RPC] [UsedImplicitly] private void PlaysoundRPC(string sndname) { transform.Find(sndname).GetComponent<AudioSource>().Play(); } [RPC] [UsedImplicitly] public void SetSize(float newSize, PhotonMessageInfo info) { if (!info.sender.IsMasterClient) throw new NotAllowedException(nameof(SetSize), info); newSize = Mathf.Clamp(newSize, 0.2f, 30f); transform.localScale = transform.localScale * (newSize * 0.25f); size = newSize; } private void Start() { startMain(); size = 4f; if (Minimap.instance != null) Minimap.instance.TrackGameObjectOnMinimap(gameObject, Color.black, false, true); if (photonView.isMine) { if (GameManager.settings.EnableCustomSize) { photonView.RPC(Rpc.SetSize, PhotonTargets.AllBuffered, GameManager.settings.TitanSize.Random); } lagMax = 150f + size * 3f; healthTime = 0f; maxHealth = NapeArmor; if (GameManager.settings.HealthMode > HealthMode.Off) { maxHealth = NapeArmor = (int) GameManager.settings.TitanHealth.Random; } if (NapeArmor > 0) { photonView.RPC(Rpc.UpdateHealthLabel, PhotonTargets.AllBuffered, NapeArmor, maxHealth); } loadskin(); } hasspawn = true; } private void startMain() { GameManager.instance.FemaleTitans.Add(this); name = "Female Titan"; grabTF = new GameObject(); grabTF.name = "titansTmpGrabTF"; currentCamera = GameObject.Find("MainCamera"); oldCorePosition = transform.position - transform.Find("Amarture/Core").position; if (myHero == null) { findNearestHero(); } foreach (AnimationState current in animation) if (current != null) current.speed = 0.7f; animation["turn180"].speed = 0.5f; NapeArmor = 1000; AnkleLHP = 50; AnkleRHP = 50; AnkleLHPMAX = 50; AnkleRHPMAX = 50; bool flag = LevelInfoManager.Get(GameManager.Level).RespawnMode == RespawnMode.NEVER; switch (IN_GAME_MAIN_CAMERA.difficulty) { case 0: NapeArmor = 1000; AnkleLHP = AnkleLHPMAX = 50; AnkleRHP = AnkleRHPMAX = 50; break; case 1: NapeArmor = !flag ? 3000 : 2500; AnkleLHP = AnkleLHPMAX = !flag ? 200 : 100; AnkleRHP = AnkleRHPMAX = !flag ? 200 : 100; foreach (AnimationState state2 in animation) if (state2 != null) state2.speed = 0.7f; animation["turn180"].speed = 0.7f; break; case 2: NapeArmor = !flag ? 6000 : 4000; AnkleLHP = AnkleLHPMAX = !flag ? 1000 : 200; AnkleRHP = AnkleRHPMAX = !flag ? 1000 : 200; foreach (AnimationState state3 in animation) if (state3 != null) state3.speed = 1f; animation["turn180"].speed = 0.9f; break; } if (IN_GAME_MAIN_CAMERA.GameMode == GameMode.PvpCapture) { NapeArmor = (int) (NapeArmor * 0.8f); } animation["legHurt"].speed = 1f; animation["legHurt_loop"].speed = 1f; animation["legHurt_getup"].speed = 1f; } [RPC] [UsedImplicitly] public void TitanGetHit(int viewID, int hitSpeed) { Transform t = this.transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/neck"); PhotonView view = PhotonView.Find(viewID); if (view != null) { Vector3 vector = view.gameObject.transform.position - t.transform.position; if (vector.magnitude < lagMax && healthTime <= 0f) { if (hitSpeed >= GameManager.settings.MinimumDamage) { NapeArmor -= hitSpeed; } if (maxHealth > 0f) { photonView.RPC(Rpc.UpdateHealthLabel, PhotonTargets.AllBuffered, NapeArmor, maxHealth); } if (NapeArmor <= 0) { NapeArmor = 0; if (!hasDie) { photonView.RPC(Rpc.Die, PhotonTargets.OthersBuffered); if (grabbedTarget != null) { grabbedTarget.GetPhotonView().RPC(Rpc.netUngrabbed, PhotonTargets.All); } NetDie(); GameManager.instance.TitanGetKill(view.owner, hitSpeed, name, null); } } else { GameManager.instance.SendKillInfo(false, view.owner.Properties.Name, true, "Female Titan's neck", hitSpeed); GameManager.instance.photonView.RPC(Rpc.ShowDamage, view.owner, hitSpeed); } healthTime = 0.2f; } } } private void turn(float d) { if (d > 0f) { turnAnimation = "turnaround1"; } else { turnAnimation = "turnaround2"; } playAnimation(turnAnimation); animation[turnAnimation].time = 0f; d = Mathf.Clamp(d, -120f, 120f); turnDeg = d; desDeg = gameObject.transform.rotation.eulerAngles.y + turnDeg; state = "turn"; } private void turn180() { turnAnimation = "turn180"; playAnimation(turnAnimation); animation[turnAnimation].time = 0f; state = "turn180"; needFreshCorePosition = true; } public void DoUpdate() { if ((!IN_GAME_MAIN_CAMERA.isPausing || IN_GAME_MAIN_CAMERA.GameType != GameType.Singleplayer) && (IN_GAME_MAIN_CAMERA.GameType == GameType.Singleplayer || photonView.isMine)) { if (hasDie) { dieTime += Time.deltaTime; if (animation["die"].normalizedTime >= 1f) { playAnimation("die_cry"); if (IN_GAME_MAIN_CAMERA.GameMode != GameMode.PvpCapture) { for (int i = 0; i < 15; i++) { GameManager.instance.RandomSpawnOneTitan("titanRespawn", 50).GetComponent<TITAN>().GetTaunted(gameObject, 20f); } } } if (dieTime > 2f && !hasDieSteam) { hasDieSteam = true; if (IN_GAME_MAIN_CAMERA.GameType == GameType.Singleplayer) { GameObject obj3 = (GameObject) Instantiate(Resources.Load("FX/FXtitanDie1")); obj3.transform.position = transform.Find("Amarture/Core/Controller_Body/hip").position; obj3.transform.localScale = transform.localScale; } else if (photonView.isMine) { PhotonNetwork.Instantiate("FX/FXtitanDie1", transform.Find("Amarture/Core/Controller_Body/hip").position, Quaternion.Euler(-90f, 0f, 0f), 0).transform.localScale = transform.localScale; } } if (dieTime > (IN_GAME_MAIN_CAMERA.GameMode != GameMode.PvpCapture ? 20f : 5f)) { if (IN_GAME_MAIN_CAMERA.GameType == GameType.Singleplayer) { GameObject obj5 = (GameObject) Instantiate(Resources.Load("FX/FXtitanDie")); obj5.transform.position = transform.Find("Amarture/Core/Controller_Body/hip").position; obj5.transform.localScale = transform.localScale; Destroy(gameObject); } else if (photonView.isMine) { PhotonNetwork.Instantiate("FX/FXtitanDie", transform.Find("Amarture/Core/Controller_Body/hip").position, Quaternion.Euler(-90f, 0f, 0f), 0).transform.localScale = transform.localScale; PhotonNetwork.Destroy(gameObject); } } } else { if (attention > 0f) { attention -= Time.deltaTime; if (attention < 0f) { attention = 0f; GameObject[] objArray = GameObject.FindGameObjectsWithTag("Player"); myHero = objArray[UnityEngine.Random.Range(0, objArray.Length)]; attention = UnityEngine.Random.Range(5f, 10f); } } if (whoHasTauntMe != null) { tauntTime -= Time.deltaTime; if (tauntTime <= 0f) { whoHasTauntMe = null; } myHero = whoHasTauntMe; } if (eren != null) { if (!eren.GetComponent<TITAN_EREN>().hasDied) { myHero = eren; } else { eren = null; myHero = null; } } if (myHero == null) { findNearestHero(); if (myHero != null) { return; } } if (myHero == null) { myDistance = float.MaxValue; } else { myDistance = Mathf.Sqrt((myHero.transform.position.x - transform.position.x) * (myHero.transform.position.x - transform.position.x) + (myHero.transform.position.z - transform.position.z) * (myHero.transform.position.z - transform.position.z)); } if (state == "idle") { if (myHero != null) { float current = 0f; float f = 0f; Vector3 vector9 = myHero.transform.position - transform.position; current = -Mathf.Atan2(vector9.z, vector9.x) * 57.29578f; f = -Mathf.DeltaAngle(current, gameObject.transform.rotation.eulerAngles.y - 90f); if (!attackTarget(myHero)) { if (Mathf.Abs(f) < 90f) { chase(); } else if (UnityEngine.Random.Range(0, 100) < 1) { turn180(); } else if (Mathf.Abs(f) <= 100f) { if (Mathf.Abs(f) > 45f && UnityEngine.Random.Range(0, 100) < 30) { turn(f); } } else if (UnityEngine.Random.Range(0, 100) < 10) { turn180(); } } } } else if (state == "attack") { if (!attacked && attackCheckTime != 0f && animation["attack_" + attackAnimation].normalizedTime >= attackCheckTime) { GameObject obj7; attacked = true; fxPosition = transform.Find("ap_" + attackAnimation).position; if (IN_GAME_MAIN_CAMERA.GameType == GameType.Multiplayer && PhotonNetwork.isMasterClient) { obj7 = PhotonNetwork.Instantiate("FX/" + fxName, fxPosition, fxRotation, 0); } else { obj7 = (GameObject) Instantiate(Resources.Load("FX/" + fxName), fxPosition, fxRotation); } obj7.transform.localScale = transform.localScale; float b = 1f - Vector3.Distance(currentCamera.transform.position, obj7.transform.position) * 0.05f; b = Mathf.Min(1f, b); currentCamera.GetComponent<IN_GAME_MAIN_CAMERA>().startShake(b, b); } if (attackCheckTimeA != 0f && (animation["attack_" + attackAnimation].normalizedTime >= attackCheckTimeA && animation["attack_" + attackAnimation].normalizedTime <= attackCheckTimeB || !attackChkOnce && animation["attack_" + attackAnimation].normalizedTime >= attackCheckTimeA)) { if (!attackChkOnce) { attackChkOnce = true; playSound("snd_eren_swing" + UnityEngine.Random.Range(1, 3)); } foreach (RaycastHit hit in checkHitCapsule(checkHitCapsuleStart.position, checkHitCapsuleEnd.position, checkHitCapsuleR)) { GameObject go = hit.collider.gameObject; if (go.CompareTag("Player")) { killPlayer(go); } if (go.CompareTag("erenHitbox")) { if (attackAnimation == "combo_1") { if (IN_GAME_MAIN_CAMERA.GameType == GameType.Multiplayer && PhotonNetwork.isMasterClient) { go.transform.root.gameObject.GetComponent<TITAN_EREN>().hitByFTByServer(1); } } else if (attackAnimation == "combo_2") { if (IN_GAME_MAIN_CAMERA.GameType == GameType.Multiplayer && PhotonNetwork.isMasterClient) { go.transform.root.gameObject.GetComponent<TITAN_EREN>().hitByFTByServer(2); } } else if (attackAnimation == "combo_3" && IN_GAME_MAIN_CAMERA.GameType == GameType.Multiplayer && PhotonNetwork.isMasterClient) { go.transform.root.gameObject.GetComponent<TITAN_EREN>().hitByFTByServer(3); } } } foreach (RaycastHit hit2 in checkHitCapsule(checkHitCapsuleEndOld, checkHitCapsuleEnd.position, checkHitCapsuleR)) { GameObject hitHero = hit2.collider.gameObject; if (hitHero.tag == "Player") { killPlayer(hitHero); } } checkHitCapsuleEndOld = checkHitCapsuleEnd.position; } if (attackAnimation == "jumpCombo_1" && animation["attack_" + attackAnimation].normalizedTime >= 0.65f && !startJump && myHero != null) { startJump = true; float y = myHero.rigidbody.velocity.y; float num7 = -20f; float num9 = transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/neck").position.y; float num10 = (num7 - gravity) * 0.5f; float num11 = y; float num12 = myHero.transform.position.y - num9; float num13 = Mathf.Abs((Mathf.Sqrt(num11 * num11 - 4f * num10 * num12) - num11) / (2f * num10)); Vector3 vector14 = myHero.transform.position + myHero.rigidbody.velocity * num13 + Vector3.up * 0.5f * num7 * num13 * num13; float num14 = vector14.y; if (num12 < 0f || num14 - num9 < 0f) { Idle(); num13 = 0.5f; vector14 = transform.position + (num9 + 5f) * Vector3.up; num14 = vector14.y; } float num15 = num14 - num9; float num16 = Mathf.Sqrt(2f * num15 / this.gravity); float num17 = this.gravity * num16 + 20f; num17 = Mathf.Clamp(num17, 20f, 90f); Vector3 vector15 = (vector14 - transform.position) / num13; abnorma_jump_bite_horizon_v = new Vector3(vector15.x, 0f, vector15.z); Vector3 velocity = rigidbody.velocity; Vector3 vector17 = new Vector3(abnorma_jump_bite_horizon_v.x, num17, abnorma_jump_bite_horizon_v.z); if (vector17.magnitude > 90f) { vector17 = vector17.normalized * 90f; } Vector3 force = vector17 - velocity; rigidbody.AddForce(force, ForceMode.VelocityChange); float num18 = Vector2.Angle(new Vector2(transform.position.x, transform.position.z), new Vector2(myHero.transform.position.x, myHero.transform.position.z)); num18 = Mathf.Atan2(myHero.transform.position.x - transform.position.x, myHero.transform.position.z - transform.position.z) * 57.29578f; gameObject.transform.rotation = Quaternion.Euler(0f, num18, 0f); } if (attackAnimation == "jumpCombo_3") { if (animation["attack_" + attackAnimation].normalizedTime >= 1f && IsGrounded()) { attack("jumpCombo_4"); } } else if (animation["attack_" + attackAnimation].normalizedTime >= 1f) { if (nextAttackAnimation != null) { attack(nextAttackAnimation); if (eren != null) { gameObject.transform.rotation = Quaternion.Euler(0f, Quaternion.LookRotation(eren.transform.position - transform.position).eulerAngles.y, 0f); } } else { findNearestHero(); Idle(); } } } else if (state == "grab") { if (animation["attack_grab_" + attackAnimation].normalizedTime >= attackCheckTimeA && animation["attack_grab_" + attackAnimation].normalizedTime <= attackCheckTimeB && grabbedTarget == null) { GameObject grabTarget = checkIfHitHand(currentGrabHand); if (grabTarget != null) { if (isGrabHandLeft) { eatSetL(grabTarget); grabbedTarget = grabTarget; } else { eatSet(grabTarget); grabbedTarget = grabTarget; } } } if (animation["attack_grab_" + attackAnimation].normalizedTime > attackCheckTime && grabbedTarget != null) { JustEatHero(grabbedTarget, currentGrabHand); grabbedTarget = null; } if (animation["attack_grab_" + attackAnimation].normalizedTime >= 1f) { Idle(); } } else if (state == "turn") { gameObject.transform.rotation = Quaternion.Lerp(gameObject.transform.rotation, Quaternion.Euler(0f, desDeg, 0f), Time.deltaTime * Mathf.Abs(turnDeg) * 0.1f); if (animation[turnAnimation].normalizedTime >= 1f) { Idle(); } } else if (state == "chase") { if ((eren == null || myDistance >= 35f || !attackTarget(myHero)) && (getNearestHeroDistance() >= 50f || UnityEngine.Random.Range(0, 100) >= 20 || !attackTarget(getNearestHero())) && myDistance < attackDistance - 15f) { Idle(UnityEngine.Random.Range(0.05f, 0.2f)); } } else if (state == "turn180") { if (animation[turnAnimation].normalizedTime >= 1f) { gameObject.transform.rotation = Quaternion.Euler(gameObject.transform.rotation.eulerAngles.x, gameObject.transform.rotation.eulerAngles.y + 180f, gameObject.transform.rotation.eulerAngles.z); Idle(); playAnimation("idle"); } } else if (state == "anklehurt") { if (animation["legHurt"].normalizedTime >= 1f) { crossFade("legHurt_loop", 0.2f); } if (animation["legHurt_loop"].normalizedTime >= 3f) { crossFade("legHurt_getup", 0.2f); } if (animation["legHurt_getup"].normalizedTime >= 1f) { Idle(); playAnimation("idle"); } } } } } public void updateLabel() { if (healthLabel != null && healthLabel.GetComponent<UILabel>().isVisible) { healthLabel.transform.LookAt(2f * healthLabel.transform.position - Camera.main.transform.position); } } }
namespace Fixtures.SwaggerBatBodyDateTime { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; public static partial class DatetimeExtensions { /// <summary> /// Get null datetime value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static DateTime? GetNull(this IDatetime operations) { return Task.Factory.StartNew(s => ((IDatetime)s).GetNullAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get null datetime value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<DateTime?> GetNullAsync( this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DateTime?> result = await operations.GetNullWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Get invalid datetime value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static DateTime? GetInvalid(this IDatetime operations) { return Task.Factory.StartNew(s => ((IDatetime)s).GetInvalidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get invalid datetime value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<DateTime?> GetInvalidAsync( this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DateTime?> result = await operations.GetInvalidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Get overflow datetime value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static DateTime? GetOverflow(this IDatetime operations) { return Task.Factory.StartNew(s => ((IDatetime)s).GetOverflowAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get overflow datetime value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<DateTime?> GetOverflowAsync( this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DateTime?> result = await operations.GetOverflowWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Get underflow datetime value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static DateTime? GetUnderflow(this IDatetime operations) { return Task.Factory.StartNew(s => ((IDatetime)s).GetUnderflowAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get underflow datetime value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<DateTime?> GetUnderflowAsync( this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DateTime?> result = await operations.GetUnderflowWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Put max datetime value 9999-12-31T23:59:59.9999999Z /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='datetimeBody'> /// </param> public static void PutUtcMaxDateTime(this IDatetime operations, DateTime? datetimeBody) { Task.Factory.StartNew(s => ((IDatetime)s).PutUtcMaxDateTimeAsync(datetimeBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put max datetime value 9999-12-31T23:59:59.9999999Z /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='datetimeBody'> /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task PutUtcMaxDateTimeAsync( this IDatetime operations, DateTime? datetimeBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutUtcMaxDateTimeWithHttpMessagesAsync(datetimeBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get max datetime value 9999-12-31t23:59:59.9999999z /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static DateTime? GetUtcLowercaseMaxDateTime(this IDatetime operations) { return Task.Factory.StartNew(s => ((IDatetime)s).GetUtcLowercaseMaxDateTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get max datetime value 9999-12-31t23:59:59.9999999z /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<DateTime?> GetUtcLowercaseMaxDateTimeAsync( this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DateTime?> result = await operations.GetUtcLowercaseMaxDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Get max datetime value 9999-12-31T23:59:59.9999999Z /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static DateTime? GetUtcUppercaseMaxDateTime(this IDatetime operations) { return Task.Factory.StartNew(s => ((IDatetime)s).GetUtcUppercaseMaxDateTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get max datetime value 9999-12-31T23:59:59.9999999Z /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<DateTime?> GetUtcUppercaseMaxDateTimeAsync( this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DateTime?> result = await operations.GetUtcUppercaseMaxDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Put max datetime value with positive numoffset /// 9999-12-31t23:59:59.9999999+14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='datetimeBody'> /// </param> public static void PutLocalPositiveOffsetMaxDateTime(this IDatetime operations, DateTime? datetimeBody) { Task.Factory.StartNew(s => ((IDatetime)s).PutLocalPositiveOffsetMaxDateTimeAsync(datetimeBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put max datetime value with positive numoffset /// 9999-12-31t23:59:59.9999999+14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='datetimeBody'> /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task PutLocalPositiveOffsetMaxDateTimeAsync( this IDatetime operations, DateTime? datetimeBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutLocalPositiveOffsetMaxDateTimeWithHttpMessagesAsync(datetimeBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get max datetime value with positive num offset /// 9999-12-31t23:59:59.9999999+14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static DateTime? GetLocalPositiveOffsetLowercaseMaxDateTime(this IDatetime operations) { return Task.Factory.StartNew(s => ((IDatetime)s).GetLocalPositiveOffsetLowercaseMaxDateTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get max datetime value with positive num offset /// 9999-12-31t23:59:59.9999999+14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<DateTime?> GetLocalPositiveOffsetLowercaseMaxDateTimeAsync( this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DateTime?> result = await operations.GetLocalPositiveOffsetLowercaseMaxDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Get max datetime value with positive num offset /// 9999-12-31T23:59:59.9999999+14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static DateTime? GetLocalPositiveOffsetUppercaseMaxDateTime(this IDatetime operations) { return Task.Factory.StartNew(s => ((IDatetime)s).GetLocalPositiveOffsetUppercaseMaxDateTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get max datetime value with positive num offset /// 9999-12-31T23:59:59.9999999+14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<DateTime?> GetLocalPositiveOffsetUppercaseMaxDateTimeAsync( this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DateTime?> result = await operations.GetLocalPositiveOffsetUppercaseMaxDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Put max datetime value with positive numoffset /// 9999-12-31t23:59:59.9999999-14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='datetimeBody'> /// </param> public static void PutLocalNegativeOffsetMaxDateTime(this IDatetime operations, DateTime? datetimeBody) { Task.Factory.StartNew(s => ((IDatetime)s).PutLocalNegativeOffsetMaxDateTimeAsync(datetimeBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put max datetime value with positive numoffset /// 9999-12-31t23:59:59.9999999-14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='datetimeBody'> /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task PutLocalNegativeOffsetMaxDateTimeAsync( this IDatetime operations, DateTime? datetimeBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutLocalNegativeOffsetMaxDateTimeWithHttpMessagesAsync(datetimeBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get max datetime value with positive num offset /// 9999-12-31T23:59:59.9999999-14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static DateTime? GetLocalNegativeOffsetUppercaseMaxDateTime(this IDatetime operations) { return Task.Factory.StartNew(s => ((IDatetime)s).GetLocalNegativeOffsetUppercaseMaxDateTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get max datetime value with positive num offset /// 9999-12-31T23:59:59.9999999-14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<DateTime?> GetLocalNegativeOffsetUppercaseMaxDateTimeAsync( this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DateTime?> result = await operations.GetLocalNegativeOffsetUppercaseMaxDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Get max datetime value with positive num offset /// 9999-12-31t23:59:59.9999999-14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static DateTime? GetLocalNegativeOffsetLowercaseMaxDateTime(this IDatetime operations) { return Task.Factory.StartNew(s => ((IDatetime)s).GetLocalNegativeOffsetLowercaseMaxDateTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get max datetime value with positive num offset /// 9999-12-31t23:59:59.9999999-14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<DateTime?> GetLocalNegativeOffsetLowercaseMaxDateTimeAsync( this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DateTime?> result = await operations.GetLocalNegativeOffsetLowercaseMaxDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Put min datetime value 0001-01-01T00:00:00Z /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='datetimeBody'> /// </param> public static void PutUtcMinDateTime(this IDatetime operations, DateTime? datetimeBody) { Task.Factory.StartNew(s => ((IDatetime)s).PutUtcMinDateTimeAsync(datetimeBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put min datetime value 0001-01-01T00:00:00Z /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='datetimeBody'> /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task PutUtcMinDateTimeAsync( this IDatetime operations, DateTime? datetimeBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutUtcMinDateTimeWithHttpMessagesAsync(datetimeBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get min datetime value 0001-01-01T00:00:00Z /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static DateTime? GetUtcMinDateTime(this IDatetime operations) { return Task.Factory.StartNew(s => ((IDatetime)s).GetUtcMinDateTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get min datetime value 0001-01-01T00:00:00Z /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<DateTime?> GetUtcMinDateTimeAsync( this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DateTime?> result = await operations.GetUtcMinDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Put min datetime value 0001-01-01T00:00:00+14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='datetimeBody'> /// </param> public static void PutLocalPositiveOffsetMinDateTime(this IDatetime operations, DateTime? datetimeBody) { Task.Factory.StartNew(s => ((IDatetime)s).PutLocalPositiveOffsetMinDateTimeAsync(datetimeBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put min datetime value 0001-01-01T00:00:00+14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='datetimeBody'> /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task PutLocalPositiveOffsetMinDateTimeAsync( this IDatetime operations, DateTime? datetimeBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutLocalPositiveOffsetMinDateTimeWithHttpMessagesAsync(datetimeBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get min datetime value 0001-01-01T00:00:00+14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static DateTime? GetLocalPositiveOffsetMinDateTime(this IDatetime operations) { return Task.Factory.StartNew(s => ((IDatetime)s).GetLocalPositiveOffsetMinDateTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get min datetime value 0001-01-01T00:00:00+14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<DateTime?> GetLocalPositiveOffsetMinDateTimeAsync( this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DateTime?> result = await operations.GetLocalPositiveOffsetMinDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Put min datetime value 0001-01-01T00:00:00-14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='datetimeBody'> /// </param> public static void PutLocalNegativeOffsetMinDateTime(this IDatetime operations, DateTime? datetimeBody) { Task.Factory.StartNew(s => ((IDatetime)s).PutLocalNegativeOffsetMinDateTimeAsync(datetimeBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put min datetime value 0001-01-01T00:00:00-14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='datetimeBody'> /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task PutLocalNegativeOffsetMinDateTimeAsync( this IDatetime operations, DateTime? datetimeBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutLocalNegativeOffsetMinDateTimeWithHttpMessagesAsync(datetimeBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get min datetime value 0001-01-01T00:00:00-14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static DateTime? GetLocalNegativeOffsetMinDateTime(this IDatetime operations) { return Task.Factory.StartNew(s => ((IDatetime)s).GetLocalNegativeOffsetMinDateTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get min datetime value 0001-01-01T00:00:00-14:00 /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<DateTime?> GetLocalNegativeOffsetMinDateTimeAsync( this IDatetime operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DateTime?> result = await operations.GetLocalNegativeOffsetMinDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } } }
// --------------------------------------------------------------------------- // Copyright (C) 2006 Microsoft Corporation All Rights Reserved // --------------------------------------------------------------------------- #define CODE_ANALYSIS using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Design; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; using System.Security.Permissions; using System.Text; using System.Windows.Forms; using System.Windows.Forms.Design; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Design; namespace System.Workflow.Activities.Rules.Design { #region class RuleSetDialog public partial class RuleSetDialog : Form { #region members and constructors private RuleSet dialogRuleSet; private IServiceProvider serviceProvider; private Parser ruleParser; private const int numCols = 4; private bool[] sortOrder = new bool[numCols] { false, false, false, false }; public RuleSetDialog(Activity activity, RuleSet ruleSet) { if (activity == null) throw (new ArgumentNullException("activity")); InitializeDialog(ruleSet); ITypeProvider typeProvider; this.serviceProvider = activity.Site; if (this.serviceProvider != null) { typeProvider = (ITypeProvider)this.serviceProvider.GetService(typeof(ITypeProvider)); if (typeProvider == null) { string message = string.Format(CultureInfo.CurrentCulture, Messages.MissingService, typeof(ITypeProvider).FullName); throw new InvalidOperationException(message); } WorkflowDesignerLoader loader = this.serviceProvider.GetService(typeof(WorkflowDesignerLoader)) as WorkflowDesignerLoader; if (loader != null) loader.Flush(); } else { // no service provider, so make a TypeProvider that has all loaded Assemblies TypeProvider newProvider = new TypeProvider(null); foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies()) newProvider.AddAssembly(a); typeProvider = newProvider; } RuleValidation validation = new RuleValidation(activity, typeProvider, false); this.ruleParser = new Parser(validation); } public RuleSetDialog(Type activityType, ITypeProvider typeProvider, RuleSet ruleSet) { if (activityType == null) throw (new ArgumentNullException("activityType")); InitializeDialog(ruleSet); RuleValidation validation = new RuleValidation(activityType, typeProvider); this.ruleParser = new Parser(validation); } private void InitializeDialog(RuleSet ruleSet) { InitializeComponent(); this.conditionTextBox.PopulateAutoCompleteList += new EventHandler<AutoCompletionEventArgs>(PopulateAutoCompleteList); this.thenTextBox.PopulateAutoCompleteList += new EventHandler<AutoCompletionEventArgs>(PopulateAutoCompleteList); this.elseTextBox.PopulateAutoCompleteList += new EventHandler<AutoCompletionEventArgs>(PopulateAutoCompleteList); this.conditionTextBox.PopulateToolTipList += new EventHandler<AutoCompletionEventArgs>(PopulateAutoCompleteList); this.thenTextBox.PopulateToolTipList += new EventHandler<AutoCompletionEventArgs>(PopulateAutoCompleteList); this.elseTextBox.PopulateToolTipList += new EventHandler<AutoCompletionEventArgs>(PopulateAutoCompleteList); this.reevaluationComboBox.Items.Add(Messages.ReevaluationNever); this.reevaluationComboBox.Items.Add(Messages.ReevaluationAlways); this.chainingBehaviourComboBox.Items.Add(Messages.Sequential); this.chainingBehaviourComboBox.Items.Add(Messages.ExplicitUpdateOnly); this.chainingBehaviourComboBox.Items.Add(Messages.FullChaining); this.HelpRequested += new HelpEventHandler(OnHelpRequested); this.HelpButtonClicked += new CancelEventHandler(OnHelpClicked); if (ruleSet != null) this.dialogRuleSet = ruleSet.Clone(); else this.dialogRuleSet = new RuleSet(); this.chainingBehaviourComboBox.SelectedIndex = (int)this.dialogRuleSet.ChainingBehavior; this.rulesListView.Select(); foreach (Rule rule in this.dialogRuleSet.Rules) this.AddNewItem(rule); if (this.rulesListView.Items.Count > 0) this.rulesListView.Items[0].Selected = true; else rulesListView_SelectedIndexChanged(this, new EventArgs()); } #endregion #region public members public RuleSet RuleSet { get { return this.dialogRuleSet; } } #endregion #region event handlers private void PopulateAutoCompleteList(object sender, AutoCompletionEventArgs e) { e.AutoCompleteValues = this.ruleParser.GetExpressionCompletions(e.Prefix); } private void rulesListView_SelectedIndexChanged(object sender, EventArgs e) { if (this.rulesListView.SelectedItems.Count > 0) { Rule rule = this.rulesListView.SelectedItems[0].Tag as Rule; this.nameTextBox.Enabled = true; this.activeCheckBox.Enabled = true; this.reevaluationComboBox.Enabled = true; this.priorityTextBox.Enabled = true; this.conditionTextBox.Enabled = true; this.thenTextBox.Enabled = true; this.elseTextBox.Enabled = true; this.nameTextBox.Text = rule.Name; this.activeCheckBox.Checked = rule.Active; this.reevaluationComboBox.SelectedIndex = (int)rule.ReevaluationBehavior; this.priorityTextBox.Text = rule.Priority.ToString(CultureInfo.CurrentCulture); //Condition this.conditionTextBox.Text = rule.Condition != null ? rule.Condition.ToString().Replace("\n", "\r\n") : string.Empty; try { this.ruleParser.ParseCondition(this.conditionTextBox.Text); conditionErrorProvider.SetError(this.conditionTextBox, string.Empty); } catch (RuleSyntaxException ex) { conditionErrorProvider.SetError(this.conditionTextBox, ex.Message); } //Then this.thenTextBox.Text = GetActionsString(rule.ThenActions); try { this.ruleParser.ParseStatementList(this.thenTextBox.Text); thenErrorProvider.SetError(this.thenTextBox, string.Empty); } catch (RuleSyntaxException ex) { thenErrorProvider.SetError(this.thenTextBox, ex.Message); } //Else this.elseTextBox.Text = GetActionsString(rule.ElseActions); try { this.ruleParser.ParseStatementList(this.elseTextBox.Text); elseErrorProvider.SetError(this.elseTextBox, string.Empty); } catch (RuleSyntaxException ex) { elseErrorProvider.SetError(this.elseTextBox, ex.Message); } this.deleteToolStripButton.Enabled = true; } else { this.nameTextBox.Text = string.Empty; this.activeCheckBox.Checked = false; this.reevaluationComboBox.Text = string.Empty; this.priorityTextBox.Text = string.Empty; this.conditionTextBox.Text = string.Empty; this.thenTextBox.Text = string.Empty; this.elseTextBox.Text = string.Empty; this.nameTextBox.Enabled = false; this.activeCheckBox.Enabled = false; this.reevaluationComboBox.Enabled = false; this.priorityTextBox.Enabled = false; this.conditionTextBox.Enabled = false; this.thenTextBox.Enabled = false; this.elseTextBox.Enabled = false; conditionErrorProvider.SetError(this.conditionTextBox, string.Empty); thenErrorProvider.SetError(this.thenTextBox, string.Empty); elseErrorProvider.SetError(this.elseTextBox, string.Empty); this.deleteToolStripButton.Enabled = false; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void conditionTextBox_Validating(object sender, CancelEventArgs e) { if (this.rulesListView.SelectedItems.Count == 0) return; try { Rule rule = this.rulesListView.SelectedItems[0].Tag as Rule; RuleCondition ruleCondition = this.ruleParser.ParseCondition(this.conditionTextBox.Text); rule.Condition = ruleCondition; if (!string.IsNullOrEmpty(this.conditionTextBox.Text)) this.conditionTextBox.Text = ruleCondition.ToString().Replace("\n", "\r\n"); UpdateItem(this.rulesListView.SelectedItems[0], rule); conditionErrorProvider.SetError(this.conditionTextBox, string.Empty); } catch (Exception ex) { conditionErrorProvider.SetError(this.conditionTextBox, ex.Message); DesignerHelpers.DisplayError(Messages.Error_ConditionParser + "\n" + ex.Message, this.Text, this.serviceProvider); e.Cancel = true; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void thenTextBox_Validating(object sender, CancelEventArgs e) { if (this.rulesListView.SelectedItems.Count == 0) return; try { Rule rule = this.rulesListView.SelectedItems[0].Tag as Rule; List<RuleAction> ruleThenActions = this.ruleParser.ParseStatementList(this.thenTextBox.Text); this.thenTextBox.Text = GetActionsString(ruleThenActions); rule.ThenActions.Clear(); foreach (RuleAction ruleAction in ruleThenActions) rule.ThenActions.Add(ruleAction); UpdateItem(this.rulesListView.SelectedItems[0], rule); thenErrorProvider.SetError(this.thenTextBox, string.Empty); } catch (Exception ex) { thenErrorProvider.SetError(this.thenTextBox, ex.Message); DesignerHelpers.DisplayError(Messages.Error_ActionsParser + "\n" + ex.Message, this.Text, this.serviceProvider); e.Cancel = true; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void elseTextBox_Validating(object sender, CancelEventArgs e) { if (this.rulesListView.SelectedItems.Count == 0) return; try { Rule rule = (Rule)this.rulesListView.SelectedItems[0].Tag; List<RuleAction> ruleElseActions = this.ruleParser.ParseStatementList(this.elseTextBox.Text); this.elseTextBox.Text = GetActionsString(ruleElseActions); rule.ElseActions.Clear(); foreach (RuleAction ruleAction in ruleElseActions) rule.ElseActions.Add(ruleAction); UpdateItem(this.rulesListView.SelectedItems[0], rule); elseErrorProvider.SetError(this.elseTextBox, string.Empty); } catch (Exception ex) { elseErrorProvider.SetError(this.elseTextBox, ex.Message); DesignerHelpers.DisplayError(Messages.Error_ActionsParser + "\n" + ex.Message, this.Text, this.serviceProvider); e.Cancel = true; } } private void newRuleToolStripButton_Click(object sender, EventArgs e) { // verify to run validation first if (this.rulesToolStrip.Focus()) { Rule newRule = new Rule(); newRule.Name = CreateNewName(); this.dialogRuleSet.Rules.Add(newRule); ListViewItem listViewItem = AddNewItem(newRule); listViewItem.Selected = true; listViewItem.Focused = true; int index = rulesListView.Items.IndexOf(listViewItem); rulesListView.EnsureVisible(index); } } private void deleteToolStripButton_Click(object sender, EventArgs e) { IntellisenseTextBox itb = this.ActiveControl as IntellisenseTextBox; if (itb != null) itb.HideIntellisenceDropDown(); MessageBoxOptions mbo = (MessageBoxOptions)0; if (CultureInfo.CurrentUICulture.TextInfo.IsRightToLeft) mbo = MessageBoxOptions.RightAlign | MessageBoxOptions.RtlReading; DialogResult dr = MessageBox.Show(this, Messages.RuleConfirmDeleteMessageText, Messages.DeleteRule, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, mbo); if (dr == DialogResult.OK) { Rule rule = this.rulesListView.SelectedItems[0].Tag as Rule; int selectionIndex = this.rulesListView.SelectedIndices[0]; this.dialogRuleSet.Rules.Remove(rule); this.rulesListView.Items.RemoveAt(selectionIndex); if (this.rulesListView.Items.Count > 0) { int newSelectionIndex = Math.Min(selectionIndex, this.rulesListView.Items.Count - 1); this.rulesListView.Items[newSelectionIndex].Selected = true; } } } private void nameTextBox_Validating(object sender, CancelEventArgs e) { if (this.rulesListView.SelectedItems.Count > 0) { Rule rule = this.rulesListView.SelectedItems[0].Tag as Rule; if (this.nameTextBox.Text != rule.Name) { string ruleName = this.nameTextBox.Text; if (string.IsNullOrEmpty(ruleName)) { e.Cancel = true; DesignerHelpers.DisplayError(Messages.Error_RuleNameIsEmpty, this.Text, this.serviceProvider); } else if (rule.Name == ruleName) { this.nameTextBox.Text = ruleName; } else if (!IsUniqueIdentifier(ruleName)) { e.Cancel = true; DesignerHelpers.DisplayError(Messages.Error_DuplicateRuleName, this.Text, this.serviceProvider); } else { rule.Name = ruleName; UpdateItem(this.rulesListView.SelectedItems[0], rule); } } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void priorityTextBox_Validating(object sender, CancelEventArgs e) { if (this.rulesListView.SelectedItems.Count > 0) { Rule rule = this.rulesListView.SelectedItems[0].Tag as Rule; try { rule.Priority = int.Parse(this.priorityTextBox.Text, CultureInfo.CurrentCulture); UpdateItem(this.rulesListView.SelectedItems[0], rule); } catch { e.Cancel = true; DesignerHelpers.DisplayError(Messages.Error_InvalidPriority, this.Text, this.serviceProvider); } } } private void activeCheckBox_CheckedChanged(object sender, EventArgs e) { if (this.rulesListView.SelectedItems.Count > 0) { Rule rule = this.rulesListView.SelectedItems[0].Tag as Rule; rule.Active = this.activeCheckBox.Checked; UpdateItem(this.rulesListView.SelectedItems[0], rule); } } private void reevaluationComboBox_SelectedIndexChanged(object sender, EventArgs e) { if (this.rulesListView.SelectedItems.Count > 0) { Rule rule = this.rulesListView.SelectedItems[0].Tag as Rule; rule.ReevaluationBehavior = (RuleReevaluationBehavior)this.reevaluationComboBox.SelectedIndex; UpdateItem(this.rulesListView.SelectedItems[0], rule); } } private void chainingBehaviourComboBox_SelectedIndexChanged(object sender, EventArgs e) { this.dialogRuleSet.ChainingBehavior = (RuleChainingBehavior)this.chainingBehaviourComboBox.SelectedIndex; } private void rulesListView_ColumnClick(object sender, ColumnClickEventArgs e) { if (e.Column < numCols) { this.rulesListView.ListViewItemSorter = new ListViewItemComparer(e.Column, sortOrder[e.Column]); sortOrder[e.Column] = !sortOrder[e.Column]; } } #endregion #region private helpers private ListViewItem AddNewItem(Rule rule) { ListViewItem listViewItem = new ListViewItem(new string[] { rule.Name, String.Empty, String.Empty, String.Empty, String.Empty }); this.rulesListView.Items.Add(listViewItem); listViewItem.Tag = rule; UpdateItem(listViewItem, rule); return listViewItem; } private void UpdateItem(ListViewItem listViewItem, Rule rule) { listViewItem.SubItems[0].Text = rule.Name; listViewItem.SubItems[1].Text = rule.Priority.ToString(CultureInfo.CurrentCulture); listViewItem.SubItems[2].Text = (string)this.reevaluationComboBox.Items[(int)rule.ReevaluationBehavior]; listViewItem.SubItems[3].Text = rule.Active.ToString(CultureInfo.CurrentCulture); listViewItem.SubItems[4].Text = DesignerHelpers.GetRulePreview(rule); } private string CreateNewName() { string newRuleNameBase = Messages.NewRuleName; int index = 1; while (true) { string newRuleName = newRuleNameBase + index.ToString(CultureInfo.InvariantCulture); if (IsUniqueIdentifier(newRuleName)) return newRuleName; index++; } } private bool IsUniqueIdentifier(string name) { foreach (Rule rule1 in this.dialogRuleSet.Rules) { if (rule1.Name == name) return false; } return true; } private static string GetActionsString(IList<RuleAction> actions) { if (actions == null) throw new ArgumentNullException("actions"); bool first = true; StringBuilder actionsText = new StringBuilder(); foreach (RuleAction ruleAction in actions) { if (!first) actionsText.Append("\r\n"); else first = false; actionsText.Append(ruleAction.ToString()); } return actionsText.ToString(); } private static void SetCaretAt(TextBoxBase textBox, int position) { textBox.Focus(); textBox.SelectionStart = position; textBox.SelectionLength = 0; textBox.ScrollToCaret(); } #endregion #region class ListViewItemComparer private class ListViewItemComparer : IComparer { private int col; private bool ascending; public ListViewItemComparer(int column, bool ascending) { this.col = column; this.ascending = ascending; } public int Compare(object x, object y) { int retval = 0; ListViewItem item1 = (ListViewItem)x; ListViewItem item2 = (ListViewItem)y; if (this.col == 1) { // looking at priority int val1 = 0; int val2 = 0; int.TryParse(item1.SubItems[col].Text, NumberStyles.Integer, CultureInfo.CurrentCulture, out val1); int.TryParse(item2.SubItems[col].Text, NumberStyles.Integer, CultureInfo.CurrentCulture, out val2); if (val1 != val2) retval = (val2 - val1); else // priorities are the same, so sort on name (column 0) retval = String.Compare(item1.SubItems[0].Text, item2.SubItems[0].Text, StringComparison.CurrentCulture); } else { retval = String.Compare(item1.SubItems[col].Text, item2.SubItems[col].Text, StringComparison.CurrentCulture); } return ascending ? retval : -retval; } } #endregion protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { if (keyData.Equals(Keys.Escape)) { this.conditionTextBox.Validating -= this.conditionTextBox_Validating; this.thenTextBox.Validating -= this.thenTextBox_Validating; this.elseTextBox.Validating -= this.elseTextBox_Validating; } return base.ProcessCmdKey(ref msg, keyData); } private void OnHelpClicked(object sender, CancelEventArgs e) { e.Cancel = true; ShowHelp(); } private void OnHelpRequested(object sender, HelpEventArgs e) { ShowHelp(); } private void ShowHelp() { if (serviceProvider != null) { IHelpService helpService = serviceProvider.GetService(typeof(IHelpService)) as IHelpService; if (helpService != null) { helpService.ShowHelpFromKeyword(this.GetType().FullName + ".UI"); } else { IUIService uisvc = serviceProvider.GetService(typeof(IUIService)) as IUIService; if (uisvc != null) uisvc.ShowError(Messages.NoHelp); } } else { IUIService uisvc = (IUIService)GetService(typeof(IUIService)); if (uisvc != null) uisvc.ShowError(Messages.NoHelp); } } } #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 Apache.Ignite.Core.Tests.Cache.Store { using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Store; using Apache.Ignite.Core.Impl; using NUnit.Framework; /// <summary> /// Tests cache store functionality. /// </summary> public class CacheStoreTest { /** */ private const string BinaryStoreCacheName = "binary_store"; /** */ private const string ObjectStoreCacheName = "object_store"; /** */ private const string CustomStoreCacheName = "custom_store"; /** */ private const string TemplateStoreCacheName = "template_store*"; /// <summary> /// Fixture set up. /// </summary> [TestFixtureSetUp] public virtual void BeforeTests() { Ignition.Start(new IgniteConfiguration(TestUtils.GetTestConfiguration()) { IgniteInstanceName = GridName, SpringConfigUrl = "config\\native-client-test-cache-store.xml", }); } /// <summary> /// Fixture tear down. /// </summary> [TestFixtureTearDown] public void AfterTests() { Ignition.StopAll(true); } /// <summary> /// Test tear down. /// </summary> [TearDown] public void AfterTest() { CacheTestStore.Reset(); var cache = GetCache(); cache.Clear(); Assert.IsTrue(cache.IsEmpty(), "Cache is not empty: " + string.Join(", ", cache.Select(x => string.Format("[{0}:{1}]", x.Key, x.Value)))); TestUtils.AssertHandleRegistryHasItems(300, 3, Ignition.GetIgnite(GridName)); } /// <summary> /// Tests that simple cache loading works and exceptions are propagated properly. /// </summary> [Test] public void TestLoadCache() { var cache = GetCache(); Assert.AreEqual(0, cache.GetSize()); cache.LoadCache(new CacheEntryFilter(), 100, 10); Assert.AreEqual(5, cache.GetSize()); for (int i = 105; i < 110; i++) Assert.AreEqual("val_" + i, cache.Get(i)); // Test exception in filter Assert.Throws<CacheStoreException>(() => cache.LoadCache(new ExceptionalEntryFilter(), 100, 10)); // Test exception in store CacheTestStore.ThrowError = true; CheckCustomStoreError(Assert.Throws<CacheStoreException>(() => cache.LoadCache(new CacheEntryFilter(), 100, 10)).InnerException); } /// <summary> /// Tests cache loading in local mode. /// </summary> [Test] public void TestLocalLoadCache() { var cache = GetCache(); Assert.AreEqual(0, cache.GetSize()); cache.LocalLoadCache(new CacheEntryFilter(), 100, 10); Assert.AreEqual(5, cache.GetSize()); for (int i = 105; i < 110; i++) Assert.AreEqual("val_" + i, cache.Get(i)); } /// <summary> /// Tests that object metadata propagates properly during cache loading. /// </summary> [Test] public void TestLoadCacheMetadata() { CacheTestStore.LoadObjects = true; var cache = GetCache(); Assert.AreEqual(0, cache.GetSize()); cache.LocalLoadCache(null, 0, 3); Assert.AreEqual(3, cache.GetSize()); var meta = cache.WithKeepBinary<Key, IBinaryObject>().Get(new Key(0)).GetBinaryType(); Assert.NotNull(meta); Assert.AreEqual("Apache.Ignite.Core.Tests.Cache.Store.Value", meta.TypeName); } /// <summary> /// Tests asynchronous cache load. /// </summary> [Test] public void TestLoadCacheAsync() { var cache = GetCache(); Assert.AreEqual(0, cache.GetSize()); cache.LocalLoadCacheAsync(new CacheEntryFilter(), 100, 10).Wait(); Assert.AreEqual(5, cache.GetSizeAsync().Result); for (int i = 105; i < 110; i++) { Assert.AreEqual("val_" + i, cache.GetAsync(i).Result); } // Test errors CacheTestStore.ThrowError = true; CheckCustomStoreError( Assert.Throws<AggregateException>( () => cache.LocalLoadCacheAsync(new CacheEntryFilter(), 100, 10).Wait()) .InnerException); } /// <summary> /// Tests write-through and read-through behavior. /// </summary> [Test] public void TestPutLoad() { var cache = GetCache(); cache.Put(1, "val"); IDictionary map = GetStoreMap(); Assert.AreEqual(1, map.Count); // TODO: IGNITE-4535 //cache.LocalEvict(new[] { 1 }); //Assert.AreEqual(0, cache.GetSize(CachePeekMode.All)); Assert.AreEqual("val", cache.Get(1)); Assert.AreEqual(1, cache.GetSize()); } [Test] public void TestExceptions() { var cache = GetCache(); cache.Put(1, "val"); CacheTestStore.ThrowError = true; CheckCustomStoreError(Assert.Throws<CacheStoreException>(() => cache.Put(-2, "fail")).InnerException); // TODO: IGNITE-4535 //cache.LocalEvict(new[] {1}); //CheckCustomStoreError(Assert.Throws<CacheStoreException>(() => cache.Get(1)).InnerException); CacheTestStore.ThrowError = false; cache.Remove(1); } [Test] [Ignore("IGNITE-4657")] public void TestExceptionsNoRemove() { var cache = GetCache(); cache.Put(1, "val"); CacheTestStore.ThrowError = true; CheckCustomStoreError(Assert.Throws<CacheStoreException>(() => cache.Put(-2, "fail")).InnerException); cache.LocalEvict(new[] {1}); CheckCustomStoreError(Assert.Throws<CacheStoreException>(() => cache.Get(1)).InnerException); } /// <summary> /// Tests write-through and read-through behavior with binarizable values. /// </summary> [Test] public void TestPutLoadBinarizable() { var cache = GetBinaryStoreCache<int, Value>(); cache.Put(1, new Value(1)); IDictionary map = GetStoreMap(); Assert.AreEqual(1, map.Count); IBinaryObject v = (IBinaryObject)map[1]; Assert.AreEqual(1, v.GetField<int>("_idx")); // TODO: IGNITE-4535 //cache.LocalEvict(new[] { 1 }); //Assert.AreEqual(0, cache.GetSize()); Assert.AreEqual(1, cache.Get(1).Index); Assert.AreEqual(1, cache.GetSize()); } /// <summary> /// Tests write-through and read-through behavior with storeKeepBinary=false. /// </summary> [Test] public void TestPutLoadObjects() { var cache = GetObjectStoreCache<int, Value>(); cache.Put(1, new Value(1)); IDictionary map = GetStoreMap(); Assert.AreEqual(1, map.Count); Value v = (Value)map[1]; Assert.AreEqual(1, v.Index); // TODO: IGNITE-4535 //cache.LocalEvict(new[] { 1 }); //Assert.AreEqual(0, cache.GetSize()); Assert.AreEqual(1, cache.Get(1).Index); Assert.AreEqual(1, cache.GetSize()); } /// <summary> /// Tests cache store LoadAll functionality. /// </summary> [Test] public void TestPutLoadAll() { var putMap = new Dictionary<int, string>(); for (int i = 0; i < 10; i++) putMap.Add(i, "val_" + i); var cache = GetCache(); cache.PutAll(putMap); IDictionary map = GetStoreMap(); Assert.AreEqual(10, map.Count); for (int i = 0; i < 10; i++) Assert.AreEqual("val_" + i, map[i]); cache.Clear(); Assert.AreEqual(0, cache.GetSize()); ICollection<int> keys = new List<int>(); for (int i = 0; i < 10; i++) keys.Add(i); IDictionary<int, string> loaded = cache.GetAll(keys).ToDictionary(x => x.Key, x => x.Value); Assert.AreEqual(10, loaded.Count); for (int i = 0; i < 10; i++) Assert.AreEqual("val_" + i, loaded[i]); Assert.AreEqual(10, cache.GetSize()); } /// <summary> /// Tests cache store removal. /// </summary> [Test] public void TestRemove() { var cache = GetCache(); for (int i = 0; i < 10; i++) cache.Put(i, "val_" + i); IDictionary map = GetStoreMap(); Assert.AreEqual(10, map.Count); for (int i = 0; i < 5; i++) cache.Remove(i); Assert.AreEqual(5, map.Count); for (int i = 5; i < 10; i++) Assert.AreEqual("val_" + i, map[i]); } /// <summary> /// Tests cache store removal. /// </summary> [Test] public void TestRemoveAll() { var cache = GetCache(); for (int i = 0; i < 10; i++) cache.Put(i, "val_" + i); IDictionary map = GetStoreMap(); Assert.AreEqual(10, map.Count); cache.RemoveAll(new List<int> { 0, 1, 2, 3, 4 }); Assert.AreEqual(5, map.Count); for (int i = 5; i < 10; i++) Assert.AreEqual("val_" + i, map[i]); } /// <summary> /// Tests cache store with transactions. /// </summary> [Test] public void TestTx() { var cache = GetCache(); using (var tx = cache.Ignite.GetTransactions().TxStart()) { tx.AddMeta("meta", 100); cache.Put(1, "val"); tx.Commit(); } IDictionary map = GetStoreMap(); Assert.AreEqual(1, map.Count); Assert.AreEqual("val", map[1]); } /// <summary> /// Tests multithreaded cache loading. /// </summary> [Test] public void TestLoadCacheMultithreaded() { CacheTestStore.LoadMultithreaded = true; var cache = GetCache(); Assert.AreEqual(0, cache.GetSize()); cache.LocalLoadCache(null, 0, null); Assert.AreEqual(1000, cache.GetSize()); for (int i = 0; i < 1000; i++) Assert.AreEqual("val_" + i, cache.Get(i)); } /// <summary> /// Tests that cache store property values are propagated from Spring XML. /// </summary> [Test] public void TestCustomStoreProperties() { var cache = GetCustomStoreCache(); Assert.IsNotNull(cache); Assert.AreEqual(42, CacheTestStore.intProperty); Assert.AreEqual("String value", CacheTestStore.stringProperty); } /// <summary> /// Tests cache store with dynamically started cache. /// </summary> [Test] public void TestDynamicStoreStart() { var grid = Ignition.GetIgnite(GridName); var reg = ((Ignite) grid).HandleRegistry; var handleCount = reg.Count; var cache = GetTemplateStoreCache(); Assert.IsNotNull(cache); cache.Put(1, cache.Name); Assert.AreEqual(cache.Name, CacheTestStore.Map[1]); Assert.AreEqual(handleCount + 1, reg.Count); grid.DestroyCache(cache.Name); Assert.AreEqual(handleCount, reg.Count); } /// <summary> /// Tests the load all. /// </summary> [Test] public void TestLoadAll([Values(true, false)] bool isAsync) { var cache = GetCache(); var loadAll = isAsync ? (Action<IEnumerable<int>, bool>) ((x, y) => { cache.LoadAllAsync(x, y).Wait(); }) : cache.LoadAll; Assert.AreEqual(0, cache.GetSize()); loadAll(Enumerable.Range(105, 5), false); Assert.AreEqual(5, cache.GetSize()); for (int i = 105; i < 110; i++) Assert.AreEqual("val_" + i, cache[i]); // Test overwrite cache[105] = "42"; cache.LocalEvict(new[] { 105 }); loadAll(new[] {105}, false); Assert.AreEqual("42", cache[105]); loadAll(new[] {105, 106}, true); Assert.AreEqual("val_105", cache[105]); Assert.AreEqual("val_106", cache[106]); } /// <summary> /// Tests the argument passing to LoadCache method. /// </summary> [Test] public void TestArgumentPassing() { var cache = GetBinaryStoreCache<object, object>(); Action<object> checkValue = o => { cache.Clear(); Assert.AreEqual(0, cache.GetSize()); cache.LoadCache(null, null, 1, o); Assert.AreEqual(o, cache[1]); }; // Null. cache.LoadCache(null, null); Assert.AreEqual(0, cache.GetSize()); // Empty args array. cache.LoadCache(null); Assert.AreEqual(0, cache.GetSize()); // Simple types. checkValue(1); checkValue(new[] {1, 2, 3}); checkValue("1"); checkValue(new[] {"1", "2"}); checkValue(Guid.NewGuid()); checkValue(new[] {Guid.NewGuid(), Guid.NewGuid()}); checkValue(DateTime.Now); checkValue(new[] {DateTime.Now, DateTime.UtcNow}); // Collections. checkValue(new ArrayList {1, "2", 3.3}); checkValue(new List<int> {1, 2}); checkValue(new Dictionary<int, string> {{1, "foo"}}); } /// <summary> /// Get's grid name for this test. /// </summary> /// <value>Grid name.</value> protected virtual string GridName { get { return null; } } /// <summary> /// Gets the store map. /// </summary> private static IDictionary GetStoreMap() { return CacheTestStore.Map; } /// <summary> /// Gets the cache. /// </summary> private ICache<int, string> GetCache() { return GetBinaryStoreCache<int, string>(); } /// <summary> /// Gets the binary store cache. /// </summary> private ICache<TK, TV> GetBinaryStoreCache<TK, TV>() { return Ignition.GetIgnite(GridName).GetCache<TK, TV>(BinaryStoreCacheName); } /// <summary> /// Gets the object store cache. /// </summary> private ICache<TK, TV> GetObjectStoreCache<TK, TV>() { return Ignition.GetIgnite(GridName).GetCache<TK, TV>(ObjectStoreCacheName); } /// <summary> /// Gets the custom store cache. /// </summary> private ICache<int, string> GetCustomStoreCache() { return Ignition.GetIgnite(GridName).GetCache<int, string>(CustomStoreCacheName); } /// <summary> /// Gets the template store cache. /// </summary> private ICache<int, string> GetTemplateStoreCache() { var cacheName = TemplateStoreCacheName.Replace("*", Guid.NewGuid().ToString()); return Ignition.GetIgnite(GridName).GetOrCreateCache<int, string>(cacheName); } /// <summary> /// Checks the custom store error. /// </summary> private static void CheckCustomStoreError(Exception err) { var customErr = err as CacheTestStore.CustomStoreException ?? err.InnerException as CacheTestStore.CustomStoreException; Assert.IsNotNull(customErr); Assert.AreEqual(customErr.Message, customErr.Details); } } /// <summary> /// Cache key. /// </summary> internal class Key { /** */ private readonly int _idx; /// <summary> /// Initializes a new instance of the <see cref="Key"/> class. /// </summary> public Key(int idx) { _idx = idx; } /** <inheritdoc /> */ public override bool Equals(object obj) { if (obj == null || obj.GetType() != GetType()) return false; return ((Key)obj)._idx == _idx; } /** <inheritdoc /> */ public override int GetHashCode() { return _idx; } } /// <summary> /// Cache value. /// </summary> internal class Value { /** */ private readonly int _idx; /// <summary> /// Initializes a new instance of the <see cref="Value"/> class. /// </summary> public Value(int idx) { _idx = idx; } /// <summary> /// Gets the index. /// </summary> public int Index { get { return _idx; } } } /// <summary> /// Cache entry predicate. /// </summary> [Serializable] public class CacheEntryFilter : ICacheEntryFilter<int, string> { /** <inheritdoc /> */ public bool Invoke(ICacheEntry<int, string> entry) { return entry.Key >= 105; } } /// <summary> /// Cache entry predicate that throws an exception. /// </summary> [Serializable] public class ExceptionalEntryFilter : ICacheEntryFilter<int, string> { /** <inheritdoc /> */ public bool Invoke(ICacheEntry<int, string> entry) { throw new Exception("Expected exception in ExceptionalEntryFilter"); } } }
using System; using System.Collections.Generic; using System.Text; using System.Drawing; using System.Windows.Forms; using System.Threading; namespace Cards.GUI { static class SpadesGui { static Card card = new Card(); public static CardBack CardBack = CardBack.Heart; static Graphics G = null; static List<player> SpadesPlayer; static Pot Pot; static GameData gameData; static bool backFace = true; static bool cardFaceCheat = false; public static bool CardFaceCheat { get { return SpadesGui.cardFaceCheat; } set { SpadesGui.cardFaceCheat = value; } } public static bool BackFace { get { return SpadesGui.backFace; } set { SpadesGui.backFace = value; } } public static bool Initialize(ref GameData gData){ try { // targetForm = _targetForm; gameData = gData; SpadesPlayer = gData.CurrentPlayerList;//spadesPlayer; Pot = gData.CurrentPot; } catch (Exception ex) { string message = ex.Message; return false; } return true; } /// <summary> /// Refresh the whole GUI with current information about the card and player /// </summary> /// <param name="graphics"></param> /// <param name="gData"></param> public static void refreshBoard(Graphics graphics, ref GameData gData) { G = graphics; gameData = gData; foreach (player p in SpadesPlayer) { drawPlayerHand(p); drawPlayerName(p); if (gameData.GameState != GameState.INTRO) drawPlayerBidsAndTricks(p); } drawPot(); } /// <summary> /// Draws the card in the pot /// card position are defined within the card class itself /// so the card position must be updated when adding to pot for display /// </summary> public static void drawPot() { int potCount = Pot.CardPile.Count; if ( potCount > 0) { foreach (Cards.SpadesCard pot in Pot.CardPile) { card.Begin(G); int xnew = pot.CardPositionX; int ynew = pot.CardPositionY; card.DrawCard(new Point(xnew, ynew), pot.CardIndex); card.End(); } } } /// <summary> /// Draws player Bid and tricks on the screen /// </summary> /// <param name="p">Player to draw </param> public static void drawPlayerBidsAndTricks(player p) { // Create font and brush. Font drawFont = new Font("verdana", 8.5f, FontStyle.Bold); SolidBrush drawBrush = new SolidBrush(Color.Black); StringFormat sf; // Create point for upper-left corner of drawing. PointF drawPoint = new PointF(0,0); sf = new StringFormat(); // draw with respective to client switch (Cards.Main.playerPositions[p.ID].seat) { case "S": //drawPoint = new PointF(p.PositionX + 50, p.PositionY - 20); drawPoint = new PointF(Cards.Main.playerPositions[p.ID].x + 50, Cards.Main.playerPositions[p.ID].y - 20); break; case "W": sf = new StringFormat(StringFormatFlags.DirectionVertical); drawPoint = new PointF(Cards.Main.playerPositions[p.ID].x + 70, Cards.Main.playerPositions[p.ID].y + 60); break; case "N": drawPoint = new PointF(Cards.Main.playerPositions[p.ID].x + 50, Cards.Main.playerPositions[p.ID].y + 100); break; case "E": sf = new StringFormat(StringFormatFlags.DirectionVertical); drawPoint = new PointF(Cards.Main.playerPositions[p.ID].x - 25, Cards.Main.playerPositions[p.ID].y + 60); break; } G.DrawString("Bid : " + p.TotalBid.ToString() +" " + "Tricks : " + p.TotalTrick.ToString(), drawFont, drawBrush, drawPoint,sf); } /// <summary> /// draws the card in player hands /// cards position must be updated before calling this function /// </summary> /// <param name="p">player of which to draw the hand </param> public static void drawPlayerHand(player p) { cardFaceCheat = false; if (CardFaceCheat == false) { if (p.ID == Cards.Main.boardBelongsTo) BackFace = false; else BackFace = true; } else { // if cheat enabled BackFace = false; } int xinc = 0; int yinc = 0; foreach (SpadesCard c in p.Hand.CardPile) { card.Begin(G); int xnew = Main.playerPositions[p.ID].x + xinc; int ynew = Main.playerPositions[p.ID].y + yinc; if (c.MoveUp == true) ynew = ynew - 5; if (!BackFace) card.DrawCard(new Point(xnew, ynew), c.CardIndex); else card.DrawCardBack(new Point(xnew, ynew), CardBack); card.End(); if (Main.playerPositions[p.ID].seat == "N" || Main.playerPositions[p.ID].seat == "S") xinc = xinc + 15; else yinc = yinc + 15; } } /// <summary> /// draws player name on the screen /// </summary> /// <param name="p">Player to draw the name of.</param> public static void drawPlayerName(player p){ //draw name also String drawString = p.Name; PointF drawPoint; StringFormat sf; // if (p.IsActivePlayer) // Create font and brush. Font drawFont = new Font("Arial", 8.5f,FontStyle.Bold); SolidBrush drawBrush = new SolidBrush(Color.Black); drawPoint = new PointF(0, 0); sf = new StringFormat(); switch (Cards.Main.playerPositions[p.ID].seat) { case "S": { sf = new StringFormat(StringFormatFlags.DirectionRightToLeft); drawPoint = new PointF((Cards.Main.playerPositions[p.ID].x), Cards.Main.playerPositions[p.ID].y + 85); break; } case "W": { drawPoint = new PointF(Cards.Main.playerPositions[p.ID].x, Cards.Main.playerPositions[p.ID].y - 15); break; } case "N": { drawPoint = new PointF(Cards.Main.playerPositions[p.ID].x + ((13 * 15) + 60), Cards.Main.playerPositions[p.ID].y); break; } case "E": { drawPoint = new PointF(Cards.Main.playerPositions[p.ID].x, Cards.Main.playerPositions[p.ID].y + (13 * 15) + 85); break; } } G.DrawString(drawString, drawFont, drawBrush, drawPoint, sf); } public static void Refresh() { refreshBoard(G, ref gameData); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Twoparam.accessibility001.accessibility001 { public class Test { private int this[int x] { set { Status = 0; } } public static int Status = -1; public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Test b = new Test(); dynamic x = int.MaxValue; b[x] = 1; return Status; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Twoparam.accessibility002.accessibility002 { public class Test { protected int this[int x] { set { Status = 0; } } public static int Status = -1; public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { var b = new Test(); dynamic x = int.MaxValue; b[x] = 1; return Status; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Twoparam.accessibility005.accessibility005 { public class Test { private class Base { public int this[int x] { set { Test.Status = 1; } } } public static int Status; public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Base b = new Base(); dynamic x = int.MaxValue; b[x] = 1; if (Test.Status == 1) return 0; return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Twoparam.accessibility006.accessibility006 { public class Test { protected class Base { public int this[int x] { set { Test.Status = 1; } } } public static int Status; public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Base b = new Base(); dynamic x = int.MaxValue; b[x] = 1; if (Test.Status == 1) return 0; return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Twoparam.accessibility007.accessibility007 { public class Test { internal class Base { public int this[int x] { set { Test.Status = 1; } } } public static int Status; public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Base b = new Base(); dynamic x = int.MaxValue; b[x] = 1; if (Test.Status == 1) return 0; return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Twoparam.accessibility011.accessibility011 { public class Test { public static int Status; public class Higher { private class Base { public int this[int x] { set { Test.Status = 1; } } } public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Base b = new Base(); dynamic x = int.MaxValue; b[x] = 1; if (Test.Status == 1) return 0; return 1; } } } // </Code> }
using Lucene.Net.Diagnostics; using System; using System.Collections.Generic; using System.Text; namespace Lucene.Net.Search { /* * 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 AtomicReader = Lucene.Net.Index.AtomicReader; using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using DocsEnum = Lucene.Net.Index.DocsEnum; using IBits = Lucene.Net.Util.IBits; using IndexReaderContext = Lucene.Net.Index.IndexReaderContext; using ReaderUtil = Lucene.Net.Index.ReaderUtil; using Similarity = Lucene.Net.Search.Similarities.Similarity; using SimScorer = Lucene.Net.Search.Similarities.Similarity.SimScorer; using Term = Lucene.Net.Index.Term; using TermContext = Lucene.Net.Index.TermContext; using TermsEnum = Lucene.Net.Index.TermsEnum; using TermState = Lucene.Net.Index.TermState; using ToStringUtils = Lucene.Net.Util.ToStringUtils; /// <summary> /// A <see cref="Query"/> that matches documents containing a term. /// this may be combined with other terms with a <see cref="BooleanQuery"/>. /// </summary> #if FEATURE_SERIALIZABLE [Serializable] #endif public class TermQuery : Query { private readonly Term term; private readonly int docFreq; private readonly TermContext perReaderTermState; internal sealed class TermWeight : Weight { private readonly TermQuery outerInstance; internal readonly Similarity similarity; internal readonly Similarity.SimWeight stats; internal readonly TermContext termStates; public TermWeight(TermQuery outerInstance, IndexSearcher searcher, TermContext termStates) { this.outerInstance = outerInstance; if (Debugging.AssertsEnabled) Debugging.Assert(termStates != null, "TermContext must not be null"); this.termStates = termStates; this.similarity = searcher.Similarity; this.stats = similarity.ComputeWeight(outerInstance.Boost, searcher.CollectionStatistics(outerInstance.term.Field), searcher.TermStatistics(outerInstance.term, termStates)); } public override string ToString() { return "weight(" + outerInstance + ")"; } public override Query Query => outerInstance; public override float GetValueForNormalization() { return stats.GetValueForNormalization(); } public override void Normalize(float queryNorm, float topLevelBoost) { stats.Normalize(queryNorm, topLevelBoost); } public override Scorer GetScorer(AtomicReaderContext context, IBits acceptDocs) { if (Debugging.AssertsEnabled) Debugging.Assert(termStates.TopReaderContext == ReaderUtil.GetTopLevelContext(context), () => "The top-reader used to create Weight (" + termStates.TopReaderContext + ") is not the same as the current reader's top-reader (" + ReaderUtil.GetTopLevelContext(context)); TermsEnum termsEnum = GetTermsEnum(context); if (termsEnum == null) { return null; } DocsEnum docs = termsEnum.Docs(acceptDocs, null); if (Debugging.AssertsEnabled) Debugging.Assert(docs != null); return new TermScorer(this, docs, similarity.GetSimScorer(stats, context)); } /// <summary> /// Returns a <see cref="TermsEnum"/> positioned at this weights <see cref="Index.Term"/> or <c>null</c> if /// the term does not exist in the given context. /// </summary> private TermsEnum GetTermsEnum(AtomicReaderContext context) { TermState state = termStates.Get(context.Ord); if (state == null) // term is not present in that reader { if (Debugging.AssertsEnabled) Debugging.Assert(TermNotInReader(context.AtomicReader, outerInstance.term), () => "no termstate found but term exists in reader term=" + outerInstance.term); return null; } //System.out.println("LD=" + reader.getLiveDocs() + " set?=" + (reader.getLiveDocs() != null ? reader.getLiveDocs().get(0) : "null")); TermsEnum termsEnum = context.AtomicReader.GetTerms(outerInstance.term.Field).GetEnumerator(); termsEnum.SeekExact(outerInstance.term.Bytes, state); return termsEnum; } private bool TermNotInReader(AtomicReader reader, Term term) { // only called from assert //System.out.println("TQ.termNotInReader reader=" + reader + " term=" + field + ":" + bytes.utf8ToString()); return reader.DocFreq(term) == 0; } public override Explanation Explain(AtomicReaderContext context, int doc) { Scorer scorer = GetScorer(context, context.AtomicReader.LiveDocs); if (scorer != null) { int newDoc = scorer.Advance(doc); if (newDoc == doc) { float freq = scorer.Freq; SimScorer docScorer = similarity.GetSimScorer(stats, context); ComplexExplanation result = new ComplexExplanation(); result.Description = "weight(" + Query + " in " + doc + ") [" + similarity.GetType().Name + "], result of:"; Explanation scoreExplanation = docScorer.Explain(doc, new Explanation(freq, "termFreq=" + freq)); result.AddDetail(scoreExplanation); result.Value = scoreExplanation.Value; result.Match = true; return result; } } return new ComplexExplanation(false, 0.0f, "no matching term"); } } /// <summary> /// Constructs a query for the term <paramref name="t"/>. </summary> public TermQuery(Term t) : this(t, -1) { } /// <summary> /// Expert: constructs a <see cref="TermQuery"/> that will use the /// provided <paramref name="docFreq"/> instead of looking up the docFreq /// against the searcher. /// </summary> public TermQuery(Term t, int docFreq) { term = t; this.docFreq = docFreq; perReaderTermState = null; } /// <summary> /// Expert: constructs a <see cref="TermQuery"/> that will use the /// provided docFreq instead of looking up the docFreq /// against the searcher. /// </summary> public TermQuery(Term t, TermContext states) { if (Debugging.AssertsEnabled) Debugging.Assert(states != null); term = t; docFreq = states.DocFreq; perReaderTermState = states; } /// <summary> /// Returns the term of this query. </summary> public virtual Term Term => term; public override Weight CreateWeight(IndexSearcher searcher) { IndexReaderContext context = searcher.TopReaderContext; TermContext termState; if (perReaderTermState == null || perReaderTermState.TopReaderContext != context) { // make TermQuery single-pass if we don't have a PRTS or if the context differs! termState = TermContext.Build(context, term); } else { // PRTS was pre-build for this IS termState = this.perReaderTermState; } // we must not ignore the given docFreq - if set use the given value (lie) if (docFreq != -1) { termState.DocFreq = docFreq; } return new TermWeight(this, searcher, termState); } public override void ExtractTerms(ISet<Term> terms) { terms.Add(Term); } /// <summary> /// Prints a user-readable version of this query. </summary> public override string ToString(string field) { StringBuilder buffer = new StringBuilder(); if (!term.Field.Equals(field, StringComparison.Ordinal)) { buffer.Append(term.Field); buffer.Append(":"); } buffer.Append(term.Text()); buffer.Append(ToStringUtils.Boost(Boost)); return buffer.ToString(); } /// <summary> /// Returns <c>true</c> if <paramref name="o"/> is equal to this. </summary> public override bool Equals(object o) { if (!(o is TermQuery)) { return false; } TermQuery other = (TermQuery)o; return (this.Boost == other.Boost) && this.term.Equals(other.term); } /// <summary> /// Returns a hash code value for this object. </summary> public override int GetHashCode() { return J2N.BitConversion.SingleToInt32Bits(Boost) ^ term.GetHashCode(); } } }
// // Copyright (c) 2004-2020 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using Xunit; using NLog.Common; using System.Text; using NLog.Time; using Xunit.Extensions; namespace NLog.UnitTests.Common { public class InternalLoggerTests : NLogTestBase, IDisposable { /// <summary> /// Test the return values of all Is[Level]Enabled() methods. /// </summary> [Fact] public void IsEnabledTests() { // Setup LogLevel to minimum named level. InternalLogger.LogLevel = LogLevel.Trace; Assert.True(InternalLogger.IsTraceEnabled); Assert.True(InternalLogger.IsDebugEnabled); Assert.True(InternalLogger.IsInfoEnabled); Assert.True(InternalLogger.IsWarnEnabled); Assert.True(InternalLogger.IsErrorEnabled); Assert.True(InternalLogger.IsFatalEnabled); // Setup LogLevel to maximum named level. InternalLogger.LogLevel = LogLevel.Fatal; Assert.False(InternalLogger.IsTraceEnabled); Assert.False(InternalLogger.IsDebugEnabled); Assert.False(InternalLogger.IsInfoEnabled); Assert.False(InternalLogger.IsWarnEnabled); Assert.False(InternalLogger.IsErrorEnabled); Assert.True(InternalLogger.IsFatalEnabled); // Switch off the internal logging. InternalLogger.LogLevel = LogLevel.Off; Assert.False(InternalLogger.IsTraceEnabled); Assert.False(InternalLogger.IsDebugEnabled); Assert.False(InternalLogger.IsInfoEnabled); Assert.False(InternalLogger.IsWarnEnabled); Assert.False(InternalLogger.IsErrorEnabled); Assert.False(InternalLogger.IsFatalEnabled); } [Fact] public void WriteToStringWriterTests() { try { // Expected result is the same for both types of method invocation. const string expected = "Warn WWW\nError EEE\nFatal FFF\nTrace TTT\nDebug DDD\nInfo III\n"; InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; { StringWriter writer1 = new StringWriter() { NewLine = "\n" }; InternalLogger.LogWriter = writer1; // Named (based on LogLevel) public methods. InternalLogger.Warn("WWW"); InternalLogger.Error("EEE"); InternalLogger.Fatal("FFF"); InternalLogger.Trace("TTT"); InternalLogger.Debug("DDD"); InternalLogger.Info("III"); TestWriter(expected, writer1); } { // // Reconfigure the LogWriter. StringWriter writer2 = new StringWriter() { NewLine = "\n" }; InternalLogger.LogWriter = writer2; // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, "WWW"); InternalLogger.Log(LogLevel.Error, "EEE"); InternalLogger.Log(LogLevel.Fatal, "FFF"); InternalLogger.Log(LogLevel.Trace, "TTT"); InternalLogger.Log(LogLevel.Debug, "DDD"); InternalLogger.Log(LogLevel.Info, "III"); TestWriter(expected, writer2); } { // // Reconfigure the LogWriter. StringWriter writer2 = new StringWriter() { NewLine = "\n" }; InternalLogger.LogWriter = writer2; // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, () => "WWW"); InternalLogger.Log(LogLevel.Error, () => "EEE"); InternalLogger.Log(LogLevel.Fatal, () => "FFF"); InternalLogger.Log(LogLevel.Trace, () => "TTT"); InternalLogger.Log(LogLevel.Debug, () => "DDD"); InternalLogger.Log(LogLevel.Info, () => "III"); TestWriter(expected, writer2); } } finally { InternalLogger.Reset(); } } [Fact] public void WriteToStringWriterWithArgsTests() { try { // Expected result is the same for both types of method invocation. const string expected = "Warn WWW 0\nError EEE 0, 1\nFatal FFF 0, 1, 2\nTrace TTT 0, 1, 2\nDebug DDD 0, 1\nInfo III 0\n"; InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; { StringWriter writer1 = new StringWriter() { NewLine = "\n" }; InternalLogger.LogWriter = writer1; // Named (based on LogLevel) public methods. InternalLogger.Warn("WWW {0}", 0); InternalLogger.Error("EEE {0}, {1}", 0, 1); InternalLogger.Fatal("FFF {0}, {1}, {2}", 0, 1, 2); InternalLogger.Trace("TTT {0}, {1}, {2}", 0, 1, 2); InternalLogger.Debug("DDD {0}, {1}", 0, 1); InternalLogger.Info("III {0}", 0); TestWriter(expected, writer1); } { // // Reconfigure the LogWriter. StringWriter writer2 = new StringWriter() { NewLine = "\n" }; InternalLogger.LogWriter = writer2; // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, "WWW {0}", 0); InternalLogger.Log(LogLevel.Error, "EEE {0}, {1}", 0, 1); InternalLogger.Log(LogLevel.Fatal, "FFF {0}, {1}, {2}", 0, 1, 2); InternalLogger.Log(LogLevel.Trace, "TTT {0}, {1}, {2}", 0, 1, 2); InternalLogger.Log(LogLevel.Debug, "DDD {0}, {1}", 0, 1); InternalLogger.Log(LogLevel.Info, "III {0}", 0); TestWriter(expected, writer2); } } finally { InternalLogger.Reset(); } } /// <summary> /// Test output van een textwriter /// </summary> /// <param name="expected"></param> /// <param name="writer"></param> private static void TestWriter(string expected, StringWriter writer) { writer.Flush(); var writerOutput = writer.ToString(); Assert.Equal(expected, writerOutput); } [Fact] public void WriteToConsoleOutTests() { // Expected result is the same for both types of method invocation. const string expected = "Warn WWW\nError EEE\nFatal FFF\nTrace TTT\nDebug DDD\nInfo III\n"; using (var loggerScope = new InternalLoggerScope(true)) { InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; InternalLogger.LogToConsole = true; { StringWriter consoleOutWriter1 = new StringWriter() { NewLine = "\n" }; // Redirect the console output to a StringWriter. loggerScope.SetConsoleOutput(consoleOutWriter1); // Named (based on LogLevel) public methods. InternalLogger.Warn("WWW"); InternalLogger.Error("EEE"); InternalLogger.Fatal("FFF"); InternalLogger.Trace("TTT"); InternalLogger.Debug("DDD"); InternalLogger.Info("III"); TestWriter(expected, consoleOutWriter1); } // // Redirect the console output to another StringWriter. { StringWriter consoleOutWriter2 = new StringWriter() { NewLine = "\n" }; loggerScope.SetConsoleOutput(consoleOutWriter2); // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, "WWW"); InternalLogger.Log(LogLevel.Error, "EEE"); InternalLogger.Log(LogLevel.Fatal, "FFF"); InternalLogger.Log(LogLevel.Trace, "TTT"); InternalLogger.Log(LogLevel.Debug, "DDD"); InternalLogger.Log(LogLevel.Info, "III"); TestWriter(expected, consoleOutWriter2); } //lambdas { StringWriter consoleOutWriter1 = new StringWriter() { NewLine = "\n" }; // Redirect the console output to a StringWriter. loggerScope.SetConsoleOutput(consoleOutWriter1); // Named (based on LogLevel) public methods. InternalLogger.Warn(() => "WWW"); InternalLogger.Error(() => "EEE"); InternalLogger.Fatal(() => "FFF"); InternalLogger.Trace(() => "TTT"); InternalLogger.Debug(() => "DDD"); InternalLogger.Info(() => "III"); TestWriter(expected, consoleOutWriter1); } } } [Fact] public void WriteToConsoleErrorTests() { using (var loggerScope = new InternalLoggerScope(true)) { // Expected result is the same for both types of method invocation. const string expected = "Warn WWW\nError EEE\nFatal FFF\nTrace TTT\nDebug DDD\nInfo III\n"; InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; InternalLogger.LogToConsoleError = true; { StringWriter consoleWriter1 = new StringWriter() { NewLine = "\n" }; // Redirect the console output to a StringWriter. loggerScope.SetConsoleError(consoleWriter1); // Named (based on LogLevel) public methods. InternalLogger.Warn("WWW"); InternalLogger.Error("EEE"); InternalLogger.Fatal("FFF"); InternalLogger.Trace("TTT"); InternalLogger.Debug("DDD"); InternalLogger.Info("III"); TestWriter(expected, loggerScope.ConsoleErrorWriter); } { // // Redirect the console output to another StringWriter. StringWriter consoleWriter2 = new StringWriter() { NewLine = "\n" }; loggerScope.SetConsoleError(consoleWriter2); // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, "WWW"); InternalLogger.Log(LogLevel.Error, "EEE"); InternalLogger.Log(LogLevel.Fatal, "FFF"); InternalLogger.Log(LogLevel.Trace, "TTT"); InternalLogger.Log(LogLevel.Debug, "DDD"); InternalLogger.Log(LogLevel.Info, "III"); TestWriter(expected, loggerScope.ConsoleErrorWriter); } } } [Fact] public void WriteToFileTests() { string expected = "Warn WWW" + Environment.NewLine + "Error EEE" + Environment.NewLine + "Fatal FFF" + Environment.NewLine + "Trace TTT" + Environment.NewLine + "Debug DDD" + Environment.NewLine + "Info III" + Environment.NewLine; var tempFile = Path.GetTempFileName(); try { InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; InternalLogger.LogFile = tempFile; // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, "WWW"); InternalLogger.Log(LogLevel.Error, "EEE"); InternalLogger.Log(LogLevel.Fatal, "FFF"); InternalLogger.Log(LogLevel.Trace, "TTT"); InternalLogger.Log(LogLevel.Debug, "DDD"); InternalLogger.Log(LogLevel.Info, "III"); AssertFileContents(tempFile, expected, Encoding.UTF8); } finally { InternalLogger.Reset(); if (File.Exists(tempFile)) { File.Delete(tempFile); } } } /// <summary> /// <see cref="TimeSource"/> that returns always the same time, /// passed into object constructor. /// </summary> private class FixedTimeSource : TimeSource { private readonly DateTime _time; public FixedTimeSource(DateTime time) { _time = time; } public override DateTime Time => _time; public override DateTime FromSystemTime(DateTime systemTime) { return _time; } } [Fact] public void TimestampTests() { using (new InternalLoggerScope()) { InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = true; StringWriter consoleOutWriter = new StringWriter() { NewLine = ";" }; InternalLogger.LogWriter = consoleOutWriter; // Set fixed time source to test time output TimeSource.Current = new FixedTimeSource(DateTime.Now); // Named (based on LogLevel) public methods. InternalLogger.Warn("WWW"); InternalLogger.Error("EEE"); InternalLogger.Fatal("FFF"); InternalLogger.Trace("TTT"); InternalLogger.Debug("DDD"); InternalLogger.Info("III"); string expectedDateTime = TimeSource.Current.Time.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture); var strings = consoleOutWriter.ToString().Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); foreach (var str in strings) { Assert.Contains(expectedDateTime + ".", str); } } } /// <summary> /// Test exception overloads /// </summary> [Fact] public void ExceptionTests() { using (new InternalLoggerScope()) { InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; var ex1 = new Exception("e1"); var ex2 = new Exception("e2", new Exception("inner")); var ex3 = new NLogConfigurationException("config error"); var ex4 = new NLogConfigurationException("config error", ex2); var ex5 = new PathTooLongException(); ex5.Data["key1"] = "value1"; Exception ex6 = null; const string prefix = " Exception: "; { string expected = "Warn WWW1" + prefix + ex1 + Environment.NewLine + "Error EEE1" + prefix + ex2 + Environment.NewLine + "Fatal FFF1" + prefix + ex3 + Environment.NewLine + "Trace TTT1" + prefix + ex4 + Environment.NewLine + "Debug DDD1" + prefix + ex5 + Environment.NewLine + "Info III1" + Environment.NewLine; StringWriter consoleOutWriter = new StringWriter() { NewLine = Environment.NewLine }; // Redirect the console output to a StringWriter. InternalLogger.LogWriter = consoleOutWriter; // Named (based on LogLevel) public methods. InternalLogger.Warn(ex1, "WWW1"); InternalLogger.Error(ex2, "EEE1"); InternalLogger.Fatal(ex3, "FFF1"); InternalLogger.Trace(ex4, "TTT1"); InternalLogger.Debug(ex5, "DDD1"); InternalLogger.Info(ex6, "III1"); consoleOutWriter.Flush(); var strings = consoleOutWriter.ToString(); Assert.Equal(expected, strings); } { string expected = "Warn WWW2" + prefix + ex1 + Environment.NewLine + "Error EEE2" + prefix + ex2 + Environment.NewLine + "Fatal FFF2" + prefix + ex3 + Environment.NewLine + "Trace TTT2" + prefix + ex4 + Environment.NewLine + "Debug DDD2" + prefix + ex5 + Environment.NewLine + "Info III2" + Environment.NewLine; StringWriter consoleOutWriter = new StringWriter() { NewLine = Environment.NewLine }; // Redirect the console output to a StringWriter. InternalLogger.LogWriter = consoleOutWriter; // Named (based on LogLevel) public methods. InternalLogger.Warn(ex1, () => "WWW2"); InternalLogger.Error(ex2, () => "EEE2"); InternalLogger.Fatal(ex3, () => "FFF2"); InternalLogger.Trace(ex4, () => "TTT2"); InternalLogger.Debug(ex5, () => "DDD2"); InternalLogger.Info(ex6, () => "III2"); consoleOutWriter.Flush(); var strings = consoleOutWriter.ToString(); Assert.Equal(expected, strings); } { string expected = "Warn WWW3" + prefix + ex1 + Environment.NewLine + "Error EEE3" + prefix + ex2 + Environment.NewLine + "Fatal FFF3" + prefix + ex3 + Environment.NewLine + "Trace TTT3" + prefix + ex4 + Environment.NewLine + "Debug DDD3" + prefix + ex5 + Environment.NewLine + "Info III3" + Environment.NewLine; StringWriter consoleOutWriter = new StringWriter() { NewLine = Environment.NewLine }; // Redirect the console output to a StringWriter. InternalLogger.LogWriter = consoleOutWriter; // Named (based on LogLevel) public methods. InternalLogger.Log(ex1, LogLevel.Warn, "WWW3"); InternalLogger.Log(ex2, LogLevel.Error, "EEE3"); InternalLogger.Log(ex3, LogLevel.Fatal, "FFF3"); InternalLogger.Log(ex4, LogLevel.Trace, "TTT3"); InternalLogger.Log(ex5, LogLevel.Debug, "DDD3"); InternalLogger.Log(ex6, LogLevel.Info, "III3"); consoleOutWriter.Flush(); var strings = consoleOutWriter.ToString(); Assert.Equal(expected, strings); } { string expected = "Warn WWW4" + prefix + ex1 + Environment.NewLine + "Error EEE4" + prefix + ex2 + Environment.NewLine + "Fatal FFF4" + prefix + ex3 + Environment.NewLine + "Trace TTT4" + prefix + ex4 + Environment.NewLine + "Debug DDD4" + prefix + ex5 + Environment.NewLine + "Info III4" + Environment.NewLine; StringWriter consoleOutWriter = new StringWriter() { NewLine = Environment.NewLine }; // Redirect the console output to a StringWriter. InternalLogger.LogWriter = consoleOutWriter; // Named (based on LogLevel) public methods. InternalLogger.Log(ex1, LogLevel.Warn, () => "WWW4"); InternalLogger.Log(ex2, LogLevel.Error, () => "EEE4"); InternalLogger.Log(ex3, LogLevel.Fatal, () => "FFF4"); InternalLogger.Log(ex4, LogLevel.Trace, () => "TTT4"); InternalLogger.Log(ex5, LogLevel.Debug, () => "DDD4"); InternalLogger.Log(ex6, LogLevel.Info, () => "III4"); var strings = consoleOutWriter.ToString(); Assert.Equal(expected, strings); } } } [Theory] [InlineData("trace", 6)] [InlineData("debug", 5)] [InlineData("info", 4)] [InlineData("warn", 3)] [InlineData("error", 2)] [InlineData("fatal", 1)] [InlineData("off", 0)] public void TestMinLevelSwitch_log(string rawLogLevel, int count) { Action log = () => { InternalLogger.Log(LogLevel.Fatal, "L1"); InternalLogger.Log(LogLevel.Error, "L2"); InternalLogger.Log(LogLevel.Warn, "L3"); InternalLogger.Log(LogLevel.Info, "L4"); InternalLogger.Log(LogLevel.Debug, "L5"); InternalLogger.Log(LogLevel.Trace, "L6"); }; TestMinLevelSwitch_inner(rawLogLevel, count, log); } [Theory] [InlineData("trace", 6)] [InlineData("debug", 5)] [InlineData("info", 4)] [InlineData("warn", 3)] [InlineData("error", 2)] [InlineData("fatal", 1)] [InlineData("off", 0)] public void TestMinLevelSwitch(string rawLogLevel, int count) { Action log = () => { InternalLogger.Fatal("L1"); InternalLogger.Error("L2"); InternalLogger.Warn("L3"); InternalLogger.Info("L4"); InternalLogger.Debug("L5"); InternalLogger.Trace("L6"); }; TestMinLevelSwitch_inner(rawLogLevel, count, log); } [Theory] [InlineData("trace", 6)] [InlineData("debug", 5)] [InlineData("info", 4)] [InlineData("warn", 3)] [InlineData("error", 2)] [InlineData("fatal", 1)] [InlineData("off", 0)] public void TestMinLevelSwitch_lambda(string rawLogLevel, int count) { Action log = () => { InternalLogger.Fatal(() => "L1"); InternalLogger.Error(() => "L2"); InternalLogger.Warn(() => "L3"); InternalLogger.Info(() => "L4"); InternalLogger.Debug(() => "L5"); InternalLogger.Trace(() => "L6"); }; TestMinLevelSwitch_inner(rawLogLevel, count, log); } private static void TestMinLevelSwitch_inner(string rawLogLevel, int count, Action log) { try { //set minimal InternalLogger.LogLevel = LogLevel.FromString(rawLogLevel); InternalLogger.IncludeTimestamp = false; StringWriter consoleOutWriter = new StringWriter() { NewLine = ";" }; InternalLogger.LogWriter = consoleOutWriter; var expected = ""; var logLevel = LogLevel.Fatal.Ordinal; for (int i = 0; i < count; i++, logLevel--) { expected += LogLevel.FromOrdinal(logLevel) + " L" + (i + 1) + ";"; } log(); var strings = consoleOutWriter.ToString(); Assert.Equal(expected, strings); } finally { InternalLogger.Reset(); } } [Theory] [InlineData("trace", true)] [InlineData("debug", true)] [InlineData("info", true)] [InlineData("warn", true)] [InlineData("error", true)] [InlineData("fatal", true)] [InlineData("off", false)] public void CreateDirectoriesIfNeededTests(string rawLogLevel, bool shouldCreateDirectory) { var tempPath = Path.GetTempPath(); var tempFileName = Path.GetRandomFileName(); var randomSubDirectory = Path.Combine(tempPath, Path.GetRandomFileName()); string tempFile = Path.Combine(randomSubDirectory, tempFileName); try { InternalLogger.LogLevel = LogLevel.FromString(rawLogLevel); InternalLogger.IncludeTimestamp = false; if (Directory.Exists(randomSubDirectory)) { Directory.Delete(randomSubDirectory); } Assert.False(Directory.Exists(randomSubDirectory)); // Set the log file, which will only create the needed directories InternalLogger.LogFile = tempFile; Assert.Equal(Directory.Exists(randomSubDirectory), shouldCreateDirectory); Assert.False(File.Exists(tempFile)); InternalLogger.Log(LogLevel.FromString(rawLogLevel), "File and Directory created."); Assert.Equal(File.Exists(tempFile), shouldCreateDirectory); } finally { InternalLogger.Reset(); if (File.Exists(tempFile)) { File.Delete(tempFile); } if (Directory.Exists(randomSubDirectory)) { Directory.Delete(randomSubDirectory); } } } [Fact] public void CreateFileInCurrentDirectoryTests() { string expected = "Warn WWW" + Environment.NewLine + "Error EEE" + Environment.NewLine + "Fatal FFF" + Environment.NewLine + "Trace TTT" + Environment.NewLine + "Debug DDD" + Environment.NewLine + "Info III" + Environment.NewLine; // Store off the previous log file string previousLogFile = InternalLogger.LogFile; var tempFileName = Path.GetRandomFileName(); try { InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; Assert.False(File.Exists(tempFileName)); // Set the log file, which only has a filename InternalLogger.LogFile = tempFileName; Assert.False(File.Exists(tempFileName)); // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, "WWW"); InternalLogger.Log(LogLevel.Error, "EEE"); InternalLogger.Log(LogLevel.Fatal, "FFF"); InternalLogger.Log(LogLevel.Trace, "TTT"); InternalLogger.Log(LogLevel.Debug, "DDD"); InternalLogger.Log(LogLevel.Info, "III"); AssertFileContents(tempFileName, expected, Encoding.UTF8); Assert.True(File.Exists(tempFileName)); } finally { InternalLogger.Reset(); if (File.Exists(tempFileName)) { File.Delete(tempFileName); } } } [Fact] public void TestReceivedLogEventTest() { using (var loggerScope = new InternalLoggerScope()) { // Arrange var receivedArgs = new List<InternalLoggerMessageEventArgs>(); var logFactory = new LogFactory(); logFactory.Setup().SetupInternalLogger(s => { EventHandler<InternalLoggerMessageEventArgs> eventHandler = (sender, e) => receivedArgs.Add(e); s.AddLogSubscription(eventHandler); s.RemoveLogSubscription(eventHandler); s.AddLogSubscription(eventHandler); }); var exception = new Exception(); // Act InternalLogger.Info(exception, "Hello {0}", "it's me!"); // Assert Assert.Single(receivedArgs); var logEventArgs = receivedArgs.Single(); Assert.Equal(LogLevel.Info, logEventArgs.Level); Assert.Equal(exception, logEventArgs.Exception); Assert.Equal("Hello it's me!", logEventArgs.Message); } } [Fact] public void TestReceivedLogEventThrowingTest() { using (var loggerScope = new InternalLoggerScope()) { // Arrange var receivedArgs = new List<InternalLoggerMessageEventArgs>(); InternalLogger.LogMessageReceived += (sender, e) => { receivedArgs.Add(e); throw new ApplicationException("I'm a bad programmer"); }; var exception = new Exception(); // Act InternalLogger.Info(exception, "Hello {0}", "it's me!"); // Assert Assert.Single(receivedArgs); var logEventArgs = receivedArgs.Single(); Assert.Equal(LogLevel.Info, logEventArgs.Level); Assert.Equal(exception, logEventArgs.Exception); Assert.Equal("Hello it's me!", logEventArgs.Message); } } [Fact] public void TestReceivedLogEventContextTest() { using (var loggerScope = new InternalLoggerScope()) { // Arrange var targetContext = new NLog.Targets.DebugTarget() { Name = "Ugly" }; var receivedArgs = new List<InternalLoggerMessageEventArgs>(); InternalLogger.LogMessageReceived += (sender, e) => { receivedArgs.Add(e); }; var exception = new Exception(); // Act NLog.Internal.ExceptionHelper.MustBeRethrown(exception, targetContext); // Assert Assert.Single(receivedArgs); var logEventArgs = receivedArgs.Single(); Assert.Equal(LogLevel.Error, logEventArgs.Level); Assert.Equal(exception, logEventArgs.Exception); Assert.Equal(targetContext.GetType(), logEventArgs.SenderType); } } public void Dispose() { TimeSource.Current = new FastLocalTimeSource(); InternalLogger.Reset(); } } }
//////////////////////////////////////////////////////////////// // // // Neoforce Controls // // // //////////////////////////////////////////////////////////////// // // // File: TrackBar.cs // // // // Version: 0.7 // // // // Date: 11/09/2010 // // // // Author: Tom Shane // // // //////////////////////////////////////////////////////////////// // // // Copyright (c) by Tom Shane // // // //////////////////////////////////////////////////////////////// #region //// Using ///////////// using Microsoft.Xna.Framework; //////////////////////////////////////////////////////////////////////////// using Microsoft.Xna.Framework.Graphics; using System; //////////////////////////////////////////////////////////////////////////// #endregion namespace TomShane.Neoforce.Controls { public class TrackBar: Control { #region //// Fields //////////// //////////////////////////////////////////////////////////////////////////// private int range = 100; private int value = 0; private int stepSize = 1; private int pageSize = 5; private bool scale = true; private Button btnSlider; //////////////////////////////////////////////////////////////////////////// #endregion #region //// Properties //////// //////////////////////////////////////////////////////////////////////////// public virtual int Value { get { return this.value; } set { if (this.value != value) { this.value = value; if (this.value < 0) this.value = 0; if (this.value > range) this.value = range; Invalidate(); if (!Suspended) OnValueChanged(new EventArgs()); } } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual int Range { get { return range; } set { if (range != value) { range = value; range = value; if (pageSize > range) pageSize = range; RecalcParams(); if (!Suspended) OnRangeChanged(new EventArgs()); } } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual int PageSize { get { return pageSize; } set { if (pageSize != value) { pageSize = value; if (pageSize > range) pageSize = range; RecalcParams(); if (!Suspended) OnPageSizeChanged(new EventArgs()); } } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual int StepSize { get { return stepSize; } set { if (stepSize != value) { stepSize = value; if (stepSize > range) stepSize = range; if (!Suspended) OnStepSizeChanged(new EventArgs()); } } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual bool Scale { get { return scale; } set { scale = value; } } //////////////////////////////////////////////////////////////////////////// #endregion #region //// Events //////////// //////////////////////////////////////////////////////////////////////////// public event EventHandler ValueChanged; public event EventHandler RangeChanged; public event EventHandler StepSizeChanged; public event EventHandler PageSizeChanged; //////////////////////////////////////////////////////////////////////////// #endregion #region //// Construstors ////// //////////////////////////////////////////////////////////////////////////// public TrackBar(Manager manager): base(manager) { Width = 64; Height = 20; CanFocus = false; btnSlider = new Button(Manager); btnSlider.Init(); btnSlider.Text = ""; btnSlider.CanFocus = true; btnSlider.Parent = this; btnSlider.Anchor = Anchors.Left | Anchors.Top | Anchors.Bottom; btnSlider.Detached = true; btnSlider.Movable = true; btnSlider.Move += new MoveEventHandler(btnSlider_Move); btnSlider.KeyPress += new KeyEventHandler(btnSlider_KeyPress); btnSlider.GamePadPress += new GamePadEventHandler(btnSlider_GamePadPress); } //////////////////////////////////////////////////////////////////////////// #endregion #region //// Methods /////////// //////////////////////////////////////////////////////////////////////////// public override void Init() { base.Init(); btnSlider.Skin = new SkinControl(Manager.Skin.Controls["TrackBar.Button"]); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected internal override void InitSkin() { base.InitSkin(); Skin = new SkinControl(Manager.Skin.Controls["TrackBar"]); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected override void DrawControl(Renderer renderer, Rectangle rect, GameTime gameTime) { RecalcParams(); SkinLayer p = Skin.Layers["Control"]; SkinLayer l = Skin.Layers["Scale"]; float ratio = 0.66f; int h = (int)(ratio * rect.Height); int t = rect.Top + (Height - h) / 2; float px = ((float)value / (float)range); int w = (int)Math.Ceiling(px * (rect.Width - p.ContentMargins.Horizontal - btnSlider.Width)) + 2; if (w < l.SizingMargins.Vertical) w = l.SizingMargins.Vertical; if (w > rect.Width - p.ContentMargins.Horizontal) w = rect.Width - p.ContentMargins.Horizontal; Rectangle r1 = new Rectangle(rect.Left + p.ContentMargins.Left, t + p.ContentMargins.Top, w, h - p.ContentMargins.Vertical); base.DrawControl(renderer, new Rectangle(rect.Left, t, rect.Width, h), gameTime); if (scale) renderer.DrawLayer(this, l, r1); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// void btnSlider_Move(object sender, MoveEventArgs e) { SkinLayer p = Skin.Layers["Control"]; int size = btnSlider.Width; int w = Width - p.ContentMargins.Horizontal - size; int pos = e.Left; if (pos < p.ContentMargins.Left) pos = p.ContentMargins.Left; if (pos > w + p.ContentMargins.Left) pos = w + p.ContentMargins.Left; btnSlider.SetPosition(pos, 0); float px = (float)range / (float)w; Value = (int)(Math.Ceiling((pos - p.ContentMargins.Left) * px)); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// private void RecalcParams() { if (btnSlider != null) { if (btnSlider.Width > 12) { btnSlider.Glyph = new Glyph(Manager.Skin.Images["Shared.Glyph"].Resource); btnSlider.Glyph.SizeMode = SizeMode.Centered; } else { btnSlider.Glyph = null; } SkinLayer p = Skin.Layers["Control"]; btnSlider.Width = (int)(Height * 0.8); btnSlider.Height = Height; int size = btnSlider.Width; int w = Width - p.ContentMargins.Horizontal - size; float px = (float)range / (float)w; int pos = p.ContentMargins.Left + (int)(Math.Ceiling(Value / (float)px)); if (pos < p.ContentMargins.Left) pos = p.ContentMargins.Left; if (pos > w + p.ContentMargins.Left) pos = w + p.ContentMargins.Left; btnSlider.SetPosition(pos, 0); } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected override void OnMousePress(MouseEventArgs e) { base.OnMouseDown(e); if (e.Button == MouseButton.Left) { int pos = e.Position.X; if (pos < btnSlider.Left) { Value -= pageSize; } else if (pos >= btnSlider.Left + btnSlider.Width) { Value += pageSize; } } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// void btnSlider_GamePadPress(object sender, GamePadEventArgs e) { if (e.Button == GamePadActions.Left || e.Button == GamePadActions.Down) Value -= stepSize; if (e.Button == GamePadActions.Right || e.Button == GamePadActions.Up) Value += stepSize; } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// void btnSlider_KeyPress(object sender, KeyEventArgs e) { if (e.Key == Microsoft.Xna.Framework.Input.Keys.Left || e.Key == Microsoft.Xna.Framework.Input.Keys.Down) Value -= stepSize; else if (e.Key == Microsoft.Xna.Framework.Input.Keys.Right || e.Key == Microsoft.Xna.Framework.Input.Keys.Up) Value += stepSize; else if (e.Key == Microsoft.Xna.Framework.Input.Keys.PageDown) Value -= pageSize; else if (e.Key == Microsoft.Xna.Framework.Input.Keys.PageUp) Value += pageSize; else if (e.Key == Microsoft.Xna.Framework.Input.Keys.Home) Value = 0; else if (e.Key == Microsoft.Xna.Framework.Input.Keys.End) Value = Range; } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected override void OnResize(ResizeEventArgs e) { base.OnResize(e); RecalcParams(); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected virtual void OnValueChanged(EventArgs e) { if (ValueChanged != null) ValueChanged.Invoke(this, e); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected virtual void OnRangeChanged(EventArgs e) { if (RangeChanged != null) RangeChanged.Invoke(this, e); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected virtual void OnPageSizeChanged(EventArgs e) { if (PageSizeChanged != null) PageSizeChanged.Invoke(this, e); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected virtual void OnStepSizeChanged(EventArgs e) { if (StepSizeChanged != null) StepSizeChanged.Invoke(this, e); } //////////////////////////////////////////////////////////////////////////// #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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // Types for awaiting Task and Task<T>. These types are emitted from Task{<T>}.GetAwaiter // and Task{<T>}.ConfigureAwait. They are meant to be used only by the compiler, e.g. // // await nonGenericTask; // ===================== // var $awaiter = nonGenericTask.GetAwaiter(); // if (!$awaiter.IsCompleted) // { // SPILL: // $builder.AwaitUnsafeOnCompleted(ref $awaiter, ref this); // return; // Label: // UNSPILL; // } // $awaiter.GetResult(); // // result += await genericTask.ConfigureAwait(false); // =================================================================================== // var $awaiter = genericTask.ConfigureAwait(false).GetAwaiter(); // if (!$awaiter.IsCompleted) // { // SPILL; // $builder.AwaitUnsafeOnCompleted(ref $awaiter, ref this); // return; // Label: // UNSPILL; // } // result += $awaiter.GetResult(); // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.Tracing; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; // NOTE: For performance reasons, initialization is not verified. If a developer // incorrectly initializes a task awaiter, which should only be done by the compiler, // NullReferenceExceptions may be generated (the alternative would be for us to detect // this case and then throw a different exception instead). This is the same tradeoff // that's made with other compiler-focused value types like List<T>.Enumerator. namespace System.Runtime.CompilerServices { /// <summary>Provides an awaiter for awaiting a <see cref="System.Threading.Tasks.Task"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> public readonly struct TaskAwaiter : ICriticalNotifyCompletion, ITaskAwaiter { // WARNING: Unsafe.As is used to access the generic TaskAwaiter<> as TaskAwaiter. // Its layout must remain the same. /// <summary>The task being awaited.</summary> internal readonly Task m_task; /// <summary>Initializes the <see cref="TaskAwaiter"/>.</summary> /// <param name="task">The <see cref="System.Threading.Tasks.Task"/> to be awaited.</param> internal TaskAwaiter(Task task) { Debug.Assert(task != null, "Constructing an awaiter requires a task to await."); m_task = task; } /// <summary>Gets whether the task being awaited is completed.</summary> /// <remarks>This property is intended for compiler user rather than use directly in code.</remarks> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> public bool IsCompleted => m_task.IsCompleted; /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.InvalidOperationException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void OnCompleted(Action continuation) { OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: true); } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.InvalidOperationException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void UnsafeOnCompleted(Action continuation) { OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: false); } /// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task"/>.</summary> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <exception cref="System.Threading.Tasks.TaskCanceledException">The task was canceled.</exception> /// <exception cref="System.Exception">The task completed in a Faulted state.</exception> [StackTraceHidden] public void GetResult() { ValidateEnd(m_task); } /// <summary> /// Fast checks for the end of an await operation to determine whether more needs to be done /// prior to completing the await. /// </summary> /// <param name="task">The awaited task.</param> [StackTraceHidden] internal static void ValidateEnd(Task task) { // Fast checks that can be inlined. if (task.IsWaitNotificationEnabledOrNotRanToCompletion) { // If either the end await bit is set or we're not completed successfully, // fall back to the slower path. HandleNonSuccessAndDebuggerNotification(task); } } /// <summary> /// Ensures the task is completed, triggers any necessary debugger breakpoints for completing /// the await on the task, and throws an exception if the task did not complete successfully. /// </summary> /// <param name="task">The awaited task.</param> [StackTraceHidden] private static void HandleNonSuccessAndDebuggerNotification(Task task) { // NOTE: The JIT refuses to inline ValidateEnd when it contains the contents // of HandleNonSuccessAndDebuggerNotification, hence the separation. // Synchronously wait for the task to complete. When used by the compiler, // the task will already be complete. This code exists only for direct GetResult use, // for cases where the same exception propagation semantics used by "await" are desired, // but where for one reason or another synchronous rather than asynchronous waiting is needed. if (!task.IsCompleted) { bool taskCompleted = task.InternalWait(Timeout.Infinite, default); Debug.Assert(taskCompleted, "With an infinite timeout, the task should have always completed."); } // Now that we're done, alert the debugger if so requested task.NotifyDebuggerOfWaitCompletionIfNecessary(); // And throw an exception if the task is faulted or canceled. if (!task.IsCompletedSuccessfully) ThrowForNonSuccess(task); } /// <summary>Throws an exception to handle a task that completed in a state other than RanToCompletion.</summary> [StackTraceHidden] private static void ThrowForNonSuccess(Task task) { Debug.Assert(task.IsCompleted, "Task must have been completed by now."); Debug.Assert(task.Status != TaskStatus.RanToCompletion, "Task should not be completed successfully."); // Handle whether the task has been canceled or faulted switch (task.Status) { // If the task completed in a canceled state, throw an OperationCanceledException. // This will either be the OCE that actually caused the task to cancel, or it will be a new // TaskCanceledException. TCE derives from OCE, and by throwing it we automatically pick up the // completed task's CancellationToken if it has one, including that CT in the OCE. case TaskStatus.Canceled: ExceptionDispatchInfo? oceEdi = task.GetCancellationExceptionDispatchInfo(); if (oceEdi != null) { oceEdi.Throw(); Debug.Fail("Throw() should have thrown"); } throw new TaskCanceledException(task); // If the task faulted, throw its first exception, // even if it contained more than one. case TaskStatus.Faulted: ReadOnlyCollection<ExceptionDispatchInfo> edis = task.GetExceptionDispatchInfos(); if (edis.Count > 0) { edis[0].Throw(); Debug.Fail("Throw() should have thrown"); break; // Necessary to compile: non-reachable, but compiler can't determine that } else { Debug.Fail("There should be exceptions if we're Faulted."); throw task.Exception!; } } } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="task">The task being awaited.</param> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <param name="continueOnCapturedContext">Whether to capture and marshal back to the current context.</param> /// <param name="flowExecutionContext">Whether to flow ExecutionContext across the await.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> internal static void OnCompletedInternal(Task task, Action continuation, bool continueOnCapturedContext, bool flowExecutionContext) { if (continuation == null) throw new ArgumentNullException(nameof(continuation)); // If TaskWait* ETW events are enabled, trace a beginning event for this await // and set up an ending event to be traced when the asynchronous await completes. if (TplEventSource.Log.IsEnabled() || Task.s_asyncDebuggingEnabled) { continuation = OutputWaitEtwEvents(task, continuation); } // Set the continuation onto the awaited task. task.SetContinuationForAwait(continuation, continueOnCapturedContext, flowExecutionContext); } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="task">The task being awaited.</param> /// <param name="stateMachineBox">The box to invoke when the await operation completes.</param> /// <param name="continueOnCapturedContext">Whether to capture and marshal back to the current context.</param> internal static void UnsafeOnCompletedInternal(Task task, IAsyncStateMachineBox stateMachineBox, bool continueOnCapturedContext) { Debug.Assert(stateMachineBox != null); // If TaskWait* ETW events are enabled, trace a beginning event for this await // and set up an ending event to be traced when the asynchronous await completes. if (TplEventSource.Log.IsEnabled() || Task.s_asyncDebuggingEnabled) { task.SetContinuationForAwait(OutputWaitEtwEvents(task, stateMachineBox.MoveNextAction), continueOnCapturedContext, flowExecutionContext: false); } else { task.UnsafeSetContinuationForAwait(stateMachineBox, continueOnCapturedContext); } } /// <summary> /// Outputs a WaitBegin ETW event, and augments the continuation action to output a WaitEnd ETW event. /// </summary> /// <param name="task">The task being awaited.</param> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <returns>The action to use as the actual continuation.</returns> private static Action OutputWaitEtwEvents(Task task, Action continuation) { Debug.Assert(task != null, "Need a task to wait on"); Debug.Assert(continuation != null, "Need a continuation to invoke when the wait completes"); if (Task.s_asyncDebuggingEnabled) { Task.AddToActiveTasks(task); } TplEventSource log = TplEventSource.Log; if (log.IsEnabled()) { // ETW event for Task Wait Begin Task? currentTaskAtBegin = Task.InternalCurrent; // If this task's continuation is another task, get it. Task? continuationTask = AsyncMethodBuilderCore.TryGetContinuationTask(continuation); log.TaskWaitBegin( currentTaskAtBegin != null ? currentTaskAtBegin.m_taskScheduler!.Id : TaskScheduler.Default.Id, currentTaskAtBegin != null ? currentTaskAtBegin.Id : 0, task.Id, TplEventSource.TaskWaitBehavior.Asynchronous, continuationTask != null ? continuationTask.Id : 0); } // Create a continuation action that outputs the end event and then invokes the user // provided delegate. This incurs the allocations for the closure/delegate, but only if the event // is enabled, and in doing so it allows us to pass the awaited task's information into the end event // in a purely pay-for-play manner (the alternatively would be to increase the size of TaskAwaiter // just for this ETW purpose, not pay-for-play, since GetResult would need to know whether a real yield occurred). return AsyncMethodBuilderCore.CreateContinuationWrapper(continuation, (innerContinuation, innerTask) => { if (Task.s_asyncDebuggingEnabled) { Task.RemoveFromActiveTasks(innerTask); } TplEventSource innerEtwLog = TplEventSource.Log; // ETW event for Task Wait End. Guid prevActivityId = new Guid(); bool bEtwLogEnabled = innerEtwLog.IsEnabled(); if (bEtwLogEnabled) { Task? currentTaskAtEnd = Task.InternalCurrent; innerEtwLog.TaskWaitEnd( currentTaskAtEnd != null ? currentTaskAtEnd.m_taskScheduler!.Id : TaskScheduler.Default.Id, currentTaskAtEnd != null ? currentTaskAtEnd.Id : 0, innerTask.Id); // Ensure the continuation runs under the activity ID of the task that completed for the // case the antecedent is a promise (in the other cases this is already the case). if (innerEtwLog.TasksSetActivityIds && (innerTask.Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0) EventSource.SetCurrentThreadActivityId(TplEventSource.CreateGuidForTaskID(innerTask.Id), out prevActivityId); } // Invoke the original continuation provided to OnCompleted. innerContinuation(); if (bEtwLogEnabled) { innerEtwLog.TaskWaitContinuationComplete(innerTask.Id); if (innerEtwLog.TasksSetActivityIds && (innerTask.Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0) EventSource.SetCurrentThreadActivityId(prevActivityId); } }, task); } } /// <summary>Provides an awaiter for awaiting a <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> public readonly struct TaskAwaiter<TResult> : ICriticalNotifyCompletion, ITaskAwaiter { // WARNING: Unsafe.As is used to access TaskAwaiter<> as the non-generic TaskAwaiter. // Its layout must remain the same. /// <summary>The task being awaited.</summary> private readonly Task<TResult> m_task; /// <summary>Initializes the <see cref="TaskAwaiter{TResult}"/>.</summary> /// <param name="task">The <see cref="System.Threading.Tasks.Task{TResult}"/> to be awaited.</param> internal TaskAwaiter(Task<TResult> task) { Debug.Assert(task != null, "Constructing an awaiter requires a task to await."); m_task = task; } /// <summary>Gets whether the task being awaited is completed.</summary> /// <remarks>This property is intended for compiler user rather than use directly in code.</remarks> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> public bool IsCompleted => m_task.IsCompleted; /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void OnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: true); } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void UnsafeOnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: false); } /// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary> /// <returns>The result of the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</returns> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <exception cref="System.Threading.Tasks.TaskCanceledException">The task was canceled.</exception> /// <exception cref="System.Exception">The task completed in a Faulted state.</exception> [StackTraceHidden] public TResult GetResult() { TaskAwaiter.ValidateEnd(m_task); return m_task.ResultOnSuccess; } } /// <summary> /// Marker interface used to know whether a particular awaiter is either a /// TaskAwaiter or a TaskAwaiter`1. It must not be implemented by any other /// awaiters. /// </summary> internal interface ITaskAwaiter { } /// <summary> /// Marker interface used to know whether a particular awaiter is either a /// CTA.ConfiguredTaskAwaiter or a CTA`1.ConfiguredTaskAwaiter. It must not /// be implemented by any other awaiters. /// </summary> internal interface IConfiguredTaskAwaiter { } /// <summary>Provides an awaitable object that allows for configured awaits on <see cref="System.Threading.Tasks.Task"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> public readonly struct ConfiguredTaskAwaitable { /// <summary>The task being awaited.</summary> private readonly ConfiguredTaskAwaitable.ConfiguredTaskAwaiter m_configuredTaskAwaiter; /// <summary>Initializes the <see cref="ConfiguredTaskAwaitable"/>.</summary> /// <param name="task">The awaitable <see cref="System.Threading.Tasks.Task"/>.</param> /// <param name="continueOnCapturedContext"> /// true to attempt to marshal the continuation back to the original context captured; otherwise, false. /// </param> internal ConfiguredTaskAwaitable(Task task, bool continueOnCapturedContext) { Debug.Assert(task != null, "Constructing an awaitable requires a task to await."); m_configuredTaskAwaiter = new ConfiguredTaskAwaitable.ConfiguredTaskAwaiter(task, continueOnCapturedContext); } /// <summary>Gets an awaiter for this awaitable.</summary> /// <returns>The awaiter.</returns> public ConfiguredTaskAwaitable.ConfiguredTaskAwaiter GetAwaiter() { return m_configuredTaskAwaiter; } /// <summary>Provides an awaiter for a <see cref="ConfiguredTaskAwaitable"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> public readonly struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion, IConfiguredTaskAwaiter { // WARNING: Unsafe.As is used to access the generic ConfiguredTaskAwaiter as this. // Its layout must remain the same. /// <summary>The task being awaited.</summary> internal readonly Task m_task; /// <summary>Whether to attempt marshaling back to the original context.</summary> internal readonly bool m_continueOnCapturedContext; /// <summary>Initializes the <see cref="ConfiguredTaskAwaiter"/>.</summary> /// <param name="task">The <see cref="System.Threading.Tasks.Task"/> to await.</param> /// <param name="continueOnCapturedContext"> /// true to attempt to marshal the continuation back to the original context captured /// when BeginAwait is called; otherwise, false. /// </param> internal ConfiguredTaskAwaiter(Task task, bool continueOnCapturedContext) { Debug.Assert(task != null, "Constructing an awaiter requires a task to await."); m_task = task; m_continueOnCapturedContext = continueOnCapturedContext; } /// <summary>Gets whether the task being awaited is completed.</summary> /// <remarks>This property is intended for compiler user rather than use directly in code.</remarks> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> public bool IsCompleted => m_task.IsCompleted; /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void OnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: true); } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void UnsafeOnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: false); } /// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task"/>.</summary> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <exception cref="System.Threading.Tasks.TaskCanceledException">The task was canceled.</exception> /// <exception cref="System.Exception">The task completed in a Faulted state.</exception> [StackTraceHidden] public void GetResult() { TaskAwaiter.ValidateEnd(m_task); } } } /// <summary>Provides an awaitable object that allows for configured awaits on <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> public readonly struct ConfiguredTaskAwaitable<TResult> { /// <summary>The underlying awaitable on whose logic this awaitable relies.</summary> private readonly ConfiguredTaskAwaitable<TResult>.ConfiguredTaskAwaiter m_configuredTaskAwaiter; /// <summary>Initializes the <see cref="ConfiguredTaskAwaitable{TResult}"/>.</summary> /// <param name="task">The awaitable <see cref="System.Threading.Tasks.Task{TResult}"/>.</param> /// <param name="continueOnCapturedContext"> /// true to attempt to marshal the continuation back to the original context captured; otherwise, false. /// </param> internal ConfiguredTaskAwaitable(Task<TResult> task, bool continueOnCapturedContext) { m_configuredTaskAwaiter = new ConfiguredTaskAwaitable<TResult>.ConfiguredTaskAwaiter(task, continueOnCapturedContext); } /// <summary>Gets an awaiter for this awaitable.</summary> /// <returns>The awaiter.</returns> public ConfiguredTaskAwaitable<TResult>.ConfiguredTaskAwaiter GetAwaiter() { return m_configuredTaskAwaiter; } /// <summary>Provides an awaiter for a <see cref="ConfiguredTaskAwaitable{TResult}"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> public readonly struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion, IConfiguredTaskAwaiter { // WARNING: Unsafe.As is used to access this as the non-generic ConfiguredTaskAwaiter. // Its layout must remain the same. /// <summary>The task being awaited.</summary> private readonly Task<TResult> m_task; /// <summary>Whether to attempt marshaling back to the original context.</summary> private readonly bool m_continueOnCapturedContext; /// <summary>Initializes the <see cref="ConfiguredTaskAwaiter"/>.</summary> /// <param name="task">The awaitable <see cref="System.Threading.Tasks.Task{TResult}"/>.</param> /// <param name="continueOnCapturedContext"> /// true to attempt to marshal the continuation back to the original context captured; otherwise, false. /// </param> internal ConfiguredTaskAwaiter(Task<TResult> task, bool continueOnCapturedContext) { Debug.Assert(task != null, "Constructing an awaiter requires a task to await."); m_task = task; m_continueOnCapturedContext = continueOnCapturedContext; } /// <summary>Gets whether the task being awaited is completed.</summary> /// <remarks>This property is intended for compiler user rather than use directly in code.</remarks> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> public bool IsCompleted => m_task.IsCompleted; /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void OnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: true); } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void UnsafeOnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: false); } /// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary> /// <returns>The result of the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</returns> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <exception cref="System.Threading.Tasks.TaskCanceledException">The task was canceled.</exception> /// <exception cref="System.Exception">The task completed in a Faulted state.</exception> [StackTraceHidden] public TResult GetResult() { TaskAwaiter.ValidateEnd(m_task); return m_task.ResultOnSuccess; } } } }